text
stringlengths
1
1.05M
<reponame>lgoldstein/communitychest<gh_stars>1-10 /* * */ package net.community.chest.swing.component.table; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.List; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; /** * <P>Copyright GPLv2</P> * * @author <NAME>. * @since Mar 22, 2009 9:40:40 AM */ public final class TableUtil { private TableUtil () { // no instance } /** * @param <TC> Type of {@link TableColumn} being processed * @param colIndex The column <U>model index</U> * @param cols A {@link Collection} of table columns to be scanned * @return The first column whose {@link TableColumn#getModelIndex()} * matches the required one - <code>null</code> if no match found */ public static final <TC extends TableColumn> TC findTableColumn (final int colIndex, final Collection<? extends TC> cols) { if ((null == cols) || (cols.size() <= 0)) return null; for (final TC tc : cols) { if ((tc != null) && (tc.getModelIndex() == colIndex)) return tc; } return null; } public static final <TC extends TableColumn> TC findTableColumn (final int colIndex, final TC ... cols) { return ((null == cols) || (cols.length <= 0)) ? null : findTableColumn(colIndex, Arrays.asList(cols)); } public static final TableColumn findTableColumn ( final int colIndex, final TableColumnModel tcModel) { for (final Enumeration<? extends TableColumn> cols= (null == tcModel) ? null : tcModel.getColumns(); (cols != null) && cols.hasMoreElements(); ) { final TableColumn tc=cols.nextElement(); if ((tc != null) && (tc.getModelIndex() == colIndex)) return tc; } return null; } /** * @param <V> Type of expected value * @param tbl The {@link JTable} instance to query * @param model The model values to be used after calling * {@link JTable#convertRowIndexToModel(int)} * @return A {@link List} of the selected values - null/empty if no/bad * selection */ public static final <V> List<V> getSelectedValues ( final JTable tbl, final List<? extends V> model) { final int selCount=(null == tbl) ? 0 : tbl.getSelectedRowCount(); if (selCount <= 0) return null; final ListSelectionModel sm=tbl.getSelectionModel(); final int selMode= (null == sm) ? (-1) : sm.getSelectionMode(); final int[] selRows; switch(selMode) { case ListSelectionModel.SINGLE_SELECTION : selRows = new int[] { tbl.getSelectedRow() }; break; case ListSelectionModel.MULTIPLE_INTERVAL_SELECTION : case ListSelectionModel.SINGLE_INTERVAL_SELECTION : selRows = tbl.getSelectedRows(); break; default : return null; // should not happen } if ((null == selRows) || (selRows.length <= 0)) return null; // should not happen final int numItems=(null == model) ? 0 : model.size(); if (numItems <= 0) return null; // should not happen List<V> ret=null; for (final int rIndex : selRows) { final int mdlIndex=(rIndex < 0) ? (-1) : tbl.convertRowIndexToModel(rIndex); final V v= ((mdlIndex < 0) || (mdlIndex >= numItems)) ? null : model.get(mdlIndex); if (null == v) // should not happen continue; if (null == ret) ret = new ArrayList<V>(selRows.length); ret.add(v); } return ret; } }
#!/bin/bash set -e PROJECT_ROOT="$(dirname "$(readlink -e "$0")")/../../.." CONTRIB="$PROJECT_ROOT/contrib" DISTDIR="$PROJECT_ROOT/dist" BUILDDIR="$CONTRIB/build-linux/appimage/build/appimage" APPDIR="$BUILDDIR/Electron-Cash.AppDir" CACHEDIR="$CONTRIB/build-linux/appimage/.cache/appimage" # pinned versions SQUASHFSKIT_COMMIT="ae0d656efa2d0df2fcac795b6823b44462f19386" PKG2APPIMAGE_COMMIT="eb8f3acdd9f11ab19b78f5cb15daa772367daf15" VERSION=`git describe --tags --dirty --always` APPIMAGE="$DISTDIR/Electron-Cash-$VERSION-x86_64.AppImage" rm -rf "$BUILDDIR" mkdir -p "$APPDIR" "$CACHEDIR" "$DISTDIR" . "$CONTRIB"/base.sh info "Refreshing submodules ..." git submodule update --init info "downloading some dependencies." download_if_not_exist "$CACHEDIR/functions.sh" "https://raw.githubusercontent.com/AppImage/pkg2appimage/$PKG2APPIMAGE_COMMIT/functions.sh" verify_hash "$CACHEDIR/functions.sh" "78b7ee5a04ffb84ee1c93f0cb2900123773bc6709e5d1e43c37519f590f86918" download_if_not_exist "$CACHEDIR/appimagetool" "https://github.com/AppImage/AppImageKit/releases/download/12/appimagetool-x86_64.AppImage" verify_hash "$CACHEDIR/appimagetool" "d918b4df547b388ef253f3c9e7f6529ca81a885395c31f619d9aaf7030499a13" download_if_not_exist "$CACHEDIR/Python-$PYTHON_VERSION.tar.xz" "https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz" verify_hash "$CACHEDIR/Python-$PYTHON_VERSION.tar.xz" $PYTHON_SRC_TARBALL_HASH download_if_not_exist "$CACHEDIR/libQt5MultimediaGstTools.so.5.11.3.xz" "https://github.com/cculianu/Electron-Cash-Build-Tools/releases/download/v1.0/libQt5MultimediaGstTools.so.5.11.3.xz" verify_hash "$CACHEDIR/libQt5MultimediaGstTools.so.5.11.3.xz" "12fbf50f7f5f3fd6b49a8e757846253ae658e96f132956fdcd7107c81b55d819" info "Building Python" tar xf "$CACHEDIR/Python-$PYTHON_VERSION.tar.xz" -C "$BUILDDIR" ( cd "$BUILDDIR/Python-$PYTHON_VERSION" export SOURCE_DATE_EPOCH=1530212462 LC_ALL=C export BUILD_DATE=$(date -u -d "@$SOURCE_DATE_EPOCH" "+%b %d %Y") LC_ALL=C export BUILD_TIME=$(date -u -d "@$SOURCE_DATE_EPOCH" "+%H:%M:%S") # Patch taken from Ubuntu python3.6_3.6.8-1~18.04.1.debian.tar.xz patch -p1 < "$CONTRIB/build-linux/appimage/patches/python-3.6.8-reproducible-buildinfo.diff" || fail "Could not patch Python build system for reproducibility" ./configure \ --cache-file="$CACHEDIR/python.config.cache" \ --prefix="$APPDIR/usr" \ --enable-ipv6 \ --enable-shared \ --with-threads \ -q || fail "Python configure failed" make -j 4 -s || fail "Could not build Python" make -s install > /dev/null || fail "Failed to install Python" # When building in docker on macOS, python builds with .exe extension because the # case insensitive file system of macOS leaks into docker. This causes the build # to result in a different output on macOS compared to Linux. We simply patch # sysconfigdata to remove the extension. # Some more info: https://bugs.python.org/issue27631 sed -i -e 's/\.exe//g' "$APPDIR"/usr/lib/python3.6/_sysconfigdata* ) info "Building squashfskit" git clone "https://github.com/squashfskit/squashfskit.git" "$BUILDDIR/squashfskit" ( cd "$BUILDDIR/squashfskit" git checkout -b pinned "$SQUASHFSKIT_COMMIT" || fail "Could not find squashfskit commit $SQUASHFSKIT_COMMIT" make -C squashfs-tools mksquashfs || fail "Could not build squashfskit" ) MKSQUASHFS="$BUILDDIR/squashfskit/squashfs-tools/mksquashfs" #info "Building libsecp256k1" # make_secp below already prints this ( pushd "$PROJECT_ROOT" "$CONTRIB"/make_secp || fail "Could not build libsecp" popd ) #info "Building libzbar" # make_zbar below already prints this ( pushd "$PROJECT_ROOT" "$CONTRIB"/make_zbar || fail "Could not build libzbar" popd ) appdir_python() { env \ PYTHONNOUSERSITE=1 \ LD_LIBRARY_PATH="$APPDIR/usr/lib:$APPDIR/usr/lib/x86_64-linux-gnu${LD_LIBRARY_PATH+:$LD_LIBRARY_PATH}" \ "$APPDIR/usr/bin/python3.6" "$@" } python='appdir_python' info "Installing pip" "$python" -m ensurepip info "Preparing electrum-locale" ( cd "$PROJECT_ROOT" pushd "$CONTRIB"/electrum-locale if ! which msgfmt > /dev/null 2>&1; then fail "Please install gettext" fi for i in ./locale/*; do dir="$PROJECT_ROOT/lib/$i/LC_MESSAGES" mkdir -p $dir msgfmt --output-file="$dir/electron-cash.mo" "$i/electron-cash.po" || true done popd ) info "Installing Electron Cash and its dependencies" mkdir -p "$CACHEDIR/pip_cache" "$python" -m pip install --cache-dir "$CACHEDIR/pip_cache" -r "$CONTRIB/deterministic-build/requirements.txt" "$python" -m pip install --cache-dir "$CACHEDIR/pip_cache" -r "$CONTRIB/deterministic-build/requirements-binaries.txt" "$python" -m pip install --cache-dir "$CACHEDIR/pip_cache" -r "$CONTRIB/deterministic-build/requirements-hw.txt" "$python" -m pip install --cache-dir "$CACHEDIR/pip_cache" "$PROJECT_ROOT" info "Installing missing libQt5MultimediaGstTools for PyQt5 5.11.3" # Packaging bug in PyQt5 5.11.3, fixed in 5.12.2, see: # https://www.riverbankcomputing.com/pipermail/pyqt/2019-April/041670.html xz -k -d "$CACHEDIR/libQt5MultimediaGstTools.so.5.11.3.xz" mv "$CACHEDIR/libQt5MultimediaGstTools.so.5.11.3" \ "$APPDIR/usr/lib/python3.6/site-packages/PyQt5/Qt/lib/libQt5MultimediaGstTools.so.5" info "Copying desktop integration" cp "$PROJECT_ROOT/electron-cash.desktop" "$APPDIR/electron-cash.desktop" cp "$PROJECT_ROOT/icons/electron-cash.png" "$APPDIR/electron-cash.png" # add launcher info "Adding launcher" cp "$CONTRIB/build-linux/appimage/apprun.sh" "$APPDIR/AppRun" info "Finalizing AppDir" ( export PKG2AICOMMIT="$PKG2APPIMAGE_COMMIT" . "$CACHEDIR/functions.sh" cd "$APPDIR" # copy system dependencies # note: temporarily move PyQt5 out of the way so # we don't try to bundle its system dependencies. mv "$APPDIR/usr/lib/python3.6/site-packages/PyQt5" "$BUILDDIR" copy_deps; copy_deps; copy_deps move_lib mv "$BUILDDIR/PyQt5" "$APPDIR/usr/lib/python3.6/site-packages" # apply global appimage blacklist to exclude stuff # move usr/include out of the way to preserve usr/include/python3.6m. mv usr/include usr/include.tmp delete_blacklisted mv usr/include.tmp usr/include ) || fail "Could not finalize AppDir" # We copy libusb here because it is on the AppImage excludelist and it can cause problems if we use system libusb info "Copying libusb" cp -f /usr/lib/x86_64-linux-gnu/libusb-1.0.so "$APPDIR/usr/lib/libusb-1.0.so" || fail "Could not copy libusb" info "Stripping binaries of debug symbols" # "-R .note.gnu.build-id" also strips the build id strip_binaries() { chmod u+w -R "$APPDIR" { printf '%s\0' "$APPDIR/usr/bin/python3.6" find "$APPDIR" -type f -regex '.*\.so\(\.[0-9.]+\)?$' -print0 } | xargs -0 --no-run-if-empty --verbose -n1 strip -R .note.gnu.build-id } strip_binaries remove_emptydirs() { find "$APPDIR" -type d -empty -print0 | xargs -0 --no-run-if-empty rmdir -vp --ignore-fail-on-non-empty } remove_emptydirs info "Removing some unneeded files to decrease binary size" rm -rf "$APPDIR"/usr/{share,include} PYDIR="$APPDIR"/usr/lib/python3.6 rm -rf "$PYDIR"/{test,ensurepip,lib2to3,idlelib,turtledemo} rm -rf "$PYDIR"/{ctypes,sqlite3,tkinter,unittest}/test rm -rf "$PYDIR"/distutils/{command,tests} rm -rf "$PYDIR"/config-3.6m-x86_64-linux-gnu rm -rf "$PYDIR"/site-packages/{opt,pip,setuptools,wheel} rm -rf "$PYDIR"/site-packages/Cryptodome/SelfTest rm -rf "$PYDIR"/site-packages/{psutil,qrcode,websocket}/tests for component in connectivity declarative help location multimedia quickcontrols2 serialport webengine websockets xmlpatterns ; do rm -rf "$PYDIR"/site-packages/PyQt5/Qt/translations/qt${component}_* rm -rf "$PYDIR"/site-packages/PyQt5/Qt/resources/qt${component}_* done rm -rf "$PYDIR"/site-packages/PyQt5/Qt/{qml,libexec} rm -rf "$PYDIR"/site-packages/PyQt5/{pyrcc.so,pylupdate.so,uic} rm -rf "$PYDIR"/site-packages/PyQt5/Qt/plugins/{bearer,gamepads,geometryloaders,geoservices,playlistformats,position,printsupport,renderplugins,sceneparsers,sensors,sqldrivers,texttospeech,webview} for component in Bluetooth Concurrent Designer Help Location NetworkAuth Nfc Positioning PositioningQuick PrintSupport Qml Quick Sensors SerialPort Sql Test Web Xml ; do rm -rf "$PYDIR"/site-packages/PyQt5/Qt/lib/libQt5${component}* rm -rf "$PYDIR"/site-packages/PyQt5/Qt${component}* done rm -rf "$PYDIR"/site-packages/PyQt5/Qt.so # these are deleted as they were not deterministic; and are not needed anyway find "$APPDIR" -path '*/__pycache__*' -delete rm -rf "$PYDIR"/site-packages/*.dist-info/ rm -rf "$PYDIR"/site-packages/*.egg-info/ find -exec touch -h -d '2000-11-11T11:11:11+00:00' {} + info "Creating the AppImage" ( cd "$BUILDDIR" chmod +x "$CACHEDIR/appimagetool" "$CACHEDIR/appimagetool" --appimage-extract # We build a small wrapper for mksquashfs that removes the -mkfs-fixed-time option # that mksquashfs from squashfskit does not support. It is not needed for squashfskit. cat > ./squashfs-root/usr/lib/appimagekit/mksquashfs << EOF #!/bin/sh args=\$(echo "\$@" | sed -e 's/-mkfs-fixed-time 0//') "$MKSQUASHFS" \$args EOF env VERSION="$VERSION" ARCH=x86_64 SOURCE_DATE_EPOCH=1530212462 \ ./squashfs-root/AppRun --no-appstream --verbose "$APPDIR" "$APPIMAGE" \ || fail "AppRun failed" ) || fail "Could not create the AppImage" info "Done" ls -la "$DISTDIR" sha256sum "$DISTDIR"/*
#!/bin/bash # Copyright (c) The Diem Core Contributors. # Copyright 2020-2021 The Databend Authors. # SPDX-License-Identifier: Apache-2.0. set -e SCRIPT_PATH="$(cd "$(dirname "$0")" >/dev/null 2>&1 && pwd)" cd "$SCRIPT_PATH/../.." || exit function add_to_profile { eval "$1" FOUND=$(grep -c "$1" "${HOME}/.profile" || true) if [ "$FOUND" == "0" ]; then echo "$1" >>"${HOME}"/.profile fi } function update_path_and_profile { touch "${HOME}"/.profile mkdir -p "${HOME}"/bin if [ -n "$CARGO_HOME" ]; then add_to_profile "export CARGO_HOME=\"${CARGO_HOME}\"" add_to_profile "export PATH=\"${HOME}/bin:${CARGO_HOME}/bin:\$PATH\"" else add_to_profile "export PATH=\"${HOME}/bin:${HOME}/.cargo/bin:\$PATH\"" fi } function install_pkg { package=$1 PACKAGE_MANAGER=$2 PRE_COMMAND=() if [ "$(whoami)" != 'root' ]; then PRE_COMMAND=(sudo) fi if which "$package" &>/dev/null; then echo "$package is already installed" else echo "Installing ${package}." case "$PACKAGE_MANAGER" in apt-get) "${PRE_COMMAND[@]}" apt-get install --no-install-recommends -yq "${package}" ;; yum) "${PRE_COMMAND[@]}" yum install -yq "${package}" ;; pacman) "${PRE_COMMAND[@]}" pacman --quiet --noconfirm -Syu "$package" ;; apk) apk --quiet --update add --no-cache "${package}" ;; dnf) dnf --quiet install "$package" ;; brew) brew install --quiet "$package" ;; *) echo "Unable to install ${package} package manager: $PACKAGE_MANAGER" exit 1 ;; esac fi } function install_build_essentials { PACKAGE_MANAGER=$1 echo "==> installing build essentials..." case "$PACKAGE_MANAGER" in apt-get) install_pkg build-essential "$PACKAGE_MANAGER" ;; pacman) install_pkg base-devel "$PACKAGE_MANAGER" ;; apk) install_pkg alpine-sdk "$PACKAGE_MANAGER" install_pkg coreutils "$PACKAGE_MANAGER" ;; yum | dnf) install_pkg gcc "$PACKAGE_MANAGER" install_pkg gcc-c++ "$PACKAGE_MANAGER" install_pkg make "$PACKAGE_MANAGER" ;; brew) # skip ;; *) echo "Unable to install build essentials with package manager: $PACKAGE_MANAGER" exit 1 ;; esac } function install_openssl { PACKAGE_MANAGER=$1 echo "==> installing openssl libs..." case "$PACKAGE_MANAGER" in apt-get) install_pkg libssl-dev "$PACKAGE_MANAGER" ;; pacman) install_pkg openssl "$PACKAGE_MANAGER" ;; apk) install_pkg openssl-dev "$PACKAGE_MANAGER" install_pkg openssl-libs-static "$PACKAGE_MANAGER" ;; yum) install_pkg openssl-devel "$PACKAGE_MANAGER" ;; dnf) install_pkg openssl-devel "$PACKAGE_MANAGER" ;; brew) install_pkg openssl "$PACKAGE_MANAGER" ;; *) echo "Unable to install openssl with package manager: $PACKAGE_MANAGER" exit 1 ;; esac } function install_protobuf { PACKAGE_MANAGER=$1 echo "==> installing protobuf compiler..." case "$PACKAGE_MANAGER" in apt-get) install_pkg protobuf-compiler "$PACKAGE_MANAGER" ;; pacman) install_pkg protoc "$PACKAGE_MANAGER" ;; apk) install_pkg protoc "$PACKAGE_MANAGER" ;; yum) install_pkg protobuf "$PACKAGE_MANAGER" ;; dnf) install_pkg protobuf-compiler "$PACKAGE_MANAGER" ;; brew) install_pkg protobuf "$PACKAGE_MANAGER" ;; *) echo "Unable to install protobuf with package manager: $PACKAGE_MANAGER" exit 1 ;; esac } function install_thrift { PACKAGE_MANAGER=$1 echo "==> installing thrift compiler..." case "$PACKAGE_MANAGER" in apt-get) install_pkg thrift-compiler "$PACKAGE_MANAGER" ;; pacman) install_pkg thrift "$PACKAGE_MANAGER" ;; apk) install_pkg thrift "$PACKAGE_MANAGER" ;; yum) install_pkg thrift "$PACKAGE_MANAGER" ;; dnf) install_pkg thrift "$PACKAGE_MANAGER" ;; brew) install_pkg thrift "$PACKAGE_MANAGER" ;; *) echo "Unable to install thrif with package manager: $PACKAGE_MANAGER" exit 1 ;; esac } function install_jdk { PACKAGE_MANAGER=$1 echo "==> installing java development kit..." case "$PACKAGE_MANAGER" in apt-get) install_pkg openjdk-11-jdk-headless "$PACKAGE_MANAGER" ;; pacman) install_pkg jre11-openjdk-headless "$PACKAGE_MANAGER" ;; apk) install_pkg openjdk11 "$PACKAGE_MANAGER" ;; yum) install_pkg java-11-openjdk "$PACKAGE_MANAGER" ;; dnf) install_pkg java-11-openjdk "$PACKAGE_MANAGER" ;; brew) install_pkg java11 "$PACKAGE_MANAGER" ;; *) echo "Unable to install jdk with package manager: $PACKAGE_MANAGER" exit 1 ;; esac } function install_pkg_config { PACKAGE_MANAGER=$1 echo "==> installing pkg-config..." case "$PACKAGE_MANAGER" in apt-get | dnf) install_pkg pkg-config "$PACKAGE_MANAGER" ;; pacman) install_pkg pkgconf "$PACKAGE_MANAGER" ;; apk | brew | yum) install_pkg pkgconfig "$PACKAGE_MANAGER" ;; *) echo "Unable to install pkg-config with package manager: $PACKAGE_MANAGER" exit 1 ;; esac } function install_mysql_client { PACKAGE_MANAGER=$1 echo "==> installing mysql client..." case "$PACKAGE_MANAGER" in apt-get) install_pkg default-mysql-client "$PACKAGE_MANAGER" ;; pacman) install_pkg mysql-clients "$PACKAGE_MANAGER" ;; apk) install_pkg mysql-client "$PACKAGE_MANAGER" ;; yum | dnf | brew) install_pkg mysql "$PACKAGE_MANAGER" ;; *) echo "Unable to install mysql client with package manager: $PACKAGE_MANAGER" exit 1 ;; esac } function install_rustup { RUST_TOOLCHAIN=$1 echo "==> Installing Rust......" if rustup --version &>/dev/null; then echo "Rust is already installed" else curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain "${RUST_TOOLCHAIN}" --profile minimal PATH="${HOME}/.cargo/bin:${PATH}" source $HOME/.cargo/env fi } function install_cargo_binary { BIN_NAME=$1 VERSION=$2 if cargo install --list | grep "${BIN_NAME}" &>/dev/null; then echo "${BIN_NAME} is already installed" else if [ -z "$VERSION" ]; then cargo install "${BIN_NAME}" else cargo install --version "${VERSION}" "${BIN_NAME}" fi fi } function install_toolchain { version=$1 echo "==> Installing ${version} of rust toolchain..." rustup install "$version" rustup set profile minimal rustup component add rustfmt --toolchain "$version" rustup component add rust-src --toolchain "$version" rustup component add clippy --toolchain "$version" rustup component add miri --toolchain "$version" rustup default "$version" } function usage { cat <<EOF usage: $0 [options] options: -y Auto approve installation -b Install build tools -d Install development tools -p Install profile -s Install codegen tools -t Install tpch data set -v Verbose mode EOF } function welcome_message { cat <<EOF Welcome to DatabendQuery! This script will download and install the necessary dependencies needed to build, test and inspect DatabendQuery. Based on your selection, these tools will be included: EOF if [[ "$INSTALL_BUILD_TOOLS" == "true" ]]; then cat <<EOF Build tools (since -b or no option was provided): * Rust (and the necessary components, e.g. rust-fmt, clippy) * build-essential * pkg-config * libssl-dev * protobuf-compiler * thrift-compiler * openjdk * tpch dataset for benchmark EOF fi if [[ "$INSTALL_DEV_TOOLS" == "true" ]]; then cat <<EOF Development tools (since -d was provided): * mysql client * python3 (boto3, yapf, yamllint, ...) * lcov * tools from rust-tools.txt ( e.g. cargo-audit, cargo-udeps, taplo-cli) EOF fi if [[ "$INSTALL_CODEGEN" == "true" ]]; then cat <<EOF Codegen tools (since -s was provided): * Python3 (numpy, pyre-check) EOF fi if [[ "$INSTALL_PROFILE" == "true" ]]; then cat <<EOF Moreover, ~/.profile will be updated (since -p was provided). EOF fi if [[ "$INSTALL_TPCH_DATA" == "true" ]]; then cat <<EOF Tpch dataset (since -t was provided): EOF fi cat <<EOF If you'd prefer to install these dependencies yourself, please exit this script now with Ctrl-C. EOF } AUTO_APPROVE=false VERBOSE=false INSTALL_BUILD_TOOLS=false INSTALL_DEV_TOOLS=false INSTALL_PROFILE=false INSTALL_CODEGEN=false INSTALL_TPCH_DATA=false # parse args while getopts "ybdpstv" arg; do case "$arg" in y) AUTO_APPROVE="true" ;; b) INSTALL_BUILD_TOOLS="true" ;; d) INSTALL_DEV_TOOLS="true" ;; p) INSTALL_PROFILE="true" ;; s) INSTALL_CODEGEN="true" ;; v) VERBOSE="true" ;; t) INSTALL_TPCH_DATA="true" ;; *) usage exit 0 ;; esac done if [[ "$VERBOSE" == "true" ]]; then set -x fi if [[ "$INSTALL_BUILD_TOOLS" == "false" ]] && [[ "$INSTALL_DEV_TOOLS" == "false" ]] && [[ "$INSTALL_PROFILE" == "false" ]] && [[ "$INSTALL_TPCH_DATA" == "false" ]] && [[ "$INSTALL_CODEGEN" == "false" ]]; then INSTALL_BUILD_TOOLS="true" fi if [ ! -f rust-toolchain.toml ]; then echo "Unknown location. Please run this from the databend repository. Abort." exit 1 fi RUST_TOOLCHAIN="$(awk -F'[ ="]+' '$1 == "channel" { print $2 }' rust-toolchain.toml)" PACKAGE_MANAGER= if [[ "$(uname)" == "Linux" ]]; then if command -v yum &>/dev/null; then PACKAGE_MANAGER="yum" elif command -v apt-get &>/dev/null; then PACKAGE_MANAGER="apt-get" elif command -v pacman &>/dev/null; then PACKAGE_MANAGER="pacman" elif command -v apk &>/dev/null; then PACKAGE_MANAGER="apk" elif command -v dnf &>/dev/null; then echo "WARNING: dnf package manager support is experimental" PACKAGE_MANAGER="dnf" else echo "Unable to find supported package manager (yum, apt-get, dnf, apk, or pacman). Abort" exit 1 fi elif [[ "$(uname)" == "Darwin" ]]; then if which brew &>/dev/null; then PACKAGE_MANAGER="brew" else echo "Missing package manager Homebrew (https://brew.sh/). Abort" exit 1 fi else echo "Unknown OS. Abort." exit 1 fi # NOTE: never use sudo under macos PRE_COMMAND=() if [[ "$(whoami)" != 'root' ]] && [[ ${PACKAGE_MANAGER} != "brew" ]]; then PRE_COMMAND=(sudo) fi if [[ "$AUTO_APPROVE" == "false" ]]; then welcome_message printf "Proceed with installing necessary dependencies? (y/N) > " read -e -r input if [[ "$input" != "y"* ]]; then echo "Exiting..." exit 0 fi fi if [[ "$PACKAGE_MANAGER" == "apt-get" ]]; then "${PRE_COMMAND[@]}" apt-get update install_pkg ca-certificates "$PACKAGE_MANAGER" fi [[ "$INSTALL_PROFILE" == "true" ]] && update_path_and_profile install_pkg curl "$PACKAGE_MANAGER" if [[ "$INSTALL_BUILD_TOOLS" == "true" ]]; then install_rustup "$RUST_TOOLCHAIN" install_build_essentials "$PACKAGE_MANAGER" install_pkg_config "$PACKAGE_MANAGER" install_openssl "$PACKAGE_MANAGER" install_protobuf "$PACKAGE_MANAGER" install_thrift "$PACKAGE_MANAGER" install_jdk "$PACKAGE_MANAGER" install_pkg cmake "$PACKAGE_MANAGER" install_pkg clang "$PACKAGE_MANAGER" install_pkg llvm "$PACKAGE_MANAGER" install_toolchain "$RUST_TOOLCHAIN" fi if [[ "$INSTALL_DEV_TOOLS" == "true" ]]; then install_mysql_client "$PACKAGE_MANAGER" install_pkg git "$PACKAGE_MANAGER" install_pkg python3 "$PACKAGE_MANAGER" if [[ "$PACKAGE_MANAGER" == "apt-get" ]]; then # for killall & timeout install_pkg psmisc "$PACKAGE_MANAGER" install_pkg coreutils "$PACKAGE_MANAGER" install_pkg python3-all-dev "$PACKAGE_MANAGER" install_pkg python3-setuptools "$PACKAGE_MANAGER" install_pkg python3-pip "$PACKAGE_MANAGER" elif [[ "$PACKAGE_MANAGER" == "apk" ]]; then # no wheel package for alpine install_pkg python3-dev "$PACKAGE_MANAGER" install_pkg py3-pip "$PACKAGE_MANAGER" install_pkg libffi-dev "$PACKAGE_MANAGER" fi python3 -m pip install --quiet boto3 "moto[all]" yapf shfmt-py toml yamllint # drivers python3 -m pip install --quiet mysql-connector-python pymysql sqlalchemy clickhouse_driver if [[ -f scripts/setup/rust-tools.txt ]]; then export RUSTFLAGS="-C target-feature=-crt-static" while IFS='@' read -r tool version; do install_cargo_binary "$tool" "$version" done <scripts/setup/rust-tools.txt fi if [[ "$PACKAGE_MANAGER" == "apk" ]]; then # needed by lcov echo http://nl.alpinelinux.org/alpine/edge/testing >>/etc/apk/repositories fi install_pkg lcov "$PACKAGE_MANAGER" fi if [[ "$INSTALL_CODEGEN" == "true" ]]; then install_pkg clang "$PACKAGE_MANAGER" install_pkg llvm "$PACKAGE_MANAGER" if [[ "$PACKAGE_MANAGER" == "apt-get" ]]; then install_pkg python3-all-dev "$PACKAGE_MANAGER" install_pkg python3-setuptools "$PACKAGE_MANAGER" install_pkg python3-pip "$PACKAGE_MANAGER" elif [[ "$PACKAGE_MANAGER" == "apk" ]]; then install_pkg python3-dev "$PACKAGE_MANAGER" install_pkg py3-pip "$PACKAGE_MANAGER" else install_pkg python3 "$PACKAGE_MANAGER" fi "${PRE_COMMAND[@]}" python3 -m pip install --quiet coscmd PyYAML fi if [[ "$INSTALL_TPCH_DATA" == "true" ]]; then # Construct a docker imagine to generate tpch-data if [[ -z $2 ]]; then docker build -f scripts/setup/tpchdata.dockerfile -t databend:latest . else docker build -f scripts/setup/tpchdata.dockerfile -t databend:latest --build-arg scale_factor=$2 . fi # Generate data into the ./data directory if it does not already exist FILE=benchmark/tpch/data/customer.tbl if test -f "$FILE"; then echo "$FILE exists." else mkdir $(pwd)/benchmark/tpch/data 2>/dev/null docker run -v $(pwd)/benchmark/tpch/data:/data --rm databend:latest fi fi [[ "${AUTO_APPROVE}" == "false" ]] && cat <<EOF Finished installing all dependencies. You should now be able to build the project by running: cargo build EOF exit 0
var editor = ace.edit("editor"); editor.setTheme("ace/theme/chrome"); editor.session.setMode("ace/mode/runtime"); editor.session.setTabSize(1); editor.setFontSize(15); /* Console */ let jqconsole = $('#console').jqconsole(); jqconsole.Write('Runtime Script\n', 'console-gray'); jqconsole.SetPromptLabel(' '); let runtime = runtimeExecuter(); let canvas = runtimeCanvas(); canvas.init($('#canvas')[0]); let evaluator = runtimeEvaluator(); let parser = runtimeParser(); /* UI */ let runBtn = $("#run-btn"); let resetBtn = $("#reset-btn"); let stepBtn = $("#step-btn"); let clearBtn = $("#clear-canvas-btn"); let runInput = $("#run-input-btn"); let statusIndicator = $('#status-indicator'); runBtn.click(() => runtime.executeAll()); resetBtn.click(() => runtime.restart()); stepBtn.click(() => runtime.executeStep()); clearBtn.click(() => canvas.clearCanvas()); runInput.click(() => runtime.inputAndExecute()); let controls = { run: runBtn, restart: resetBtn, stepBtn: stepBtn, clearBtn: clearBtn, statusIndicator: statusIndicator }; runtime.config(parser, evaluator, editor, jqconsole, canvas, controls); /* Breakpoints */ editor.on("guttermousedown", e => { var target = e.domEvent.target; if (target.className.indexOf("ace_gutter-cell") == -1){ return; } if (!editor.isFocused()){ return; } if (e.clientX > 25 + target.getBoundingClientRect().left){ return; } var breakpoints = e.editor.session.getBreakpoints(); var row = e.getDocumentPosition().row; if(typeof breakpoints[row] === typeof undefined){ e.editor.session.setBreakpoint(row); }else{ e.editor.session.clearBreakpoint(row); } let breakpointIdx = []; for (let i = 0; i < breakpoints.length; i++) { if (breakpoints[i] !== undefined) { breakpointIdx.push(i); } } runtime.setBreakpoints(breakpointIdx); e.stop(); }) function gotoLine (line) { editor.gotoLine(line+1, 0); } let startPrompt = () => { // Start the prompt with history enabled. jqconsole.Prompt(true, function (input) { switch (input) { case 'clear': jqconsole.Reset(); break; case 'env': jqconsole.Write(`${JSON.stringify(runtime.getEnv(), null, 2)}\n`, 'console-default'); break; } startPrompt(); }); } startPrompt(); /* Load Code */ function getCodeUrl(codeId) { return 'https://raw.githubusercontent.com/yjlo123/runtime-script/master/examples/' + codeId + '.runtime'; } function getURLParameter(sParam) { var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == sParam) { return sParameterName[1]; } } } function getCode(codeId) { $.ajax(getCodeUrl(codeId)) .done(function(code) { editor.setValue(code); editor.gotoLine(0); }) .fail(function() { jqconsole.Write('Loading source failed.\n', 'console-error'); }) .always(function() { console.log('Load source code finished.') }); } let codeId = getURLParameter('src'); if (codeId) { getCode(codeId); } let refreshFuncBtn = $('#refresh-func-btn'); refreshFuncBtn.click(() => { let funcs = runtime.getFuncList(); let funcArray = []; for (var funcName in funcs) { funcArray.push([funcName, funcs[funcName]]) } funcArray.sort((a, b) => a[1] - b[1]); $('#func-list').empty(); funcArray.forEach(element => { $('#func-list').append($(`<div class="func-item" onClick="gotoLine(${element[1]})">${element[0]}</div>`)); }); });
/** * Get all object property names (own or not own). * * @memberOf module:HtmlComponent * @name getAllPropertyNames * @param {object} subject - object to be analyzed. * @returns {string[]} Returns array of property names. * @see https://stackoverflow.com/questions/8024149/is-it-possible-to-get-the-non-enumerable-inherited-property-names-of-an-object */ export default subject => { const propsSet = new Set(); let obj = subject; do { Object.getOwnPropertyNames(obj).forEach(propertyName => propsSet.add(propertyName)); } while ((obj = Object.getPrototypeOf(obj)) && obj instanceof Object); propsSet.delete('constructor'); return Array.from(propsSet); };
<reponame>lab900/angular-libraries import { FieldOptions } from '../models/FormField'; import { FormComponent } from '../models/IFormComponent'; import { FormGroup } from '@angular/forms'; export class FormFieldUtils { public static isReadOnly(fieldOptions: FieldOptions, data: any, formComponent?: FormComponent): boolean { let isReadOnly: boolean; if (formComponent && formComponent.readonly === true) { isReadOnly = formComponent.readonly; } else if (typeof fieldOptions?.readonly === 'function') { isReadOnly = fieldOptions?.readonly(data); } else { isReadOnly = fieldOptions?.readonly ?? false; } return isReadOnly; } public static isRequired(isReadOnly: boolean, fieldOptions: FieldOptions, data: any): boolean { if (typeof fieldOptions?.required === 'function') { return (!isReadOnly && fieldOptions?.required(data)) ?? false; } else { return (!isReadOnly && fieldOptions?.required) ?? false; } } public static isHidden(fieldOptions: FieldOptions, group: FormGroup): boolean { if (typeof fieldOptions?.hide === 'function') { return fieldOptions?.hide(group.value); } else { return fieldOptions?.hide ?? false; } } }
#!/bin/bash # mkdir -p ~/lang-downloads cd ~/lang-downloads wget -O frk-jbarth-ubhd.zip http://digi.ub.uni-heidelberg.de/diglitData/v/abbyy11r8-vs-tesseract4.zip wget -O frk-stweil-gt.zip https://digi.bib.uni-mannheim.de/~stweil/fraktur-gt.zip mkdir -p ~/lang-files cd ~/lang-files unzip ~/lang-downloads/frk-jbarth-ubhd.zip -d frk unzip ~/lang-downloads/frk-stweil-gt.zip -d frk mkdir -p ./frk-ligatures cp ./frk/abbyy-vs-tesseract/*.tif ./frk-ligatures/ cp ./frk/gt/*.txt ./frk-ligatures/ cd ./frk-ligatures/ ls -1 *.tif >pages sed -i -e 's/.tif//g' pages mkdir -p ~/lang-stopwords cd ~/lang-stopwords wget -O frk.stopwords.txt https://raw.githubusercontent.com/stopwords-iso/stopwords-de/master/stopwords-de.txt echo "Edit ~/lang-files/stopwords/frk.stopwords.txt as wordacc uses a space delimited stopwords file, not line delimited."
package httpinfo import ( "context" "net/http" "time" ) type ctxKey string const ctxKeyRR = ctxKey("rr") // Record records the http response information and helps to reach // them from any other middleware. See examples on how to use it. func Record(opts ...Option) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { var ( ctx = r.Context() rr = &responseRecorder{ writer: rw, routeGetter: func(r *http.Request) string { return r.Method + " " + r.URL.Path }, start: time.Now(), } ) defer rr.WriteHeaderNow() for _, opt := range opts { opt(rr) } ctx = context.WithValue(ctx, ctxKeyRR, rr) rw = rr.wrapped() r = r.WithContext(ctx) next.ServeHTTP(rw, r) }) } }
#!/bin/bash # CI test that does a full deploy on baremetal hardware. # $HW_ENV_DIR is the directory where environment-specific files are kept. # Usage: full-deploy-baremetal.sh \ # <release> \ # <hw-env-dir> \ # <network-isolation> \ # <config-file> \ # <playbook> set -eux : ${OPT_ADDITIONAL_PARAMETERS:=""} RELEASE=$1 HW_ENV_DIR=$2 NETWORK_ISOLATION=$3 CONFIG_FILE=$4 PLAYBOOK=$5 socketdir=$(mktemp -d /tmp/sockXXXXXX) export ANSIBLE_SSH_CONTROL_PATH=$socketdir/%%h-%%r bash quickstart.sh \ --ansible-debug \ --bootstrap \ --working-dir $WORKSPACE/ \ --tags all \ --no-clone \ --teardown all \ --config $WORKSPACE/$HW_ENV_DIR/network_configs/$NETWORK_ISOLATION/config_files/$CONFIG_FILE \ --extra-vars @$WORKSPACE/$HW_ENV_DIR/network_configs/$NETWORK_ISOLATION/env_settings.yml \ --playbook $PLAYBOOK \ --extra-vars undercloud_instackenv_template=$WORKSPACE/$HW_ENV_DIR/instackenv.json \ --extra-vars network_environment_file=$WORKSPACE/$HW_ENV_DIR/network_configs/$NETWORK_ISOLATION/${NETWORK_ISOLATION}.yml \ --extra-vars nic_configs_dir=$WORKSPACE/$HW_ENV_DIR/network_configs/$NETWORK_ISOLATION/nic_configs/ \ --release ${CI_ENV:+$CI_ENV/}$RELEASE${REL_TYPE:+-$REL_TYPE} \ $OPT_ADDITIONAL_PARAMETERS \ $VIRTHOST
#!/bin/sh node export.js "https://monitor.2020.linuxplumbersconf.org/playback/presentation/lpc2020/playback.html?meetingId=d4742aeda71bb0f338bca6b8e368247502f2727b-1598490146327&t=57m50s" MEETING_ID 0 false exec "$@"
#!/bin/bash # install packages for the gworkspace test files # this includes the objective c compiler and gnustep # load library file if [ -f libTYSP.sh ]; then source libTYSP.sh else source $HOME/bin/libTYSP.sh fi # check for running on Windows under MSYS if [ $TERM = "cygwin" ]; then echo "This script is Linux only! "; exit; fi #define $result variable here result=: unset result echo echo "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" echo "* updating package list *" echo "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" promptYESNO "Do you want to update the package list" "n" if [ ! $YESNO ] || [ $YESNO = "y" ]; then sudo apt-get update result=$?; echo ; echo RESULT=$result if [ $result -ne 0 ] && [ $result -ne 100 ]; then read -sn1 -p "Error updating package list! "; echo; fi unset result fi unset YESNO echo echo "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" echo "* installing objective c *" echo "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" sudo apt-get install gobjc result=$? ; echo ; echo RESULT=$result if [ ! $result ] || [ $result -ne 0 ]; then read -sn1 -p "Error installing packages! "; echo; fi unset result echo echo "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" echo "* installing gnustep *" echo "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" sudo apt-get install gnustep-core-devel result=$? ; echo ; echo RESULT=$result if [ ! $result ] || [ $result -ne 0 ]; then read -sn1 -p "Error installing packages! "; echo; fi unset result echo read -sn1 -p "Press Enter to end . . ."
/* Found this at: * https://stackoverflow.com/questions/54292012/handle-empty-strings-as-image-paths-when-using-gatsby-transformer-sharp?rq=1 */ let fieldsToRemove = [] const deleteFieldsRecursive = (node) => { // if node is an empty string, delete it fieldsToRemove.forEach(fieldToRemove => { if (node[fieldToRemove] === '') { delete node[fieldToRemove] } }) // if node is an empty object, go into it and evaluate subnodes if (typeof node === 'object') { Object.values(node).forEach(subNode => { deleteFieldsRecursive(subNode) }) } } exports.onCreateNode = ({ node }, configOptions) => { fieldsToRemove = configOptions.fieldsToRemove // if node is a markdownremark node, but doesn't have // frontmatter, then return if (node.internal.type === 'MarkdownRemark') { if (!node.frontmatter) { return; } deleteFieldsRecursive(node) } }
#!/usr/bin/env bats load test_helper setup() { dokku apps:create my_app >&2 dokku "$PLUGIN_COMMAND_PREFIX:create" l >&2 dokku "$PLUGIN_COMMAND_PREFIX:link" l my_app >&2 } teardown() { dokku "$PLUGIN_COMMAND_PREFIX:unlink" l my_app >&2 dokku --force "$PLUGIN_COMMAND_PREFIX:destroy" l >&2 rm "$DOKKU_ROOT/my_app" -rf } @test "($PLUGIN_COMMAND_PREFIX:hook:pre-delete) removes app from links file when destroying app" { [[ -n $(< "$PLUGIN_DATA_ROOT/l/LINKS") ]] dokku --force apps:destroy my_app [[ -z $(< "$PLUGIN_DATA_ROOT/l/LINKS") ]] }
<reponame>lanpinguo/rootfs_build<gh_stars>0 #ifndef _SUNXI_DI_H #define _SUNXI_DI_H #include <linux/types.h> #include "di.h" #define DI_RESERVED_MEM #define DI_MODULE_NAME "deinterlace" #define DI_TIMEOUT 30 /* DI-Interlace 30ms timeout */ #define DI_MODULE_TIMEOUT 0x1055 #define FLAG_WIDTH (2048) #define FLAG_HIGH (1100) typedef struct { void __iomem *base_addr; __di_mem_t mem_in_params; __di_mem_t mem_out_params; atomic_t di_complete; atomic_t enable; wait_queue_head_t wait; void *in_flag_phy; void *out_flag_phy; size_t flag_size; u32 irq_number; u32 time_value; struct mutex slock; bool opened; #ifdef CONFIG_PM struct dev_pm_domain di_pm_domain; #endif }di_struct, *pdi_struct; #define DI_IOC_MAGIC 'D' #define DI_IOCSTART _IOWR(DI_IOC_MAGIC, 0, __di_rectsz_t) enum { DEBUG_INIT = 1U << 0, DEBUG_INT = 1U << 1, DEBUG_DATA_INFO = 1U << 2, DEBUG_SUSPEND = 1U << 3, DEBUG_TEST = 1U << 4, }; #define dprintk(level_mask, fmt, arg...) if (unlikely(debug_mask & level_mask)) \ printk(KERN_DEBUG fmt , ## arg) #endif
#!/bin/bash # ========== Experiment Seq. Idx. 3118 / 60.7.4.0 / N. 0 - _S=60.7.4.0 D1_N=38 a=1 b=-1 c=1 d=1 e=-1 f=-1 D3_N=1 g=-1 h=-1 i=1 D4_N=2 j=2 D5_N=0 ========== set -u # Prints header echo -e '\n\n========== Experiment Seq. Idx. 3118 / 60.7.4.0 / N. 0 - _S=60.7.4.0 D1_N=38 a=1 b=-1 c=1 d=1 e=-1 f=-1 D3_N=1 g=-1 h=-1 i=1 D4_N=2 j=2 D5_N=0 ==========\n\n' # Prepares all environment variables JBHI_DIR="$HOME/jbhi-special-issue" RESULTS_DIR="$JBHI_DIR/results" if [[ "No" == "Yes" ]]; then SVM_SUFFIX="svm" PREDICTIONS_FORMAT="isbi" else SVM_SUFFIX="nosvm" PREDICTIONS_FORMAT="titans" fi RESULTS_PREFIX="$RESULTS_DIR/deep.38.layer.1.test.2.index.3118.$SVM_SUFFIX" RESULTS_PATH="$RESULTS_PREFIX.results.txt" # ...variables expected by jbhi-checks.include.sh and jbhi-footer.include.sh SOURCES_GIT_DIR="$JBHI_DIR/jbhi-special-issue" LIST_OF_INPUTS="$RESULTS_PREFIX.finish.txt" # ...this experiment is a little different --- only one master procedure should run, so there's only a master lock file METRICS_TEMP_PATH="$RESULTS_DIR/this_results.anova.txt" METRICS_PATH="$RESULTS_DIR/all_results.anova.txt" START_PATH="$METRICS_PATH.start.txt" FINISH_PATH="-" LOCK_PATH="$METRICS_PATH.running.lock" LAST_OUTPUT="$METRICS_PATH" mkdir -p "$RESULTS_DIR" # # Assumes that the following environment variables where initialized # SOURCES_GIT_DIR="$JBHI_DIR/jbhi-special-issue" # LIST_OF_INPUTS="$DATASET_DIR/finish.txt:$MODELS_DIR/finish.txt:" # START_PATH="$OUTPUT_DIR/start.txt" # FINISH_PATH="$OUTPUT_DIR/finish.txt" # LOCK_PATH="$OUTPUT_DIR/running.lock" # LAST_OUTPUT="$MODEL_DIR/[[[:D1_MAX_NUMBER_OF_STEPS:]]].meta" EXPERIMENT_STATUS=1 STARTED_BEFORE=No # Checks if code is stable, otherwise alerts scheduler pushd "$SOURCES_GIT_DIR" >/dev/null GIT_STATUS=$(git status --porcelain) GIT_COMMIT=$(git log | head -n 1) popd >/dev/null if [ "$GIT_STATUS" != "" ]; then echo 'FATAL: there are uncommitted changes in your git sources file' >&2 echo ' for reproducibility, experiments only run on committed changes' >&2 echo >&2 echo ' Git status returned:'>&2 echo "$GIT_STATUS" >&2 exit 162 fi # The experiment is already finished - exits with special code so scheduler won't retry if [[ "$FINISH_PATH" != "-" ]]; then if [[ -e "$FINISH_PATH" ]]; then echo 'INFO: this experiment has already finished' >&2 exit 163 fi fi # The experiment is not ready to run due to dependencies - alerts scheduler if [[ "$LIST_OF_INPUTS" != "" ]]; then IFS=':' tokens_of_input=( $LIST_OF_INPUTS ) input_missing=No for input_to_check in ${tokens_of_input[*]}; do if [[ ! -e "$input_to_check" ]]; then echo "ERROR: input $input_to_check missing for this experiment" >&2 input_missing=Yes fi done if [[ "$input_missing" != No ]]; then exit 164 fi fi # Sets trap to return error code if script is interrupted before successful finish LOCK_SUCCESS=No FINISH_STATUS=161 function finish_trap { if [[ "$LOCK_SUCCESS" == "Yes" ]]; then rmdir "$LOCK_PATH" &> /dev/null fi if [[ "$FINISH_STATUS" == "165" ]]; then echo 'WARNING: experiment discontinued because other process holds its lock' >&2 else if [[ "$FINISH_STATUS" == "160" ]]; then echo 'INFO: experiment finished successfully' >&2 else [[ "$FINISH_PATH" != "-" ]] && rm -f "$FINISH_PATH" echo 'ERROR: an error occurred while executing the experiment' >&2 fi fi exit "$FINISH_STATUS" } trap finish_trap EXIT # While running, locks experiment so other parallel threads won't attempt to run it too if mkdir "$LOCK_PATH" --mode=u=rwx,g=rx,o=rx &>/dev/null; then LOCK_SUCCESS=Yes else echo 'WARNING: this experiment is already being executed elsewhere' >&2 FINISH_STATUS="165" exit fi # If the experiment was started before, do any cleanup necessary if [[ "$START_PATH" != "-" ]]; then if [[ -e "$START_PATH" ]]; then echo 'WARNING: this experiment is being restarted' >&2 STARTED_BEFORE=Yes fi #...marks start date -u >> "$START_PATH" echo GIT "$GIT_COMMIT" >> "$START_PATH" fi if [[ "$STARTED_BEFORE" == "Yes" ]]; then # If the experiment was started before, do any cleanup necessary echo -n else echo "D1_N;D3_N;D4_N;a;b;c;d;e;f;g;h;i;j;m_ap;m_auc;m_tn;m_fp;m_fn;m_tp;m_tpr;m_fpr;k_ap;k_auc;k_tn;k_fp;k_fn;k_tp;k_tpr;k_fpr;isbi_auc" > "$METRICS_PATH" fi python \ "$SOURCES_GIT_DIR/etc/compute_metrics.py" \ --metadata_file "$SOURCES_GIT_DIR/data/all-metadata.csv" \ --predictions_format "$PREDICTIONS_FORMAT" \ --metrics_file "$METRICS_TEMP_PATH" \ --predictions_file "$RESULTS_PATH" EXPERIMENT_STATUS="$?" echo -n "38;1;2;" >> "$METRICS_PATH" echo -n "1;-1;1;1;-1;-1;-1;-1;1;2;" >> "$METRICS_PATH" tail "$METRICS_TEMP_PATH" -n 1 >> "$METRICS_PATH" # #...starts training if [[ "$EXPERIMENT_STATUS" == "0" ]]; then if [[ "$LAST_OUTPUT" == "" || -e "$LAST_OUTPUT" ]]; then if [[ "$FINISH_PATH" != "-" ]]; then date -u >> "$FINISH_PATH" echo GIT "$GIT_COMMIT" >> "$FINISH_PATH" fi FINISH_STATUS="160" fi fi
def count_unique_prime_factors(num): unique_prime_factors = [] for i in range(2, num + 1): if num % i == 0: if is_prime(i): unique_prime_factors.append(i) return len(set(unique_prime_factors)) def is_prime(n): if (n <= 1): return False if (n <= 3): return True if (n % 2 == 0 or n % 3 == 0): return False i = 5 while(i * i <= n): if (n % i == 0 or n % (i + 2) == 0): return False i = i + 6 return True count_unique_prime_factors(24)
<filename>radiaTest-server/server/schema/celerytask.py<gh_stars>0 from typing import Optional from pydantic import BaseModel class CeleryTaskQuerySchema(BaseModel): tid: Optional[str] status: Optional[str] object_type: Optional[str] page_num: int page_size: int class CeleryTaskCreateSchema(BaseModel): tid: str status: Optional[str] object_type: str vmachine_id: Optional[int] user_id: Optional[int] class CeleryTaskUserInfoSchema(BaseModel): auth: str user_id: int group_id: int org_id: int
#!/bin/bash # # Copyright (c) 2018 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 # Helper routines for generating JSON formatted results. declare -a json_result_array declare -a json_array_array # Generate a timestamp in nanoseconds since 1st Jan 1970 timestamp_ns() { local t local s local n local ns t="$(date +%-s:%-N)" s=$(echo $t | awk -F ':' '{print $1}') n=$(echo $t | awk -F ':' '{print $2}') ns=$(( (s * 1000000000) + n )) echo $ns } # Generate a timestamp in milliseconds since 1st Jan 1970 timestamp_ms() { echo $(($(date +%s%N)/1000000)) } metrics_json_init() { # Clear out any previous results json_result_array=() json_filename=${RESULT_DIR}/$(echo ${TEST_NAME} | sed 's/[ \/]/-/g').json local json="$(cat << EOF "@timestamp" : $(timestamp_ms) EOF )" metrics_json_add_fragment "$json" local json="$(cat << EOF "env" : { "Runtime": "$RUNTIME_PATH", "RuntimeVersion": "$RUNTIME_VERSION", "RuntimeCommit": "$RUNTIME_COMMIT", "Hypervisor": "$HYPERVISOR_PATH", "HypervisorVersion": "$HYPERVISOR_VERSION", "Proxy": "$PROXY_PATH", "ProxyVersion": "$PROXY_VERSION", "Shim": "$SHIM_PATH", "ShimVersion": "$SHIM_VERSION", "machinename": "$(uname -n)" } EOF )" metrics_json_add_fragment "$json" local json="$(cat << EOF "date" : { "ns": $(timestamp_ns), "Date": "$(date -u +"%Y-%m-%dT%T.%3N")" } EOF )" metrics_json_add_fragment "$json" local json="$(cat << EOF "test" : { "runtime": "${RUNTIME}", "testname": "${TEST_NAME}" } EOF )" metrics_json_add_fragment "$json" } metrics_json_save() { if [ ! -d ${RESULT_DIR} ];then mkdir -p ${RESULT_DIR} fi local maxelem=$(( ${#json_result_array[@]} - 1 )) local json="$(cat << EOF { $(for index in $(seq 0 $maxelem); do if (( index != maxelem )); then echo "${json_result_array[$index]}," else echo "${json_result_array[$index]}" fi done) } EOF )" echo "$json" > $json_filename # If we have a JSON URL set up, post the results there as well if [[ $JSON_URL ]]; then echo "Posting results to [$JSON_URL]" curl -XPOST -H"Content-Type: application/json" "$JSON_URL" -d "@$json_filename" fi } metrics_json_add_fragment() { local data=$1 # Place on end of array json_result_array[${#json_result_array[@]}]="$data" } metrics_json_start_array() { json_array_array=() } metrics_json_add_array_element() { local data=$1 # Place on end of array json_array_array[${#json_array_array[@]}]="$data" } metrics_json_end_array() { local name=$1 local maxelem=$(( ${#json_array_array[@]} - 1 )) local json="$(cat << EOF "$name": [ $(for index in $(seq 0 $maxelem); do if (( index != maxelem )); then echo "${json_array_array[$index]}," else echo "${json_array_array[$index]}" fi done) ] EOF )" # And save that to the top level metrics_json_add_fragment "$json" }
<gh_stars>1-10 import { APIRequestContext, GlobalOptions } from './api'; import { Schema, SchemaResource } from './schema'; export interface Target { [index: string]: {}; } export declare class Endpoint implements Target, APIRequestContext { _options: GlobalOptions; google: any; [index: string]: {}; constructor(options: {}); /** * Given a schema, add methods and resources to a target. * * @param {object} target The target to which to apply the schema. * @param {object} rootSchema The top-level schema, so we don't lose track of it * during recursion. * @param {object} schema The current schema from which to extract methods and * resources. * @param {object} context The context to add to each method. */ applySchema(target: Target, rootSchema: Schema, schema: SchemaResource, context: APIRequestContext): void; /** * Given a schema, add methods to a target. * * @param {object} target The target to which to apply the methods. * @param {object} rootSchema The top-level schema, so we don't lose track of it * during recursion. * @param {object} schema The current schema from which to extract methods. * @param {object} context The context to add to each method. */ private applyMethodsFromSchema(target, rootSchema, schema, context); /** * Given a method schema, add a method to a target. * * @param target The target to which to add the method. * @param schema The top-level schema that contains the rootUrl, etc. * @param method The method schema from which to generate the method. * @param context The context to add to the method. */ private makeMethod(schema, method, context); private getPathParams(params?); }
import comet_ml import os import sys import pytest from scripts.download_toy_data import download_toy_data @pytest.fixture(scope="session", autouse=True) def setup_tests(): download_toy_data('tests/out/_test_data/')
#!/bin/bash SCRIPT=$(readlink -f "$0") && cd $(dirname "$SCRIPT") # --- Script Init --- set -e set -o pipefail mkdir -p log rm -R -f log/* touch log/stderror.err ktools_monitor.sh $$ & pid0=$! exit_handler(){ exit_code=$? kill -9 $pid0 2> /dev/null if [ "$exit_code" -gt 0 ]; then echo 'Ktools Run Error - exitcode='$exit_code else echo 'Run Completed' fi set +x group_pid=$(ps -p $$ -o pgid --no-headers) sess_pid=$(ps -p $$ -o sess --no-headers) script_pid=$$ printf "Script PID:%d, GPID:%s, SPID:%d " $script_pid $group_pid $sess_pid >> log/killout.txt ps f -g $sess_pid > log/subprocess_list PIDS_KILL=$(pgrep -a --pgroup $group_pid | awk -F: '$1>$script_pid' | grep -v celery | grep -v python | grep -v $group_pid | grep -v run_ktools) echo "$PIDS_KILL" >> log/killout.txt kill -9 $(echo "$PIDS_KILL" | awk 'BEGIN { FS = "[ \t\n]+" }{ print $1 }') 2>/dev/null exit $exit_code } trap exit_handler QUIT HUP INT KILL TERM ERR check_complete(){ set +e proc_list="eve getmodel gulcalc fmcalc summarycalc eltcalc aalcalc leccalc pltcalc" has_error=0 for p in $proc_list; do started=$(find log -name "$p*.log" | wc -l) finished=$(find log -name "$p*.log" -exec grep -l "finish" {} + | wc -l) if [ "$finished" -lt "$started" ]; then echo "[ERROR] $p - $((started-finished)) processes lost" has_error=1 elif [ "$started" -gt 0 ]; then echo "[OK] $p" fi done if [ "$has_error" -ne 0 ]; then false # raise non-zero exit code fi } # --- Setup run dirs --- find output/* ! -name '*summary-info*' -exec rm -R -f {} + rm -R -f fifo/* rm -R -f work/* mkdir work/kat/ mkdir work/gul_S1_summaryleccalc mkdir work/gul_S1_summaryaalcalc mkdir work/il_S1_summaryleccalc mkdir work/il_S1_summaryaalcalc mkfifo fifo/gul_P1 mkfifo fifo/gul_S1_summary_P1 mkfifo fifo/gul_S1_eltcalc_P1 mkfifo fifo/gul_S1_summarycalc_P1 mkfifo fifo/gul_S1_pltcalc_P1 mkfifo fifo/il_P1 mkfifo fifo/il_S1_summary_P1 mkfifo fifo/il_S1_eltcalc_P1 mkfifo fifo/il_S1_summarycalc_P1 mkfifo fifo/il_S1_pltcalc_P1 # --- Do insured loss computes --- eltcalc < fifo/il_S1_eltcalc_P1 > work/kat/il_S1_eltcalc_P1 & pid1=$! summarycalctocsv < fifo/il_S1_summarycalc_P1 > work/kat/il_S1_summarycalc_P1 & pid2=$! pltcalc < fifo/il_S1_pltcalc_P1 > work/kat/il_S1_pltcalc_P1 & pid3=$! tee < fifo/il_S1_summary_P1 fifo/il_S1_eltcalc_P1 fifo/il_S1_summarycalc_P1 fifo/il_S1_pltcalc_P1 work/il_S1_summaryaalcalc/P1.bin work/il_S1_summaryleccalc/P1.bin > /dev/null & pid4=$! ( summarycalc -f -1 fifo/il_S1_summary_P1 < fifo/il_P1 ) 2>> log/stderror.err & # --- Do ground up loss computes --- eltcalc < fifo/gul_S1_eltcalc_P1 > work/kat/gul_S1_eltcalc_P1 & pid5=$! summarycalctocsv < fifo/gul_S1_summarycalc_P1 > work/kat/gul_S1_summarycalc_P1 & pid6=$! pltcalc < fifo/gul_S1_pltcalc_P1 > work/kat/gul_S1_pltcalc_P1 & pid7=$! tee < fifo/gul_S1_summary_P1 fifo/gul_S1_eltcalc_P1 fifo/gul_S1_summarycalc_P1 fifo/gul_S1_pltcalc_P1 work/gul_S1_summaryaalcalc/P1.bin work/gul_S1_summaryleccalc/P1.bin > /dev/null & pid8=$! ( summarycalc -i -1 fifo/gul_S1_summary_P1 < fifo/gul_P1 ) 2>> log/stderror.err & ( eve 1 1 | getmodel | gulcalc -S0 -L0 -r -a1 -i - | tee fifo/gul_P1 | fmcalc -a2 > fifo/il_P1 ) 2>> log/stderror.err & wait $pid1 $pid2 $pid3 $pid4 $pid5 $pid6 $pid7 $pid8 # --- Do insured loss kats --- kat work/kat/il_S1_eltcalc_P1 > output/il_S1_eltcalc.csv & kpid1=$! kat work/kat/il_S1_pltcalc_P1 > output/il_S1_pltcalc.csv & kpid2=$! kat work/kat/il_S1_summarycalc_P1 > output/il_S1_summarycalc.csv & kpid3=$! # --- Do ground up loss kats --- kat work/kat/gul_S1_eltcalc_P1 > output/gul_S1_eltcalc.csv & kpid4=$! kat work/kat/gul_S1_pltcalc_P1 > output/gul_S1_pltcalc.csv & kpid5=$! kat work/kat/gul_S1_summarycalc_P1 > output/gul_S1_summarycalc.csv & kpid6=$! wait $kpid1 $kpid2 $kpid3 $kpid4 $kpid5 $kpid6 aalcalc -Kil_S1_summaryaalcalc > output/il_S1_aalcalc.csv & lpid1=$! leccalc -r -Kil_S1_summaryleccalc -F output/il_S1_leccalc_full_uncertainty_aep.csv -f output/il_S1_leccalc_full_uncertainty_oep.csv -S output/il_S1_leccalc_sample_mean_aep.csv -s output/il_S1_leccalc_sample_mean_oep.csv -W output/il_S1_leccalc_wheatsheaf_aep.csv -M output/il_S1_leccalc_wheatsheaf_mean_aep.csv -m output/il_S1_leccalc_wheatsheaf_mean_oep.csv -w output/il_S1_leccalc_wheatsheaf_oep.csv & lpid2=$! aalcalc -Kgul_S1_summaryaalcalc > output/gul_S1_aalcalc.csv & lpid3=$! leccalc -r -Kgul_S1_summaryleccalc -F output/gul_S1_leccalc_full_uncertainty_aep.csv -f output/gul_S1_leccalc_full_uncertainty_oep.csv -S output/gul_S1_leccalc_sample_mean_aep.csv -s output/gul_S1_leccalc_sample_mean_oep.csv -W output/gul_S1_leccalc_wheatsheaf_aep.csv -M output/gul_S1_leccalc_wheatsheaf_mean_aep.csv -m output/gul_S1_leccalc_wheatsheaf_mean_oep.csv -w output/gul_S1_leccalc_wheatsheaf_oep.csv & lpid4=$! wait $lpid1 $lpid2 $lpid3 $lpid4 rm -R -f work/* rm -R -f fifo/* check_complete exit_handler
SELECT * FROM Image WHERE Id = :uuid;
#!/usr/bin/env bash # Step 1: # Build image and add a descriptive tag docker build -t nextjs . # Step 2: # List docker images docker image ls # Step 3: # Retrieve an authentication token # and authenticate Docker client to registry aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/y5l2b5h6 # Step 4: # tag docker tag nextjs public.ecr.aws/y5l2b5h6/nextjs:green # Step 5: # Push image to a AWS repository docker push public.ecr.aws/y5l2b5h6/nextjs:green
/* * Copyright 2014-2016 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaaproject.kaa.server.control.service.sdk; import org.apache.commons.codec.binary.Base64; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.kaaproject.kaa.server.common.zk.ServerNameUtil; import org.kaaproject.kaa.server.common.zk.gen.BootstrapNodeInfo; import org.kaaproject.kaa.server.common.zk.gen.TransportMetaData; import org.kaaproject.kaa.server.common.zk.gen.VersionConnectionInfoPair; import org.kaaproject.kaa.server.control.service.sdk.compress.TarEntryData; import java.util.List; public class CommonSdkUtil { private static final String SEPARATOR = ":"; private CommonSdkUtil(){ } public static TarEntryData tarEntryForSources(String source, String name) { TarArchiveEntry tarEntry = new TarArchiveEntry(name); tarEntry.setSize(source.getBytes().length); return new TarEntryData(tarEntry, source.getBytes()); } public static String bootstrapNodesToString(List<BootstrapNodeInfo> bootstrapNodes) { String bootstrapServers = ""; if (bootstrapNodes != null && !bootstrapNodes.isEmpty()) { for (BootstrapNodeInfo node : bootstrapNodes) { List<TransportMetaData> supportedChannels = node.getTransports(); int accessPointId = ServerNameUtil.crc32(node.getConnectionInfo()); for (TransportMetaData transport : supportedChannels) { for (VersionConnectionInfoPair pair : transport.getConnectionInfo()) { bootstrapServers += accessPointId; bootstrapServers += SEPARATOR; bootstrapServers += transport.getId(); bootstrapServers += SEPARATOR; bootstrapServers += pair.getVersion(); bootstrapServers += SEPARATOR; bootstrapServers += Base64.encodeBase64String(pair.getConenctionInfo().array()); bootstrapServers += ";"; } } } } return bootstrapServers; } }
require(['jquery','tools'], function ($) { var goodsid = $.getQueryString("goodsid"); var sign_seller = $.getQueryString("sign_seller"); var isEdit = $.getQueryString("edit"); if (isEdit=="1"){ $('.success strong').html('修改成功啦!') } var publish={ init:function(){ this.modifyDom(); this.share(); }, share:function(){ window._bd_share_config = { "common": { bdText: "发布成功啦~", bdDesc: "我在虚贝等你开黑哦!!!", bdUrl: 'http://www.xubei.com', }, share: [{ "bdSize": 24 }] } with (document) 0[(getElementsByTagName('head')[0] || body).appendChild(createElement('script')).src = 'http://bdimg.share.baidu.com/static/api/js/share.js?cdnversion=' + ~(-new Date() / 36e5)]; }, modifyDom:function(){ if (sign_seller=="1"){ $('.isSign').show(); $('#goodsDetail').attr('href', 'http://new.xubei.com/goods_details_xa.html?goodsId='+ goodsid) }else{ $('.isSign').hide(); $('#goodsDetail').hide(); } } } publish.init(); })
/** * @author ooooo * @date 2021/3/24 16:38 */ #ifndef CPP_0456__SOLUTION2_H_ #define CPP_0456__SOLUTION2_H_ #include <iostream> #include <vector> #include <stack> using namespace std; // o(n) class Solution { public: bool find132pattern(vector<int> &nums) { int n = nums.size(); if (n < 3) { return false; } stack<int> maxStack; int last = INT_MIN; for (int i = n - 1; i >= 0; --i) { if (nums[i] < last) { return true; } while (!maxStack.empty() && maxStack.top() < nums[i]) { last = maxStack.top(); maxStack.pop(); } maxStack.push(nums[i]); } return false; } }; #endif //CPP_0456__SOLUTION2_H_
public class Test { public static void main(String[] args) { int start = 5; int end = 10; for(int i=start; i<=end; i++){ System.out.println(i); } } } // prints 5 6 7 8 9 10
<filename>lang/py/pylib/code/Queue/Queue_priority.py #!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2010 <NAME>. All rights reserved. # """PriorityQueue """ #end_pymotw_header import Queue import threading class Job(object): def __init__(self, priority, description): self.priority = priority self.description = description print 'New job:', description return def __cmp__(self, other): return cmp(self.priority, other.priority) q = Queue.PriorityQueue() q.put( Job(3, 'Mid-level job') ) q.put( Job(10, 'Low-level job') ) q.put( Job(1, 'Important job') ) def process_job(q): while True: next_job = q.get() print 'Processing job:', next_job.description q.task_done() workers = [ threading.Thread(target=process_job, args=(q,)), threading.Thread(target=process_job, args=(q,)), ] for w in workers: w.setDaemon(True) w.start() q.join()
<gh_stars>1-10 import React from 'react'; import PropTypes from 'prop-types'; import { Form } from 'semantic'; import SearchDropdown from 'components/SearchDropdown'; import SearchContext from '../Context'; export default class DropdownFilter extends React.Component { static contextType = SearchContext; getDefaultValue() { const { multiple } = this.props; return multiple ? [] : ''; } getValue() { const { name } = this.props; return this.context.getFilterValue(name) || this.getDefaultValue(); } getOptions() { let { options } = this.props; if (!options) { const value = this.getValue(); const arr = Array.isArray(value) ? value : [value]; return arr.map((value) => { return { value, text: value, }; }); } } render() { if (this.props.onDataNeeded) { const { label, disabled, error, ...rest } = this.props; return ( <Form.Field disabled={disabled} error={error}> <label>{label}</label> <SearchDropdown value={this.getValue()} onChange={this.context.onFilterChange} {...rest} /> </Form.Field> ); } else { return ( <Form.Dropdown value={this.getValue()} options={this.getOptions()} onChange={this.context.onFilterChange} {...this.props} /> ); } } } DropdownFilter.propTypes = { name: PropTypes.string.isRequired, label: PropTypes.string.isRequired, }; DropdownFilter.defaultProps = { fluid: true, search: false, clearable: true, selection: true, };
def add_embed_footer(embed_dict: dict) -> dict: if "footer" not in embed_dict: modified_embed = embed_dict.copy() modified_embed["footer"] = {"text": "Use felix help <command/category> for more information."} return modified_embed else: return embed_dict
const path = require('path'); module.exports = { entry: { app: './src/Timer.js', }, module: { rules: [ { exclude: [/node_modules/], test: /\.js$/, use: [{ loader: 'babel-loader', }], }, ], }, output: { filename: 'danehansen-Timer.min.js', library: ['danehansen', 'Timer'], libraryTarget: 'umd', path: __dirname, }, externals: [ { '@danehansen/event-dispatcher': { amd: '@danehansen/event-dispatcher', commonjs: '@danehansen/event-dispatcher', commonjs2: '@danehansen/event-dispatcher', root: ['danehansen', 'EventDispatcher'], }, }, ], }
#!/usr/bin/env bash # Copyright 2020 Antrea Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This script applies unreleased patches (or released in a more recent version # of OVS than the one Antrea is using) to OVS before building it. It needs to be # run from the root of the OVS source tree. set -eo pipefail function echoerr { >&2 echo "$@" } # Inspired from https://stackoverflow.com/a/24067243/4538702 # 'sort -V' is available on Ubuntu 18.04 # less than function version_lt() { test "$(printf '%s\n' "$@" | sort -rV | head -n 1)" != "$1"; } # greater than function version_gt() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1"; } # greater than or equal to function version_get() { test "$(printf '%s\n' "$@" | sort -rV | head -n 1)" == "$1"; } if version_lt "$OVS_VERSION" "2.11.0" || version_gt "$OVS_VERSION" "2.13.0"; then echoerr "OVS_VERSION $OVS_VERSION is not supported (must be >= 2.11.0 and <= 2.13.0)" exit 1 fi # We cannot use 3-way merge unless we are in a git repository. If we need 3-way # merge, we will need to clone the repository with git instead of downloading a # release tarball (see Dockerfile). # These 2 patches (post 2.13.0) ensures that datapath flows are not deleted on # ovs-vswitchd exit by default. Antrea relies on this to support hitless upgrade # of the Agent DaemonSet. # The second patch depends on the first one. curl https://github.com/openvswitch/ovs/commit/586cd3101e7fda54d14fb5bf12d847f35d968627.patch | \ git apply # We exclude 2 files which are likely to cause conflicts. curl https://github.com/openvswitch/ovs/commit/79eadafeb1b47a3871cb792aa972f6e4d89d1a0b.patch | \ git apply --exclude NEWS --exclude vswitchd/ovs-vswitchd.8.in # This patch (post 2.13.0) ensures that ovs-vswitchd does not delete datapath # ports on exit. curl https://github.com/openvswitch/ovs/commit/7cc77b301f80a63cd4893198d82be0eef303f731.patch | \ git apply if version_get "$OVS_VERSION" "2.13.0"; then # OVS hardcodes the installation path to /usr/lib/python3.7/dist-packages/ but this location # does not seem to be in the Python path in Ubuntu 18.04. There may be a better way to do this, # but this seems like an acceptable workaround. sed -i 's/python3\.7/python3\.6/' debian/openvswitch-test.install sed -i 's/python3\.7/python3\.6/' debian/python3-openvswitch.install fi
[ { "name": "John", "age": 21, "year_level": 3 } ]
// insertion-sort 'use strict'; export default ( array, compare ) => { // Not an array, empty or array of 1 is already sorted if ( !Array.isArray( array ) || array.length < 2 ) { return array; } // Swap elements of the array const swap = ( array, first, second ) => { const temp = array[ first ]; array[ first ] = array[ second ]; array[ second ] = temp; return array; }; // Create a compare function if one is not passed in if ( typeof compare !== 'function' ) { compare = ( a, b ) => { return a > b ? 1 : -1; }; } let i; let j; /* * Assume first element is sorted * Add first unsorted element to sorted array * Compare new element in sorted array with previous elements * to determine correct destination index in sorted array */ for ( i = 1; i < array.length; i++ ) { j = i; // Make sure we don't walk off the array and compare until sorted while ( ( j - 1 ) >= 0 && compare( array[ j ], array[ j - 1 ] ) < 0 ) { swap( array, j, j - 1 ); j--; } } return array; };
<filename>src/main/java/com/haufelexware/gocd/dto/GoMaterialRevision.java package com.haufelexware.gocd.dto; import java.util.List; /** * DTO for a material revision in a pipeline. */ public class GoMaterialRevision { private GoMaterial material; private boolean changed; private List<GoModification> modifications; public GoMaterial getMaterial() { return material; } public void setMaterial(GoMaterial material) { this.material = material; } public boolean isChanged() { return changed; } public void setChanged(boolean changed) { this.changed = changed; } public List<GoModification> getModifications() { return modifications; } public void setModifications(List<GoModification> modifications) { this.modifications = modifications; } }
use std::fs; use std::path::Path; fn create_echo_script(directory: &str, script_name: &str) -> Result<String, String> { let script_path = Path::new(directory).join(script_name); let script_content = r#" #/usr/bin/env bash printf "%s" "$*" 1>&2 "#; match fs::write(&script_path, script_content) { Ok(_) => Ok(script_path.to_string_lossy().into_owned()), Err(e) => Err(format!("Error creating script file: {}", e)), } }
#!/bin/bash sudo docker-compose up -d;
import cv2 import matplotlib.pyplot as plt def apply_image_transformation(input_image_path): # Read the input image using OpenCV input_image = cv2.imread(input_image_path) # Apply a specific transformation (e.g., grayscale conversion) transformed_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY) # Display the original and transformed images side by side plt.subplot(121), plt.imshow(cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB)) plt.title('Original Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122), plt.imshow(transformed_image, cmap='gray') plt.title('Transformed Image'), plt.xticks([]), plt.yticks([]) plt.show() # Example usage apply_image_transformation('input_image.jpg')
#!/usr/bin/env bash BEDROCK_VERSION=${BEDROCK_VERSION:-1.17.10.04} echo "Creating git tag for version ${BEDROCK_VERSION}..." git tag ${BEDROCK_VERSION} echo "Pushing tags..." git push --tags echo "Done."
export const versionString = "Calla v0.2.7";
if test $# -eq 0 then echo "usage: $0 <test header file> <toolset> [<target>]" else export BOOST_ARCHIVE_LIST=$1 runtest.ksh $2 $3 fi
<gh_stars>1000+ // Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !amd64,!ppc64le gccgo purego package poly1305 type mac struct{ macGeneric } func newMAC(key *[32]byte) mac { return mac{newMACGeneric(key)} }
/* Run-Length Encoding (c) <NAME> ENCODER */ #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <string> #include <sstream> using namespace std; string to_string(int t) { ostringstream os; os << t; return os.str(); } int main() { ifstream in; string filename; string outputfile; cout << "Run-Length Encoding" << endl; cout << "https://github.com/AfaanBilal/run-length-encoding" << endl << endl; cout << "ENCODER" << endl; cout << "Enter input filename : "; cin >> filename; cout << "Enter output filename: "; cin >> outputfile; in.open(filename, ios::in | ios::binary); if(in.is_open()) { streampos start = in.tellg(); in.seekg(0, ios::end); streampos end = in.tellg(); in.seekg(0, ios::beg); std::vector<char> contents; contents.resize(static_cast<size_t>(end - start)); in.read(&contents[0], contents.size()); std::vector<char> compressed; int cCount = 1; char prevChar = 0; for(const char& c : contents) { if (c == prevChar) cCount++; else if (prevChar != 0) { compressed.push_back(prevChar); string count_str = to_string(cCount); for(const char& cc : count_str) compressed.push_back(cc); cCount = 1; } prevChar = c; } compressed.push_back(prevChar); string count_str = to_string(cCount); for(const char& cc : count_str) compressed.push_back(cc); std::string original_str(contents.begin(), contents.end()); std::string compressed_str(compressed.begin(), compressed.end()); ofstream outf(outputfile, ios::out | ios::binary); if (outf.is_open()) outf << compressed_str; else cout << "Error: could not open output file: " << outputfile; int comp_ratio = (float)compressed_str.length() / original_str.length() * 100; cout << endl; cout << "Original : " << original_str << endl; cout << "Compressed: " << compressed_str << endl; cout << "Compression ratio: " << comp_ratio << "%" << endl; } else { cout << "Error: could not open file: " << filename; } }
<reponame>HobbsSquad/Menu-Master-UI-React import { REQUEST_DAYS, DAYS_SUCCESS, DAYS_FAIL, REQUEST_CURRENT_DAY, CURRENT_DAY_SUCCESS, CURRENT_DAY_FAIL, REQUEST_NEW_DAY, NEW_DAY_SUCCESS, NEW_DAY_FAIL, REQUEST_MEALS, MEALS_SUCCESS, MEALS_FAIL } from "../actionTypes/menu"; const initialState = { daysStatus: '', days: null, currentDayStatus: '', currentDay: null, newDayStatus: '', mealsStatus: '', meals: null }; const menu = (state = initialState, action) => { switch (action.type) { case REQUEST_DAYS: { return { ...state, daysStatus: 'requestingDays' } } case DAYS_SUCCESS: { return { ...state, daysStatus: 'daysLoaded', days: action.days } } case DAYS_FAIL: { return { ...state, daysStatus: 'daysFailed', days: null } } case REQUEST_CURRENT_DAY: { return { ...state, currentDayStatus: 'requestingCurrentDay' } } case CURRENT_DAY_SUCCESS: { return { ...state, currentDayStatus: 'currentDayLoaded', currentDay: action.currentDay } } case CURRENT_DAY_FAIL: { return { ...state, currentDayStatus: 'currentDayFailed', currentDay: null } } case REQUEST_NEW_DAY: { return { ...state, newDayStatus: 'requestingNewDay' } } case NEW_DAY_SUCCESS: { return { ...state, newDayStatus: 'newDaySuccess', days: action.days } } case NEW_DAY_FAIL: { return { ...state, newDayStatus: 'newDayFail' } } case REQUEST_MEALS: { return { ...state, mealsStatus: 'requestingMeals' } } case MEALS_SUCCESS: { return { ...state, mealsStatus: 'mealsSuccess', meals: action.meals } } case MEALS_FAIL: { return { ...state, mealsStatus: 'mealsFail' } } default: return state; } } export default menu
class Stats: def __init__(self, errors): self.errors = errors def __iadd__(self, other): for i in range(len(self.errors)): for j in range(len(self.errors[i])): self.errors[i][j] += other.errors[i][j] return self def back(self): return self.errors[-1] # Usage end_stats2 = Stats([[0, 0, 0, 0], [0, 0, 0, 0]]) end_stats2.errors[10][1] = 14 end_stats2.errors[10][3] = 5 end_stats2.errors[15][0] = 90 end_stats2.errors[15][1] = 17 end_stats2.errors[15][2] = 2 stats = Stats([[0, 0, 0, 0], [0, 0, 0, 0]]) stats += end_stats2 r = stats.back() print(r) # Output: [90, 17, 2, 5]
#ifndef RING_HPP #define RING_HPP #include<iostream> #include<cassert> #include<cstdint> namespace Ring { class ring{ private: std::uint32_t n; std::uint32_t value; //n>value and (value>0 no always) ,n>0 ,n =[2,2^31) ; public: explicit ring(std::uint32_t init_n, std::int64_t init_v=0); bool operator==(const ring& b)const; bool operator!=(const ring& b)const; //unary operation; ring operator+()const {return *this;} ring operator-()const {return ring{n,(n-value)};} //binary operation; ring operator+(const ring& b)const; ring operator -(const ring& b)const; ring operator *(const ring& b)const; //finding reverse element; ring inverse() const; //output value; friend std::ostream& operator<<(std::ostream& out_line, const ring& r); //converse bool and uint32_t explicit operator bool() const { return (value);} explicit operator std::uint32_t()const {return(value);} }; } #endif // RING_HPP
<gh_stars>1-10 module Workflow class UpdatePolicySelection end end
<reponame>knpwrs/common-breakpoints export default { mobile: 0, tablet: 769, desktop: 1024, widescreen: 1216, fullhd: 1408, }; export { bulma as queries } from './queries';
<reponame>meder/scorecard<gh_stars>1-10 // Copyright 2020 Security Scorecard Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package checks import ( "context" "net/http" "testing" "github.com/google/go-github/v38/github" "github.com/ossf/scorecard/v2/checker" sce "github.com/ossf/scorecard/v2/errors" scut "github.com/ossf/scorecard/v2/utests" ) type mockRepos struct { branches []*string protections map[string]*github.Protection defaultBranch *string releases []*string nonadmin bool } func (m mockRepos) Get(ctx context.Context, o, r string) ( *github.Repository, *github.Response, error) { return &github.Repository{ DefaultBranch: m.defaultBranch, }, nil, nil } func (m mockRepos) ListReleases(ctx context.Context, owner string, repo string, opts *github.ListOptions) ([]*github.RepositoryRelease, *github.Response, error) { res := make([]*github.RepositoryRelease, len(m.releases)) for i, rel := range m.releases { res[i] = &github.RepositoryRelease{TargetCommitish: rel} } return res, nil, nil } func (m mockRepos) GetBranchProtection(ctx context.Context, o string, r string, b string) (*github.Protection, *github.Response, error) { if !m.nonadmin { p, ok := m.protections[b] if ok { return p, &github.Response{ Response: &http.Response{StatusCode: http.StatusAccepted}, }, nil } } return nil, &github.Response{ Response: &http.Response{StatusCode: http.StatusNotFound}, }, //nolint sce.Create(sce.ErrScorecardInternal, errInternalBranchNotFound.Error()) } func (m mockRepos) ListBranches(ctx context.Context, owner string, repo string, opts *github.BranchListOptions) ([]*github.Branch, *github.Response, error) { res := make([]*github.Branch, len(m.branches)) for i, rel := range m.branches { _, protected := m.protections[*rel] res[i] = &github.Branch{Name: rel, Protected: &protected} } return res, nil, nil } func TestReleaseAndDevBranchProtected(t *testing.T) { t.Parallel() rel1 := "release/v.1" sha := "8fb3cb86082b17144a80402f5367ae65f06083bd" main := "main" //nolint tests := []struct { name string expected scut.TestReturn branches []*string defaultBranch *string releases []*string protections map[string]*github.Protection nonadmin bool }{ { name: "Only development branch", expected: scut.TestReturn{ Errors: nil, Score: 1, NumberOfWarn: 6, NumberOfInfo: 2, NumberOfDebug: 0, }, defaultBranch: &main, branches: []*string{&rel1, &main}, releases: nil, protections: map[string]*github.Protection{ "main": { RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: false, Contexts: nil, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: false, RequireCodeOwnerReviews: false, RequiredApprovingReviewCount: 0, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: false, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: false, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, }, }, { name: "Take worst of release and development", expected: scut.TestReturn{ Errors: nil, Score: 5, NumberOfWarn: 8, NumberOfInfo: 9, NumberOfDebug: 0, }, defaultBranch: &main, branches: []*string{&rel1, &main}, releases: []*string{&rel1}, protections: map[string]*github.Protection{ "main": { RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: true, Contexts: []string{"foo"}, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: true, RequireCodeOwnerReviews: true, RequiredApprovingReviewCount: 1, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: true, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: true, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, "release/v.1": { RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: false, Contexts: nil, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: false, RequireCodeOwnerReviews: false, RequiredApprovingReviewCount: 0, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: false, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: false, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, }, }, { name: "Both release and development are OK", expected: scut.TestReturn{ Errors: nil, Score: 9, NumberOfWarn: 4, NumberOfInfo: 14, NumberOfDebug: 0, }, defaultBranch: &main, branches: []*string{&rel1, &main}, releases: []*string{&rel1}, protections: map[string]*github.Protection{ "main": { RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: true, Contexts: []string{"foo"}, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: true, RequireCodeOwnerReviews: true, RequiredApprovingReviewCount: 1, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: true, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: true, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, "release/v.1": { RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: true, Contexts: []string{"foo"}, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: true, RequireCodeOwnerReviews: true, RequiredApprovingReviewCount: 1, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: true, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: true, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, }, }, { name: "Ignore a non-branch targetcommitish", expected: scut.TestReturn{ Errors: nil, Score: 1, NumberOfWarn: 6, NumberOfInfo: 2, NumberOfDebug: 0, }, defaultBranch: &main, branches: []*string{&rel1, &main}, releases: []*string{&sha}, protections: map[string]*github.Protection{ "main": { RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: false, Contexts: nil, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: false, RequireCodeOwnerReviews: false, RequiredApprovingReviewCount: 0, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: false, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: false, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, }, }, { name: "TargetCommittish nil", expected: scut.TestReturn{ Errors: []error{sce.ErrScorecardInternal}, Score: checker.InconclusiveResultScore, NumberOfWarn: 0, NumberOfInfo: 0, NumberOfDebug: 0, }, defaultBranch: &main, branches: []*string{&main}, releases: []*string{nil}, protections: map[string]*github.Protection{ "main": { RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: false, Contexts: nil, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: false, RequireCodeOwnerReviews: false, RequiredApprovingReviewCount: 0, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: false, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: false, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, }, }, { name: "Non-admin check with protected release and development", expected: scut.TestReturn{ Errors: nil, Score: 1, NumberOfWarn: 2, NumberOfInfo: 0, NumberOfDebug: 0, }, nonadmin: true, defaultBranch: &main, branches: []*string{&rel1, &main}, releases: []*string{&rel1}, protections: map[string]*github.Protection{ "main": { RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: true, Contexts: []string{"foo"}, }, }, "release/v.1": { RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: true, Contexts: []string{"foo"}, }, }, }, }, } for _, tt := range tests { tt := tt // Re-initializing variable so it is not changed while executing the closure below t.Run(tt.name, func(t *testing.T) { t.Parallel() m := mockRepos{ defaultBranch: tt.defaultBranch, branches: tt.branches, releases: tt.releases, protections: tt.protections, nonadmin: tt.nonadmin, } dl := scut.TestDetailLogger{} r := checkReleaseAndDevBranchProtection(context.Background(), m, &dl, "testowner", "testrepo") scut.ValidateTestReturn(t, tt.name, &tt.expected, &r, &dl) }) } } func TestIsBranchProtected(t *testing.T) { t.Parallel() tests := []struct { name string protection *github.Protection expected scut.TestReturn }{ { name: "Nothing is enabled", expected: scut.TestReturn{ Errors: nil, Score: 1, NumberOfWarn: 6, NumberOfInfo: 2, NumberOfDebug: 0, }, protection: &github.Protection{ RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: false, Contexts: nil, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: false, RequireCodeOwnerReviews: false, RequiredApprovingReviewCount: 0, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: false, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: false, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, }, { name: "Nothing is enabled and values in github.Protection are nil", expected: scut.TestReturn{ Errors: nil, Score: 1, NumberOfWarn: 4, NumberOfInfo: 2, NumberOfDebug: 0, }, protection: &github.Protection{}, }, { name: "Required status check enabled", expected: scut.TestReturn{ Errors: nil, Score: 2, NumberOfWarn: 6, NumberOfInfo: 3, NumberOfDebug: 0, }, protection: &github.Protection{ RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: true, Contexts: []string{"foo"}, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: false, RequireCodeOwnerReviews: false, RequiredApprovingReviewCount: 0, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: false, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: false, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, }, { name: "Required status check enabled without checking for status string", expected: scut.TestReturn{ Errors: nil, Score: 2, NumberOfWarn: 6, NumberOfInfo: 3, NumberOfDebug: 0, }, protection: &github.Protection{ RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: true, Contexts: nil, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: false, RequireCodeOwnerReviews: false, RequiredApprovingReviewCount: 0, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: false, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: false, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, }, { name: "Required pull request enabled", expected: scut.TestReturn{ Errors: nil, Score: 2, NumberOfWarn: 5, NumberOfInfo: 3, NumberOfDebug: 0, }, protection: &github.Protection{ RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: false, Contexts: []string{"foo"}, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: false, RequireCodeOwnerReviews: false, RequiredApprovingReviewCount: 1, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: false, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: true, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, }, { name: "Required admin enforcement enabled", expected: scut.TestReturn{ Errors: nil, Score: 3, NumberOfWarn: 5, NumberOfInfo: 3, NumberOfDebug: 0, }, protection: &github.Protection{ RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: false, Contexts: []string{"foo"}, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: false, RequireCodeOwnerReviews: false, RequiredApprovingReviewCount: 0, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: true, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: false, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, }, { name: "Required linear history enabled", expected: scut.TestReturn{ Errors: nil, Score: 2, NumberOfWarn: 5, NumberOfInfo: 3, NumberOfDebug: 0, }, protection: &github.Protection{ RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: false, Contexts: []string{"foo"}, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: false, RequireCodeOwnerReviews: false, RequiredApprovingReviewCount: 0, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: false, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: true, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, }, { name: "Allow force push enabled", expected: scut.TestReturn{ Errors: nil, Score: 0, NumberOfWarn: 7, NumberOfInfo: 1, NumberOfDebug: 0, }, protection: &github.Protection{ RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: false, Contexts: []string{"foo"}, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: false, RequireCodeOwnerReviews: false, RequiredApprovingReviewCount: 0, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: false, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: false, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: true, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, }, { name: "Allow deletions enabled", expected: scut.TestReturn{ Errors: nil, Score: 0, NumberOfWarn: 7, NumberOfInfo: 1, NumberOfDebug: 0, }, protection: &github.Protection{ RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: false, Contexts: []string{"foo"}, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: false, RequireCodeOwnerReviews: false, RequiredApprovingReviewCount: 0, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: false, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: false, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: true, }, }, }, { name: "Branches are protected", expected: scut.TestReturn{ Errors: nil, Score: 9, NumberOfWarn: 2, NumberOfInfo: 7, NumberOfDebug: 0, }, protection: &github.Protection{ RequiredStatusChecks: &github.RequiredStatusChecks{ Strict: true, Contexts: []string{"foo"}, }, RequiredPullRequestReviews: &github.PullRequestReviewsEnforcement{ DismissalRestrictions: &github.DismissalRestrictions{ Users: nil, Teams: nil, }, DismissStaleReviews: true, RequireCodeOwnerReviews: true, RequiredApprovingReviewCount: 1, }, EnforceAdmins: &github.AdminEnforcement{ URL: nil, Enabled: true, }, Restrictions: &github.BranchRestrictions{ Users: nil, Teams: nil, Apps: nil, }, RequireLinearHistory: &github.RequireLinearHistory{ Enabled: true, }, AllowForcePushes: &github.AllowForcePushes{ Enabled: false, }, AllowDeletions: &github.AllowDeletions{ Enabled: false, }, }, }, } for _, tt := range tests { tt := tt // Re-initializing variable so it is not changed while executing the closure below t.Run(tt.name, func(t *testing.T) { t.Parallel() dl := scut.TestDetailLogger{} score := IsBranchProtected(tt.protection, "test", &dl) scut.ValidateTestValues(t, tt.name, &tt.expected, score, nil, &dl) }) } }
import axios from 'axios'; export let progress const axiosConfig = { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept':'application/json' }, timeout: 5000, } const qs = require('querystring') const api = axios.create({ baseURL: 'http://localhost/teste-unilab' }) export async function index() { try { const response = await api.get('/products', axiosConfig ) if (response) { console.log(response.data); return response.data } } catch (e) { console.log(e.message); } } export async function _delete(ids){ // async function conetion(id){ try { const response = await api.post(`/products/delete/${ids}`, {},axiosConfig ) if (response) { console.log(response.data); return response.data } } catch (e) { console.log(e.message); } // } console.log(ids); // ids.map(id =>conetion(id)) } export async function show(id) { try { const response = await api.get(`/products/${id}`, { // params:{ // } } ) if (response) { console.log(response.data); return response.data } } catch (e) { console.log(e.message); } } export async function find( brand, size, amout, value ) { try { const response = await api.get(`/products/find`, { params: { brand, size, amout, value } }, axiosConfig ) if (response) { console.log(response.data); return response.data } } catch (e) { console.log(e.message); } } export async function update( id, id_brand, flavor_name, type_ref, size_ref, amout, value ) { try { const requestBody={ id_brand, flavor_name, type_ref, size_ref, amout, value } const response = await api.post(`/products/${id}`, qs.stringify(requestBody), axiosConfig ) if (response) { console.log(response.data); return response } } catch (e) { console.log(e.message); } } export async function create( id_brand, flavor_name, type_ref, size_ref, amout, value ) { try { console.log({ data: { id_brand, flavor_name, type_ref, size_ref, amout, value }} ) const requestBody={ id_brand, flavor_name, type_ref, size_ref, amout, value } const response = await api.post('/products', qs.stringify(requestBody), axiosConfig ) if (response) { return response.data } } catch (e) { const message = "Error" return message } }
from datetime import datetime, timedelta from pytz import timezone, UTC from googleapiclient.discovery import build from google.oauth2.credentials import Credentials from google.auth.transport.requests import Request from google.auth.exceptions import RefreshError from harvestreaper.googlecal.views import GoogleOAuth2Adapter from harvestreaper.settings import GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET STRPTIME_UTIL = "%Y-%m-%dT%H:%M:%S%z" STRFTIME_UTIL = "%I:%M %p" def _get_creds(token): now = UTC.localize(datetime.now()) creds = Credentials(token=token.token, refresh_token=token.token_secret, token_uri=GoogleOAuth2Adapter.access_token_url, client_id=GOOGLE_CLIENT_ID, client_secret=GOOGLE_CLIENT_SECRET) # Refresh the token if the token is expired if now > token.expires_at: try: creds.refresh(Request()) except RefreshError: print('Error: User failed to have their token refreshed') return None token.token = creds.token token.token_secret = creds.refresh_token token.expires_at = UTC.localize(creds.expiry) token.save() return creds def get_calendar_events(token, start_date, end_date): creds = _get_creds(token) if creds is None: return None service = build('calendar', 'v3', credentials=creds) formatted_start = start_date.isoformat() + 'Z' formatted_end = end_date.isoformat() + 'Z' massaged_events = { 'Sat': [], 'Sun': [], 'Mon': [], 'Tue': [], 'Wed': [], 'Thu': [], 'Fri': [] } try: events_result = service.events().list(calendarId='primary', timeMin=formatted_start, timeMax=formatted_end, singleEvents=True, orderBy='startTime').execute() except Exception as e: print(e) return massaged_events events = events_result.get('items', []) for event in events: start = event['start'].get('dateTime') end = event['end'].get('dateTime') day_of_week = None declined_event = False massaged_start = "09:00" massaged_end = "05:00" duration = 8 * 60 * 60 for attendee in event.get('attendees', []): if attendee.get('self', '') is True and attendee.get('responseStatus', '') == 'declined': # noqa declined_event = True if declined_event: continue if start and end: start_obj = datetime.strptime(start, STRPTIME_UTIL) end_obj = datetime.strptime(end, STRPTIME_UTIL) day_of_week = start_obj.strftime('%a') duration = (end_obj - start_obj).total_seconds() massaged_start = start_obj.strftime(STRFTIME_UTIL) massaged_end = end_obj.strftime(STRFTIME_UTIL) else: # Check to see if it's a multi day event # NOTE: We don't present multi day events because there are so many edges at the moment full_day_start = datetime.strptime(event['start'].get('date'), '%Y-%m-%d') full_day_end = datetime.strptime(event['end'].get('date'), '%Y-%m-%d') if full_day_start.day != full_day_end.day - 1: # 12am - 12am next day (hence - 1 day) continue raw_day = timezone('US/Eastern').localize(full_day_start) day_of_week = raw_day.strftime('%a') start = datetime.strftime(raw_day + timedelta(hours=9), STRPTIME_UTIL) # Set to 9AM by default massaged_start = "09:00 AM" massaged_end = "05:00 PM" massaged_events[day_of_week].append({ "start": massaged_start, "raw_start": start, "end": massaged_end, "duration": round(duration / 60 / 60, 2), "summary": event['summary'] if 'summary' in event else '' }) return massaged_events
// Custom exception class for handling interruptions during report filling process public class ReportFillInterruptedException extends Exception { // Constructor with a message parameter public ReportFillInterruptedException(String message) { super(message); // Call superclass constructor with the message } // Override getMessage method to provide detailed exception message @Override public String getMessage() { return "Report filling process interrupted: " + super.getMessage(); } } // Sample usage of ReportFillInterruptedException in a report generation system public class ReportGenerator { public void fillReport() { try { // Filling process logic if (/* interruption condition */) { throw new ReportFillInterruptedException("Data source connection lost"); } // Continue filling process } catch (ReportFillInterruptedException e) { System.out.println("Exception: " + e.getMessage()); // Handle interruption gracefully } } }
#!/usr/bin/env bash set -euo pipefail SCRIPT_DIR="$1" FILES_DIR="$2" echo "[Install] Installing packages" SYSTEM="base linux e2fsprogs dosfstools systemd-resolvconf openssh reflector" GUEST_UTILS="virtualbox-guest-utils-nox" UTILS="neovim wget curl sudo man-db man-pages texinfo" SHELL="zsh grml-zsh-config" PACKAGES="$SYSTEM $GUEST_UTILS $UTILS $SHELL" pacstrap /mnt $PACKAGES echo "[Install] Generating fstab" genfstab -L /mnt >> /mnt/etc/fstab sed -i -E '/\/boot/ s/(rw,\S*)/\1,noauto,x-systemd.automount/' /mnt/etc/fstab
#!/usr/bin/env bash export LC_ALL=C set -euxo pipefail ### Change these values to select the cmake version to install CMAKE_VERSION_MAJOR=3 CMAKE_VERSION_MINOR=16 CMAKE_VERSION_PATCH=0 ### Installation CMAKE_VERSION_FULL=${CMAKE_VERSION_MAJOR}.${CMAKE_VERSION_MINOR}.${CMAKE_VERSION_PATCH} # If cmake is already installed with the expected version (from cache), skip the # installation process. if /opt/cmake/bin/cmake --version | grep "${CMAKE_VERSION_FULL}"; then exit 0 fi # Download the pre-built binary from the cmake.org website. # It is distributed as a script containing a self extractible archive. URL_PREFIX=https://cmake.org/files/v${CMAKE_VERSION_MAJOR}.${CMAKE_VERSION_MINOR} CMAKE_FILE_PREFIX=cmake-${CMAKE_VERSION_MAJOR}.${CMAKE_VERSION_MINOR}.${CMAKE_VERSION_PATCH} if [ "${TRAVIS_OS_NAME}" = "linux" ] then CMAKE_INSTALL_SCRIPT=${CMAKE_FILE_PREFIX}-Linux-x86_64.sh CMAKE_INSTALL_SCRIPT_SHA256SUM=c87dc439a8d6b1b368843c580f0f92770ed641af8ff8fe0b706cfa79eed3ac91 wget ${URL_PREFIX}/${CMAKE_INSTALL_SCRIPT} echo "${CMAKE_INSTALL_SCRIPT_SHA256SUM} ${CMAKE_INSTALL_SCRIPT}" | sha256sum -c # Make it executable sudo chmod +x ${CMAKE_INSTALL_SCRIPT} # Install to /opt/cmake CMAKE_INSTALL_PREFIX=/opt/cmake sudo mkdir -p ${CMAKE_INSTALL_PREFIX} sudo ./${CMAKE_INSTALL_SCRIPT} --prefix=${CMAKE_INSTALL_PREFIX} --skip-license fi if [ "${TRAVIS_OS_NAME}" = "osx" ] then CMAKE_ARCHIVE=${CMAKE_FILE_PREFIX}-Darwin-x86_64.tar.gz CMAKE_ARCHIVE_SHA256SUM=aa5221fb0be10088a47314546b7be5767056cb10fc2cbf64d18a374f25b226ce curl -L ${URL_PREFIX}/${CMAKE_ARCHIVE} --output ${CMAKE_ARCHIVE} echo "${CMAKE_ARCHIVE_SHA256SUM} ${CMAKE_ARCHIVE}" | shasum -a 256 -c sudo mkdir -p /opt/cmake sudo tar -C /opt/cmake --strip-components=1 -xzf ${CMAKE_ARCHIVE} fi
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ import React from 'react'; import { render } from 'enzyme'; import { requiredProps } from '../../test'; import { EuiResizableContainer } from './resizable_container'; describe('EuiResizableContainer', () => { test('is rendered', () => { const component = render( <EuiResizableContainer {...requiredProps}> {(EuiResizablePanel, EuiResizableButton) => ( <> <EuiResizablePanel initialSize={50}>Testing</EuiResizablePanel> <EuiResizableButton /> <EuiResizablePanel initialSize={50}>123</EuiResizablePanel> </> )} </EuiResizableContainer> ); expect(component).toMatchSnapshot(); }); test('can be vertical', () => { const component = render( <EuiResizableContainer {...requiredProps} direction="vertical"> {(EuiResizablePanel, EuiResizableButton) => ( <> <EuiResizablePanel initialSize={50}>Testing</EuiResizablePanel> <EuiResizableButton /> <EuiResizablePanel initialSize={50}>123</EuiResizablePanel> </> )} </EuiResizableContainer> ); expect(component).toMatchSnapshot(); }); test('can be controlled externally', () => { const panel1 = 50; const panel2 = 50; const component = render( <EuiResizableContainer {...requiredProps}> {(EuiResizablePanel, EuiResizableButton) => ( <> <EuiResizablePanel size={panel1}>Testing</EuiResizablePanel> <EuiResizableButton /> <EuiResizablePanel size={panel2}>123</EuiResizablePanel> </> )} </EuiResizableContainer> ); expect(component).toMatchSnapshot(); }); test('can have scrollable panels', () => { const component = render( <EuiResizableContainer {...requiredProps}> {(EuiResizablePanel, EuiResizableButton) => ( <> <EuiResizablePanel initialSize={50} scrollable> Testing </EuiResizablePanel> <EuiResizableButton /> <EuiResizablePanel initialSize={50} scrollable> 123 </EuiResizablePanel> </> )} </EuiResizableContainer> ); expect(component).toMatchSnapshot(); }); test('can have more than two panels', () => { const component = render( <EuiResizableContainer {...requiredProps}> {(EuiResizablePanel, EuiResizableButton) => ( <> <EuiResizablePanel initialSize={33}>Testing</EuiResizablePanel> <EuiResizableButton /> <EuiResizablePanel initialSize={33}>123</EuiResizablePanel> <EuiResizableButton /> <EuiResizablePanel initialSize={33}>And again</EuiResizablePanel> </> )} </EuiResizableContainer> ); expect(component).toMatchSnapshot(); }); test('can adjust panel props', () => { const component = render( <EuiResizableContainer {...requiredProps}> {(EuiResizablePanel, EuiResizableButton) => ( <> <EuiResizablePanel initialSize={50} paddingSize="none"> Testing </EuiResizablePanel> <EuiResizableButton /> <EuiResizablePanel initialSize={50} color="plain"> 123 </EuiResizablePanel> </> )} </EuiResizableContainer> ); expect(component).toMatchSnapshot(); }); test('can have toggleable panels', () => { const component = render( <EuiResizableContainer {...requiredProps}> {(EuiResizablePanel, EuiResizableButton) => ( <> <EuiResizablePanel mode="collapsible" initialSize={20}> Sidebar </EuiResizablePanel> <EuiResizableButton /> <EuiResizablePanel mode="main" initialSize={80}> Sidebar content </EuiResizablePanel> </> )} </EuiResizableContainer> ); expect(component).toMatchSnapshot(); }); test('toggleable panels can be configurable', () => { const component = render( <EuiResizableContainer {...requiredProps}> {(EuiResizablePanel, EuiResizableButton) => ( <> <EuiResizablePanel mode={[ 'collapsible', { 'data-test-subj': 'panel-toggle', className: 'panel-toggle', position: 'top', }, ]} initialSize={20} > Sidebar </EuiResizablePanel> <EuiResizableButton /> <EuiResizablePanel mode="main" initialSize={80}> Sidebar content </EuiResizablePanel> </> )} </EuiResizableContainer> ); expect(component).toMatchSnapshot(); }); });
#!/usr/bin/sh # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T # All Rights Reserved # # Copyright 2005 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. #ident "%Z%%M% %I% %E% SMI" set -- `getopt p: $*` if [ $? != 0 ]; then TEXTDOMAIN=SUNW_OST_OSCMD export TEXTDOMAIN /usr/bin/gettext "Usage: batch [-p project]\n" >&2 exit 2 fi exec /usr/xpg4/bin/at -qb -m $*
<filename>src/stations/classes/station.class.ts import { UserClass } from 'src/users/classes/user.class'; export class StationClass { _id?: string; active?: boolean; name?: string; description?: string; icecast_password?: string; icecast_port?: number; genre?: string; listeners?: number; user?: string | UserClass; //Supervisor state?: number; }
#!/bin/bash # Copyright 2019 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -eo pipefail function cleanup { echo 'pkill -f azurefileplugin' pkill -f azurefileplugin } readonly CSC_BIN="$GOBIN/csc" readonly volname="citest-$(date +%s)" endpoint='tcp://127.0.0.1:10000' if [[ "$#" -gt 0 ]]; then endpoint="$1" fi staging_target_path='/tmp/stagingtargetpath' if [[ "$#" -gt 1 ]]; then staging_target_path="$2" fi target_path='/tmp/targetpath' if [[ "$#" -gt 2 ]]; then target_path="$3" fi params='skuname=Standard_LRS' if [[ "$#" -gt 3 ]]; then params="$4" fi cloud='AzurePublicCloud' if [[ "$#" -gt 4 ]]; then cloud="$5" fi echo "Begin to run integration test on $cloud..." # Run CSI driver as a background service _output/azurefileplugin --endpoint "$endpoint" --nodeid CSINode -v=5 & trap cleanup EXIT if [[ "$cloud" == 'AzureChinaCloud' ]]; then sleep 25 else sleep 5 fi # Begin to run CSI functions one by one echo 'Create volume test:' readonly value=$("$CSC_BIN" controller new --endpoint "$endpoint" --cap 1,mount,cifs "$volname" --req-bytes 2147483648 --params "$params") sleep 15 readonly volumeid=$(echo "$value" | awk '{print $1}' | sed 's/"//g') echo "Got volume id: $volumeid" "$CSC_BIN" controller validate-volume-capabilities --endpoint "$endpoint" --cap 1,mount,cifs "$volumeid" if [[ "$cloud" != 'AzureChinaCloud' ]]; then # azure file mount/unmount on travis VM does not work against AzureChinaCloud echo "stage volume test:" "$CSC_BIN" node stage --endpoint "$endpoint" --cap 1,mount,cifs --staging-target-path "$staging_target_path" "$volumeid" sleep 2 echo 'Mount volume test:' "$CSC_BIN" node publish --endpoint "$endpoint" --cap 1,mount,cifs --staging-target-path "$staging_target_path" --target-path "$target_path" "$volumeid" sleep 2 if [[ ! "$params" =~ "fsType" ]]; then echo 'Expand volume test' "$CSC_BIN" controller expand-volume --endpoint "$endpoint" --req-bytes 21474836480 --cap 1,mount,cifs "$volumeid" fi echo 'Unmount volume test:' "$CSC_BIN" node unpublish --endpoint "$endpoint" --target-path "$target_path" "$volumeid" sleep 2 echo "unstage volume test:" "$CSC_BIN" node unstage --endpoint "$endpoint" --staging-target-path "$staging_target_path" "$volumeid" sleep 2 fi echo 'Delete volume test:' "$CSC_BIN" controller del --endpoint "$endpoint" "$volumeid" sleep 15 "$CSC_BIN" identity plugin-info --endpoint "$endpoint" "$CSC_BIN" node get-info --endpoint "$endpoint" echo "Integration test on $cloud is complete."
<gh_stars>1-10 export * from './accountConnected' export * from './accountNotConnected' export * from './arrowRight' export * from './close' export * from './disconnect' export * from './edit' export * from './eye' export * from './fullscreen' export * from './menu' export * from './search' export * from './share' export * from './shortArrow'
<gh_stars>0 from . import progue_pb2 from . import progue_pb2_grpc
def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] right = [x for x in arr if x > pivot] return quicksort(left) + [pivot] + quicksort(right) arr = [5,2,4,7,1,3] arr = quicksort(arr)
import time from concurrent.futures import Future from functools import wraps def log_execution_time(custom_args=None, custom_kwargs=None): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() - start_time if isinstance(result, Future): def resolve_future(future): return future.result() result = result.add_done_callback(resolve_future) print(f"Execution time: {end_time} seconds") return result return wrapper return decorator
#!/usr/bin/env bash set -euxo pipefail # Check all prerequisite # cc command -v cmake | xargs echo "cmake: " | tee test.log command -v make | xargs echo "make: " | tee -a test.log command -v swig | xargs echo "swig: " | tee -a test.log # python PY=(3.6 3.7 3.8 3.9) for i in "${PY[@]}"; do command -v "python$i" | xargs echo "python$i: " | tee -a test.log done ################## ## PYTHON 3.X ## ################## for i in "${PY[@]}"; do echo "Cleaning Python..." | tee -a test.log make clean_python echo "Cleaning Python...DONE" | tee -a test.log echo "Rebuild Python$i pypi archive..." | tee -a test.log make package_python UNIX_PYTHON_VER="$i" echo "Rebuild Python$i pypi archive...DONE" | tee -a test.log echo "Creating Python$i venv..." | tee -a test.log TEMP_DIR="temp_python$i" VENV_DIR=${TEMP_DIR}/venv "python$i" -m pip install --user virtualenv "python$i" -m virtualenv "${VENV_DIR}" echo "Creating Python$i venv...DONE" | tee -a test.log echo "Installing ortools Python$i venv..." | tee -a test.log "${VENV_DIR}/bin/python" -m pip install "${TEMP_DIR}/ortools/dist/*.whl" echo "Installing ortools Python$i venv...DONE" | tee -a test.log set +e echo "Testing ortools Python$i..." | tee -a test.log (cd "${VENV_DIR}/bin" && ./python -c "from ortools.linear_solver import pywraplp") 2>&1 | tee -a test.log (cd "${VENV_DIR}/bin" && ./python -c "from ortools.constraint_solver import pywrapcp") 2>&1 | tee -a test.log (cd "${VENV_DIR}/bin" && ./python -c "from ortools.sat import pywrapsat") 2>&1 | tee -a test.log (cd "${VENV_DIR}/bin" && ./python -c "from ortools.graph import pywrapgraph") 2>&1 | tee -a test.log (cd "${VENV_DIR}/bin" && ./python -c "from ortools.algorithms import pywrapknapsack_solver") 2>&1 | tee -a test.log cp test.py.in "${VENV_DIR}/test.py" "${VENV_DIR}/bin/python" "${VENV_DIR}/test.py" 2>&1 | tee -a test.log echo "Testing ortools Python$i...DONE" | tee -a test.log set -e done
<gh_stars>1-10 import React from "react"; import { useNotifications } from "@mantine/notifications"; import PropTypes from "prop-types"; import { useDidUpdate } from "@mantine/hooks"; /** * Mantine notifications system. For more information, see: https://mantine.dev/others/notifications/ */ const NotificationHandler = (props) => { const notification = useNotifications(); const { task } = props; useDidUpdate(() => { if (task.command === "show") { notification.showNotification({ ...task.props, id: task.id }); } else if (task.command === "update") { notification.updateNotification(task.id, { ...task.props, id: task.id, }); } else { notification.hideNotification(task.id); } }, [task]); return <div style={{ width: 0 }} />; }; NotificationHandler.displayName = "NotificationHandler"; NotificationHandler.defaultProps = {}; NotificationHandler.propTypes = { /** * The ID of this component, used to identify dash components in callbacks */ id: PropTypes.string, /** * Task for notification handler along with notification props */ task: PropTypes.exact({ command: PropTypes.oneOf(["hide", "show", "update"]).isRequired, id: PropTypes.string.isRequired, props: PropTypes.exact({ color: PropTypes.string, style: PropTypes.object, title: PropTypes.string, loading: PropTypes.bool, message: PropTypes.string, autoClose: PropTypes.oneOfType([ PropTypes.number, PropTypes.oneOf([false]), ]), disallowClose: PropTypes.bool, }), }), }; export default NotificationHandler;
#!/usr/bin/env bash set -e # abort on error set -u # abort on undefined variable SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" source "$SCRIPT_DIR/variables.sh" cat >generated/hpecp.conf<<EOF [default] api_host = ${CTRL_PUB_IP} api_port = 8080 use_ssl = ${INSTALL_WITH_SSL} verify_ssl = False warn_ssl = False username = admin password = admin123 [tenant2] tenant = /api/v1/tenant/2 EOF cat >generated/hpecp_private.conf<<EOF [default] api_host = ${CTRL_PRV_IP} api_port = 8080 use_ssl = ${INSTALL_WITH_SSL} verify_ssl = False warn_ssl = False username = admin password = admin123 [tenant2] tenant = /api/v1/tenant/2 EOF cat >generated/get_admin_kubeconfig_private.sh<<EOF #!/bin/bash display_usage() { echo "Usage: \$0 clustername" echo echo "Example:" echo " export CLUSTERNAME=your_cluster_name" echo " alias kubectl='kubectl --kubeconfig <(\$0 \\\$CLUSTERNAME)'" } if [[ \$# -lt 1 ]]; then display_usage exit 1 fi CLUSTER_NAME=\$1 CLUSTER_ID=\$(hpecp k8scluster list --query "[?label.name == '\${CLUSTER_NAME}'] | [0] | [_links.self.href]" --output text) hpecp k8scluster --id \$CLUSTER_ID admin-kube-config EOF chmod +x generated/get_admin_kubeconfig_private.sh cat >generated/get_admin_kubeconfig_public.sh<<EOF #!/bin/bash display_usage() { echo "Usage: \$0 clustername" echo echo "Example:" echo " export CLUSTERNAME=your_cluster_name" echo " kubectl --insecure-skip-tls-verify --kubeconfig <(\$0 \\\$CLUSTERNAME) get pods --all-namespaces" } if [[ \$# -lt 1 ]]; then display_usage exit 1 fi CLUSTER_NAME=\$1 CLUSTER_ID=\$(hpecp k8scluster list --query "[?label.name == '\${CLUSTER_NAME}'] | [0] | [_links.self.href]" --output text) hpecp k8scluster --id \$CLUSTER_ID admin-kube-config| sed s@https://.*:@https://${GATW_PUB_IP}:@ EOF chmod +x generated/get_admin_kubeconfig_public.sh # | sed s@https://.*:@https://${GATW_PUB_IP}:@ # add private key to RDP server to allow passwordless ssh to all other hosts if [[ "$RDP_SERVER_ENABLED" == "True" && "$RDP_SERVER_OPERATING_SYSTEM" = "LINUX" && "$RDP_PUB_IP" && -f generated/controller.prv_key ]]; then ssh -q -o StrictHostKeyChecking=no -i "${LOCAL_SSH_PRV_KEY_PATH}" -T ubuntu@${RDP_PUB_IP} "touch .hushlogin" # We can leave the controller.prv_key in the home folder, because it is need when adding hosts to HCP cat generated/controller.prv_key | \ ssh -q -o StrictHostKeyChecking=no -i "${LOCAL_SSH_PRV_KEY_PATH}" -T ubuntu@${RDP_PUB_IP} "cat > ~/.ssh/id_rsa" ssh -q -o StrictHostKeyChecking=no -i "${LOCAL_SSH_PRV_KEY_PATH}" -T ubuntu@${RDP_PUB_IP} "chmod 600 ~/.ssh/id_rsa" cat generated/controller.prv_key | \ ssh -q -o StrictHostKeyChecking=no -i "${LOCAL_SSH_PRV_KEY_PATH}" -T ubuntu@${RDP_PUB_IP} "cat > ~/Desktop/HCP_controller.prv_key" cat generated/hpecp_private.conf | \ ssh -q -o StrictHostKeyChecking=no -i "${LOCAL_SSH_PRV_KEY_PATH}" -T ubuntu@${RDP_PUB_IP} "cat > ~/.hpecp.conf" cat generated/get_admin_kubeconfig_private.sh | \ ssh -q -o StrictHostKeyChecking=no -i "${LOCAL_SSH_PRV_KEY_PATH}" -T ubuntu@${RDP_PUB_IP} "cat > ~/get_admin_kubeconfig.sh" ssh -q -o StrictHostKeyChecking=no -i "${LOCAL_SSH_PRV_KEY_PATH}" -T ubuntu@${RDP_PUB_IP} "chmod +x ~/get_admin_kubeconfig.sh" #ssh -o StrictHostKeyChecking=no -i "${LOCAL_SSH_PRV_KEY_PATH}" -T ubuntu@${RDP_PUB_IP} "[[ -d .ssh ]] || mkdir -p ~/.ssh" #ssh -o StrictHostKeyChecking=no -i "${LOCAL_SSH_PRV_KEY_PATH}" -T ubuntu@${RDP_PUB_IP} "[[ -f .ssh/id_rsa ]] || mv ~/Desktop/controller.prv_key ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa" if [[ "$AD_SERVER_ENABLED" == "True" && "$AD_PUB_IP" ]]; then ssh -q -o StrictHostKeyChecking=no -i "${LOCAL_SSH_PRV_KEY_PATH}" -T ubuntu@${RDP_PUB_IP} <<-EOF1 cat > ~/.ssh/config <<-EOF2 Host controller HostName ${CTRL_PRV_IP} User centos StrictHostKeyChecking no Host gateway HostName ${GATW_PRV_IP} User centos StrictHostKeyChecking no Host ad HostName ${AD_PRV_IP} User centos StrictHostKeyChecking no EOF2 EOF1 fi # ssh -q -o StrictHostKeyChecking=no -i "${LOCAL_SSH_PRV_KEY_PATH}" -T ubuntu@${RDP_PUB_IP} <<-EOF # sudo cp /var/lib/snapd/desktop/applications/gedit_gedit.desktop /usr/share/applications/gedit.desktop # xdg-mime default gedit.desktop text/plain # EOF if [[ "$WORKER_COUNT" != "0" ]]; then ssh -q -o StrictHostKeyChecking=no -i "${LOCAL_SSH_PRV_KEY_PATH}" -T ubuntu@${RDP_PUB_IP} "echo ${WRKR_PRV_IPS[@]} > ~/Desktop/HCP_WORKER_HOSTS.txt" fi # add private key to AD server to allow passwordless ssh to all other hosts if [[ "$AD_SERVER_ENABLED" == "True" && "$AD_PUB_IP" ]]; then cat generated/controller.pub_key | \ ssh -q -o StrictHostKeyChecking=no -i "${LOCAL_SSH_PRV_KEY_PATH}" -T centos@${AD_PUB_IP} "cat >> /home/centos/.ssh/authorized_keys" fi fi exit 0
package com.krailis.scala_99_problems.Lists import scala.annotation.tailrec object P22 { def range(i: Int, j: Int): List[Int] = { @tailrec def doRange(k: Int, acc: List[Int]): List[Int] = (k, acc) match { case (k, acc) if k <= j => doRange(k + 1, acc :+ k) case (_, acc) => acc } doRange(i, Nil) } }
#!/bin/bash # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # # Bash unit tests for TensorFlow Debugger (tfdbg) Python examples that do not # involve downloading data. Also tests the binary offline_analyzer. # # Command-line flags: # --virtualenv: (optional) If set, will test the examples and binaries # against pip install of TensorFlow in a virtualenv. set -e # Filter out LOG(INFO) export TF_CPP_MIN_LOG_LEVEL=1 IS_VIRTUALENV=0 PYTHON_BIN_PATH="" while true; do if [[ -z "$1" ]]; then break elif [[ "$1" == "--virtualenv" ]]; then IS_VIRTUALENV=1 PYTHON_BIN_PATH=$(which python) echo echo "IS_VIRTUALENV = ${IS_VIRTUALENV}" echo "PYTHON_BIN_PATH = ${PYTHON_BIN_PATH}" echo "Will test tfdbg examples and binaries against virtualenv pip install." echo fi shift 1 done if [[ -z "${PYTHON_BIN_PATH}" ]]; then DEBUG_FIBONACCI_BIN="$TEST_SRCDIR/org_tensorflow/tensorflow/python/debug/debug_fibonacci" DEBUG_ERRORS_BIN="$TEST_SRCDIR/org_tensorflow/tensorflow/python/debug/debug_errors" DEBUG_MNIST_BIN="$TEST_SRCDIR/org_tensorflow/tensorflow/python/debug/debug_mnist" DEBUG_TFLEARN_IRIS_BIN="$TEST_SRCDIR/org_tensorflow/tensorflow/python/debug/debug_tflearn_iris" DEBUG_KERAS_BIN="$TEST_SRCDIR/org_tensorflow/tensorflow/python/debug/debug_keras" OFFLINE_ANALYZER_BIN="$TEST_SRCDIR/org_tensorflow/tensorflow/python/debug/offline_analyzer" else DEBUG_FIBONACCI_BIN="${PYTHON_BIN_PATH} -m tensorflow.python.debug.examples.debug_fibonacci" DEBUG_ERRORS_BIN="${PYTHON_BIN_PATH} -m tensorflow.python.debug.examples.debug_errors" DEBUG_MNIST_BIN="${PYTHON_BIN_PATH} -m tensorflow.python.debug.examples.debug_mnist" DEBUG_TFLEARN_IRIS_BIN="${PYTHON_BIN_PATH} -m tensorflow.python.debug.examples.debug_tflearn_iris" DEBUG_KERAS_BIN="${PYTHON_BIN_PATH} -m tensorflow.python.debug.examples.debug_keras" OFFLINE_ANALYZER_BIN="${PYTHON_BIN_PATH} -m tensorflow.python.debug.cli.offline_analyzer" fi # Override the default ui_type=curses to allow the test to pass in a tty-less # test environment. cat << EOF | ${DEBUG_FIBONACCI_BIN} --tensor_size=2 --ui_type=readline run exit EOF cat << EOF | ${DEBUG_ERRORS_BIN} --error=no_error --ui_type=readline run exit EOF cat << EOF | ${DEBUG_ERRORS_BIN} --error=uninitialized_variable --debug --ui_type=readline run ni -a -d -t v/read exit EOF cat << EOF | ${DEBUG_MNIST_BIN} --debug --max_steps=1 --fake_data --ui_type=readline run -t 1 run --node_name_filter hidden --op_type_filter MatMul run -f has_inf_or_nan EOF # Test the custom dump_root option. CUSTOM_DUMP_ROOT=$(mktemp -d) mkdir -p ${CUSTOM_DUMP_ROOT} cat << EOF | ${DEBUG_TFLEARN_IRIS_BIN} --debug --fake_data --train_steps=2 --dump_root="${CUSTOM_DUMP_ROOT}" --ui_type=readline run -p run -f has_inf_or_nan EOF # Verify that the dump root has been cleaned up on exit. if [[ -d "${CUSTOM_DUMP_ROOT}" ]]; then echo "ERROR: dump root at ${CUSTOM_DUMP_ROOT} failed to be cleaned up." 1>&2 exit 1 fi # Test debugging of tf.keras. cat << EOF | ${DEBUG_KERAS_BIN} --debug --ui_type=readline run -f has_inf_or_nan EOF # Test offline_analyzer. echo echo "Testing offline_analyzer" echo # TODO(cais): Generate an actual debug dump and load it with offline_analyzer, # so that we can test the binary runs with a non-error exit code. set +e OUTPUT=$(${OFFLINE_ANALYZER_BIN} 2>&1) set -e EXPECTED_OUTPUT="ERROR: dump_dir flag is empty." if [[ "${OUTPUT}" != "${EXPECTED_OUTPUT}" ]]; then echo "ERROR: offline_analyzer output didn't match expectation: ${OUTPUT}" 1>&2 echo "Expected output: ${EXPECTED_OUTPUT}" exit 1 fi echo echo "SUCCESS: tfdbg examples and binaries test PASSED"
#!/bin/bash # -e When this option is on, if a simple command fails for any of the reasons listed in Consequences of # Shell Errors or returns an exit status value >0, and is not part of the compound list following a # while, until, or if keyword, and is not a part of an AND or OR list, and is not a pipeline # preceded by the ! reserved word, then the shell shall immediately exit. set -e # -u The shell shall write a message to standard error when it tries to expand a variable that is not # set and immediately exit. An interactive shell shall not exit. set -u # -o pipefail Sets the exit code of a pipeline to that of the rightmost command to exit with a non-zero # status, or to zero if all commands of the pipeline exit successfully. set -o pipefail # grab current working directory BPWD=$(pwd) readonly HELM_VERSION=$(cat app.yml | yq -r '.helmVersion | if . == null or . == "" then "v3.1.2" else . end') # install helm curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 chmod 700 get_helm.sh ./get_helm.sh --version $HELM_VERSION --no-sudo which helm helm version # install & configure kubectl curl -o kubectl https://amazon-eks.s3-us-west-2.amazonaws.com/1.14.6/2019-08-22/bin/linux/amd64/kubectl chmod +x ./kubectl mv ./kubectl /usr/local/bin/kubectl kubectl version --short --client # install eksctl curl --silent --location "https://github.com/weaveworks/eksctl/releases/download/latest_release/eksctl_$(uname -s)_amd64.tar.gz" | tar xz -C /tmp mv /tmp/eksctl /usr/local/bin eksctl version readonly APP_DOMAIN=$(cat app.yml | yq -r '.application.domain') readonly APP_IMAGE_NAME=$(cat app.yml | yq -r '.application.image.name') readonly APP_TAGS="$(cat app.yml | yq -r '.application.tags | to_entries | map(.key + "=" + .value) | join("\\,")')" if [ "$BRANCH_NAME"=="master" ] || [ "$BRANCH_NAME"=="main" ]; then APP_ROUTING="domain" FEATURE_DOMAIN=${APP_NAME}.${APP_DOMAIN} INGRESS_PATH="/" elif expr "$BRANCH_TYPE" : "feature" > /dev/null; then APP_ROUTING=$(cat app.yml | yq -r '.ingress.routing | if . == "path" or . == "domain" then . else "path" end') readonly HELM_BRANCH_NAME=${APP_NAMESPACE%-${APP_NAME}} if [[ "$APP_ROUTING" == "domain" ]]; then FEATURE_DOMAIN=$HELM_BRANCH_NAME.$APP_DOMAIN INGRESS_PATH="/" else FEATURE_DOMAIN=${APP_NAME}.${APP_DOMAIN} INGRESS_PATH="/${HELM_BRANCH_NAME}" fi fi # Set container name to use readonly IMAGE_NAME=${APP_IMAGE_NAME}:${IMAGE_TAG} # Assume EKS ROLE aws sts assume-role --role-arn $EKS_ADMIN_ROLE --role-session-name "EKS-CodeBuild-admin-session" > assume-role-output.json export AWS_ACCESS_KEY_ID=$(jq -r '.Credentials.AccessKeyId' assume-role-output.json) export AWS_SECRET_ACCESS_KEY=$(jq -r '.Credentials.SecretAccessKey' assume-role-output.json) export AWS_SESSION_TOKEN=$(jq -r '.Credentials.SessionToken' assume-role-output.json) rm assume-role-output.json # END Assume EKS ROLE eksctl utils write-kubeconfig --cluster=$EKS_CLUSTER_NAME --set-kubeconfig-context=true kubectl get nodes # install & configure app helm chart echo "HELM_RELEASE_NAME: $APP_NAMESPACE" echo "FEATURE_DOMAIN: $FEATURE_DOMAIN" echo "IMAGE_NAME: $IMAGE_NAME" # dry-run to validate the upgrade helm upgrade $APP_NAMESPACE ./app-settings --values app.yml --install --dry-run \ --set application.domain=$FEATURE_DOMAIN \ --set deployment.namespace=$APP_NAMESPACE \ --set image.name=$IMAGE_NAME \ --set ingress.routing=$APP_ROUTING \ --set ingress.path=$INGRESS_PATH # dry-run was successful perform upgrade/install helm upgrade $APP_NAMESPACE ./app-settings --values app.yml --install \ --set application.domain=$FEATURE_DOMAIN \ --set deployment.namespace=$APP_NAMESPACE \ --set image.name=$IMAGE_NAME \ --set ingress.routing=$APP_ROUTING \ --set ingress.path=$INGRESS_PATH echo "Completed pushing helm chart successfully to $APP_NAMESPACE namespace." echo -e "\n####################################################################\n" echo "Access at: https://$FEATURE_DOMAIN$INGRESS_PATH" echo -e "\n####################################################################"
import React, {useMemo} from 'react'; import PropTypes from 'prop-types'; import {commonTimezones} from '../../util/timezones'; import LazyDropdown from '../LazyDropdown'; import styles from './TimezonePicker.module.scss'; function TimezonePicker({onChange, currentTz, title, ...props}) { const options = useMemo( () => commonTimezones.map(({name, caption}) => ({ key: name, value: name, text: name, description: caption, })), [] ); return ( <div> {title} <LazyDropdown {...props} className={styles.dropdown} options={options} search selectOnBlur={false} selectOnNavigation={false} value={currentTz} onChange={(_, {value}) => { onChange(value); }} /> </div> ); } TimezonePicker.propTypes = { onChange: PropTypes.func.isRequired, currentTz: PropTypes.string.isRequired, title: PropTypes.string, inline: PropTypes.bool, }; TimezonePicker.defaultProps = { title: null, inline: false, }; export default React.memo(TimezonePicker);
import itertools def generate_n_tuples(list_of_elements, n): """Generates n-tuples of elements from the given list of elements.""" return itertools.combinations(list_of_elements, n)
<reponame>Polidea/SiriusObfuscator @import Foundation; #undef MAX @interface MyClass : NSObject { }; -(void)publicMethod; @end
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/1024+0+512-old/model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/1024+0+512-old/1024+0+512-FW-1 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function remove_all_but_function_words_first_two_thirds_full --eval_function last_element_eval
#!/usr/bin/env bash # Copyright 2018 The Knative Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Documentation about this script and how to use it can be found # at https://github.com/knative/test-infra/tree/master/ci source $(dirname $0)/../vendor/knative.dev/test-infra/scripts/release.sh function build_release() { # Run `generate-yamls.sh`, which should be versioned with the # branch since the detail of building may change over time. local YAML_LIST="$(mktemp)" export TAG $(dirname $0)/generate-yamls.sh "${REPO_ROOT_DIR}" "${YAML_LIST}" ARTIFACTS_TO_PUBLISH=$(cat "${YAML_LIST}" | tr '\n' ' ') if (( ! PUBLISH_RELEASE )); then # Copy the generated YAML files to the repo root dir if not publishing. cp ${ARTIFACTS_TO_PUBLISH} ${REPO_ROOT_DIR} fi } main $@
<filename>archetypes/streampipes-archetype-pe-sinks-jvm/src/main/resources/archetype-resources/src/main/java/config/Config.java /* * 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. * */ #set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) #set( $svc_name = $package.getClass().forName("org.apache.velocity.util.StringUtils").sub("$artifactId", "-", " ") ) package ${package}.config; import org.apache.streampipes.config.SpConfig; import org.apache.streampipes.container.model.PeConfig; import static ${package}.config.ConfigKeys.*; public enum Config implements PeConfig { INSTANCE; private SpConfig config; private final static String SERVICE_ID= "pe/${package}.sink.jvm"; Config() { config = SpConfig.getSpConfig(SERVICE_ID); config.register(HOST, "${artifactId}", "Data sink host"); config.register(PORT, 8090, "Data sink port"); config.register(SERVICE_NAME, "${svc_name}", "Data sink service name"); } @Override public String getHost() { return config.getString(HOST); } @Override public int getPort() { return config.getInteger(PORT); } @Override public String getId() { return SERVICE_ID; } @Override public String getName() { return config.getString(SERVICE_NAME); } }
def updateAndRetrieveEmployee(id, name, position, hours, rate): # Update employee information in the database Employee.where("id", id).update({"name": name, "position": position, "hours": hours, "rate": rate}) # Retrieve the updated employee record updated_employee = Employee.where("id", id).get() return updated_employee
package de.otto.edison.togglz; import org.togglz.core.repository.StateRepository; public interface RemoteTogglzConfig { }
import request from 'supertest'; import app from '../src/app'; describe('app', () => { it('GETs /api/foo and should obtain { foo: "bar" }', async () => { expect.assertions(1); const res = await request(app).get('/api/foo').expect(200); expect(res.body).toMatchInlineSnapshot(` Object { "foo": "bar", } `); }); });
#!/bin/bash TAG=${TRAVIS_TAG:-latest} echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin docker push $DOCKER_USERNAME/concaveturret:$TAG
package uk.gov.companieshouse.ocrapiconsumer.kafka; import static uk.gov.companieshouse.ocrapiconsumer.OcrApiConsumerApplication.APPLICATION_NAME_SPACE; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import uk.gov.companieshouse.kafka.exceptions.ProducerConfigException; import uk.gov.companieshouse.kafka.producer.Acks; import uk.gov.companieshouse.kafka.producer.CHKafkaProducer; import uk.gov.companieshouse.kafka.producer.ProducerConfig; import uk.gov.companieshouse.logging.Logger; import uk.gov.companieshouse.logging.LoggerFactory; public abstract class KafkaProducer implements InitializingBean { protected static final String EXPECTED_CONFIG_ERROR_MESSAGE = "Broker addresses for kafka broker missing, check if environment variable KAFKA_BROKER_ADDR is configured. " + "[Hint: The property 'kafka.broker.addresses' uses the value of this environment variable in live " + "environments and that of 'spring.embedded.kafka.brokers' property in test.]"; private static final int PRODUCER_RETRIES = 10; private static final Logger LOG = LoggerFactory.getLogger(APPLICATION_NAME_SPACE); protected CHKafkaProducer chKafkaProducer; @Value("${kafka.bootstrap-servers}") private String brokerAddresses; @Override public void afterPropertiesSet() { LOG.trace("Configuring CH Kafka producer"); final ProducerConfig config = createProducerConfig(); setBrokerAddress(config); config.setAcks(Acks.WAIT_FOR_ALL); config.setRetries(PRODUCER_RETRIES); modifyProducerConfig(config); chKafkaProducer = createChKafkaProducer(config); } /** * Extending classes may implement this to provide any specific producer configuration modifications required. * @param producerConfig the producer configuration to be modified */ protected void modifyProducerConfig(final ProducerConfig producerConfig) { } protected CHKafkaProducer getChKafkaProducer() { return chKafkaProducer; } protected void setBrokerAddress(ProducerConfig config) { if (brokerAddresses != null && !brokerAddresses.isEmpty()) { config.setBrokerAddresses(brokerAddresses.split(",")); } else { throw new ProducerConfigException(EXPECTED_CONFIG_ERROR_MESSAGE); } } /** * Extending classes may implement this to facilitate testing for example. * @param config the {@link ProducerConfig} used to configure the producer * @return the {@link CHKafkaProducer} created */ protected CHKafkaProducer createChKafkaProducer(final ProducerConfig config) { return new CHKafkaProducer(config); } /** * Extending classes may implement this to facilitate testing for example. * @return the {@link ProducerConfig} created */ protected ProducerConfig createProducerConfig() { return new ProducerConfig(); } protected void setBrokerAddresses(String brokerAddresses) { this.brokerAddresses = brokerAddresses; } }
import java.util.*; public class CatsAndMouse { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); for(int i = 0; i < tests; i++) { String line = stdin.nextLine(); String[] abmString = line.split(" "); int[] abm = new int[3]; for(int j = 0; j < 3; j++) { abm[j] = Integer.parseInt(abmString[j]); } int a = abm[0]; int b = abm[1]; int m = abm[2]; int catACatchMouseSteps = Math.abs(a - m); int catBCatchMouseSteps = Math.abs(b - m); if(catACatchMouseSteps == catBCatchMouseSteps) { System.out.println("Mouse C"); } else if(catACatchMouseSteps < catBCatchMouseSteps) { System.out.println("Cat A"); } else { System.out.println("Cat B"); } } stdin.close(); } }
package com.leetcode; public class Solution_5178 { public int[] countPoints(int[][] points, int[][] queries) { int[] result = new int[queries.length]; for (int i = 0; i < queries.length; i++) { int count = 0; for (int j = 0; j < points.length; j++) { if (in(queries[i], points[j][0], points[j][1])) count++; } result[i] = count; } return result; } public boolean in(int[] query, int x, int y) { return query[2] * query[2] >= (x - query[0]) * (x - query[0]) + (y - query[1]) * (y - query[1]); } }
/** * Copyright 2020 Materna Information & Communications SE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package de.materna.fegen.util.spring.controller; import de.materna.fegen.util.spring.annotation.FegenIgnore; import de.materna.fegen.util.spring.security.SecurityEvaluator; import org.springframework.beans.factory.BeanFactory; import org.springframework.data.rest.webmvc.BasePathAwareController; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * The endpoints in this controller provide information about * which endpoints in this spring application may be called * by the caller of the endpoints in this controller */ @BasePathAwareController @RestController @FegenIgnore @RequestMapping("/fegen/security") public class FegenMetaSecurityController { private final SecurityEvaluator securityEvaluator; public FegenMetaSecurityController(BeanFactory beanFactory) { this.securityEvaluator = SecurityEvaluator.createInstance(beanFactory); } /** * Returns a list of capitalized HTTP methods that the caller of this endpoint may use * to call the endpoint at the given path. */ @GetMapping("allowedMethods") public ResponseEntity<List<String>> allowedMethods(@RequestParam String path) { return ResponseEntity.ok(securityEvaluator.allowedMethods(path)); } /** * Returns true iff the caller of this endpoint may use the specified method * to call the endpoint at the specified path. */ @GetMapping("isAllowed") public ResponseEntity<Boolean> isAllowed(@RequestParam String path, @RequestParam String method) { return ResponseEntity.ok(securityEvaluator.isAllowed(path, method)); } }
#!/bin/sh read name enroll_num program courses # Display user's inputted information. echo "Your name is: $name" echo "Your enrollment number is: $enroll_num" echo "Your program is: $program" echo "You study the following courses:" # Display user's courses. for curr_course in $courses do echo " > $curr_course" done
<filename>common/src/main/java/com/codefinity/microcontinuum/common/port/adapter/persistance/leveldb/AbstractLevelDBRepository.java /*package com.codefinity.microcontinuum.common.port.adapter.persistance.leveldb; import org.iq80.leveldb.DB; public abstract class AbstractLevelDBRepository { private DB database; private String databasePath; protected AbstractLevelDBRepository(String aDirectoryPath) { super(); this.openDatabase(aDirectoryPath); } protected DB database() { return this.database; } protected String databasePath() { return this.databasePath; } private void setDatabase(DB aDatabase) { this.database = aDatabase; } private void setDatabasePath(String aDatabasePath) { this.databasePath = aDatabasePath; } private void openDatabase(String aDirectoryPath) { LevelDBProvider levelDBProvider = LevelDBProvider.instance(); DB db = levelDBProvider.databaseFrom(aDirectoryPath); this.setDatabase(db); this.setDatabasePath(aDirectoryPath); } } */
sudo rm old-hits.txt sudo touch old-hits.txt sudo rm public/hits_hygiene/*.hits sudo turkic delete HospitalHygiene_video_rgb_17_0 --force sudo turkic delete HospitalHygiene_video_d_17_0 --force sudo turkic delete HospitalHygiene_video_fs_17_0 --force sudo turkic delete HospitalHygiene_video_rgb_18_0 --force sudo turkic delete HospitalHygiene_video_d_18_0 --force sudo turkic delete HospitalHygiene_video_fs_18_0 --force sudo turkic delete HospitalHygiene_video_rgb_19_0 --force sudo turkic delete HospitalHygiene_video_d_19_0 --force sudo turkic delete HospitalHygiene_video_fs_19_0 --force sudo turkic delete HospitalHygiene_video_rgb_20_0 --force sudo turkic delete HospitalHygiene_video_d_20_0 --force sudo turkic delete HospitalHygiene_video_fs_20_0 --force
<reponame>bgould/avian<filename>classpath/java/io/FilterReader.java /* Copyright (c) 2008-2015, <NAME> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. There is NO WARRANTY for this software. See license.txt for details. */ package java.io; public abstract class FilterReader extends Reader { protected Reader in; protected FilterReader(Reader in) { this.in = in; } public int read() throws IOException { return in.read(); } public int read(char[] buffer, int offset, int length) throws IOException { return in.read(buffer, offset, length); } public boolean ready() throws IOException { throw new UnsupportedOperationException(); } public long skip(long n) throws IOException { throw new UnsupportedOperationException(); } public void close() throws IOException { in.close(); } public boolean markSupported() { return in.markSupported(); } public void mark(int readAheadLimit) throws IOException { in.mark(readAheadLimit); } public void reset() throws IOException { in.reset(); } }
# This command maps /home/dedey to /root/dedey inside the docker and drops one into # a terminal inside the docker. Then one can just run the training command. docker run --runtime=nvidia -it --rm -v /home/dedey:/root/dedey debadeepta/petridishpytorch:latest
#!/usr/bin/env bash # Copyright (c) 2021, ARM Limited and Contributors. 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 ARM 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 HOLDER 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. # # This script uses the following environment variables from the variant # # VARIANT - build variant name # TOP_DIR - workspace root directory # CROSS_COMPILE - PATH to GCC including CROSS-COMPILE prefix # PARALLELISM - number of cores to build across # UEFI_BUILD_ENABLED - Flag to enable building UEFI # UEFI_PATH - sub-directory containing UEFI code # UEFI_BUILD_MODE - DEBUG or RELEASE # UEFI_TOOLCHAIN - Toolchain supported by Linaro uefi-tools: GCC49, GCC48 or GCC47 # UEFI_PLATFORMS - List of platforms to build # UEFI_PLAT_{platform name} - array of platform parameters: # - platname - the name of the platform used by the build # - makefile - the makefile to execute for this platform # - output - where to store the files in packaging phase # - defines - extra platform defines during the build # - binary - what to call the final output binary TOP_DIR=`pwd` UEFI_PATH=edk2 UEFI_TOOLCHAIN=GCC5 UEFI_BUILD_MODE=DEBUG TARGET_ARCH=AARCH64 GCC=tools/gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu- CROSS_COMPILE=$TOP_DIR/$GCC BUILD_PLAT=$1 BUILD_TYPE=$2 #Currently the BUILD_PLAT flag is not used. For future use if ! [[ $BUILD_PLAT = IR ]] && ! [[ $BUILD_PLAT = ES ]] ; then echo "Please provide a target." echo "Usage $0 <IR/ES> <BUILD_TYPE>" echo "S->Standalone BBR,F->Full systemready" exit fi if ! [[ $BUILD_TYPE = S ]] && ! [[ $BUILD_TYPE = F ]] ; then echo "Please provide a Build type." echo "Usage $0 <target> <S/F>" echo "S->Standalone BBR,F->Full systemready" exit fi echo "Target: $BUILD_PLAT" echo "Build type: $BUILD_TYPE" if [[ $BUILD_TYPE = S ]]; then BBR_DIR=$TOP_DIR/../../ else BBR_DIR=$TOP_DIR/bbr-acs fi do_build() { pushd $TOP_DIR/$UEFI_PATH CROSS_COMPILE_DIR=$(dirname $CROSS_COMPILE) PATH="$PATH:$CROSS_COMPILE_DIR" export EDK2_TOOLCHAIN=$UEFI_TOOLCHAIN export ${UEFI_TOOLCHAIN}_AARCH64_PREFIX=$CROSS_COMPILE local vars= export PACKAGES_PATH=$TOP_DIR/$UEFI_PATH export PYTHON_COMMAND=/usr/bin/python3 export WORKSPACE=$TOP_DIR/$UEFI_PATH #Build base tools source $TOP_DIR/$UEFI_PATH/edksetup.sh make -C $TOP_DIR/$UEFI_PATH/BaseTools build -a AARCH64 -t GCC5 -p MdeModulePkg/MdeModulePkg.dsc popd } do_clean() { pushd $TOP_DIR/$UEFI_PATH CROSS_COMPILE_DIR=$(dirname $CROSS_COMPILE) PATH="$PATH:$CROSS_COMPILE_DIR" source $TOP_DIR/$UEFI_PATH/edksetup.sh make -C $TOP_DIR/$UEFI_PATH/BaseTools clean popd } do_package () { echo "Packaging..."; if [ -f $TOP_DIR/$UEFI_PATH/Build/MdeModule/${UEFI_BUILD_MODE}_${UEFI_TOOLCHAIN}/${TARGET_ARCH}/CapsuleApp.efi ]; then echo "CapsuleApp.efi successfully generated at $TOP_DIR/$UEFI_PATH/Build/MdeModule/${UEFI_BUILD_MODE}_${UEFI_TOOLCHAIN}/${TARGET_ARCH}/CapsuleApp.efi" else echo "Error: CapsuleApp.efi could not be generated. Please check the logs" fi } DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) source $DIR/framework.sh $@
<gh_stars>1-10 package stl import ( "bytes" "fmt" "testing" ) func Test_headerBinary(t *testing.T) { for _, tst := range []struct { h string want []byte }{ { h: "", want: make([]byte, 80), }, { h: "This is a header", want: []byte{0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, }, { h: "This header is too long, so it will be trimmed. This header is too long, so it will be trimmed.", want: []byte{0x54, 0x68, 0x69, 0x73, 0x20, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x20, 0x69, 0x73, 0x20, 0x74, 0x6f, 0x6f, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x2c, 0x20, 0x73, 0x6f, 0x20, 0x69, 0x74, 0x20, 0x77, 0x69, 0x6c, 0x6c, 0x20, 0x62, 0x65, 0x20, 0x74, 0x72, 0x69, 0x6d, 0x6d, 0x65, 0x64, 0x2e, 0x20, 0x20, 0x54, 0x68, 0x69, 0x73, 0x20, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x20, 0x69, 0x73, 0x20, 0x74, 0x6f, 0x6f, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x2c, 0x20, 0x73, 0x6f, 0x20, 0x69, 0x74, 0x20}, }, } { tst := tst t.Run(tst.h, func(t *testing.T) { t.Parallel() got := headerBinary(tst.h) if !bytes.Equal(got, tst.want) { t.Errorf("got %x; want %x", got, tst.want) } }) } } func Test_triCountBinary(t *testing.T) { for _, tst := range []struct { c uint32 want []byte }{ { c: 0, want: []byte{0x00, 0x00, 0x00, 0x00}, }, { c: 500, want: []byte{0xf4, 0x01, 0x00, 0x00}, }, { c: 1000222, want: []byte{0x1e, 0x43, 0x0f, 0x00}, }, } { tst := tst t.Run(fmt.Sprintf("%d", tst.c), func(t *testing.T) { t.Parallel() if got := triCountBinary(tst.c); !bytes.Equal(got, tst.want) { t.Errorf("got %x; want %x", got, tst.want) } }) } } func Test_triangleBinary(t *testing.T) { for _, tst := range []struct { t Triangle want []byte }{ { t: Triangle{ Normal: UnitVector{ Ni: 0, Nj: 0, Nk: 0, }, Vertices: [3]Coordinate{ { X: 0, Y: 0, Z: 0, }, { X: 0, Y: 0, Z: 0, }, { X: 0, Y: 0, Z: 0, }, }, AttrByteCnt: 0, }, want: []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, }, { t: Triangle{ Normal: UnitVector{ Ni: 5, Nj: 0, Nk: 0, }, Vertices: [3]Coordinate{ { X: 0, Y: 2, Z: 0, }, { X: 0, Y: 0, Z: 1, }, { X: 123, Y: 0, Z: 0, }, }, AttrByteCnt: 0, }, want: []byte{0x00, 0x00, 0xa0, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0xf6, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, }, { t: Triangle{ Normal: UnitVector{ Ni: 0, Nj: 0, Nk: 0, }, Vertices: [3]Coordinate{ { X: 0, Y: 0, Z: 0, }, { X: 0, Y: 0, Z: 0, }, { X: 0, Y: 0, Z: 0, }, }, AttrByteCnt: 5, }, want: []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00}, }, } { tst := tst t.Run("triangleBinary", func(t *testing.T) { t.Parallel() if got := triangleBinary(tst.t); !bytes.Equal(got, tst.want) { t.Errorf("got %x; want %x", got, tst.want) } }) } }
#!/bin/bash # Copyright 2020 Hewlett Packard Enterprise Development LP set -e echo "Enabling HPE CSM CMS services" systemctl enable cfs-state-reporter.service
#!/usr/bin/env bash set -e set -o pipefail file_path="$1" archive_name="$2" file_size=$(wc -c <"$file_path" | sed -e 's/^[[:space:]]*//') scripts_path="scripts" date=`date '+%Y-%m-%d'` utc_iso_date=`date -u +'%Y-%m-%dT%H:%M:%SZ'` source="mobile.binarysize" json_name="$scripts_path/$archive_name.json" json_gz="$scripts_path/$archive_name.json.gz" # Write binary size to json file cat >"$json_name" <<EOL {"sdk": "telemetry", "platform": "android", "size": ${file_size}, "created_at": "${utc_iso_date}"} EOL # Compress json file gzip -f "$json_name" > "$json_gz" # Publish to aws "$scripts_path"/publish_to_aws.sh $source $date $json_gz
<reponame>qubekit/QUBEBench<gh_stars>0 from functools import wraps def exception_catcher(func): """ basically just used to catch and ignore exceptions when running in bulk. This prevents the whole program stopping when just one molecule is 'broken'. """ @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as exc: if len(args) >= 1 and hasattr(args[0], 'molecule'): if hasattr(args[0].molecule, 'bulk_run'): if not args[0].molecule.bulk_run: raise else: raise print(exc) return wrapper
<reponame>gHainar/PhotoWall class Order < ApplicationRecord mount_uploader :in_image_url, ImageUploader mount_uploader :out_image_url, ImageUploader include AASM belongs_to :user attr_accessor :active_admin_requested_event scope :waiting, ->{ where(state: 'waiting')} scope :priced, ->{ where(state: 'priced')} scope :work_in_progress, ->{ where(state: 'wip')} scope :completed, ->{ where(state: 'completed')} scope :paid, ->{ where(state: 'paid')} scope :canceled, ->{ where(state: 'canceled')} def ready? completed? || paid? end aasm column: :state do state :waiting, initial: true state :priced state :wip state :completed state :paid state :canceled # forward event :set_price do transitions from: [:waiting], to: :priced end event :accept_price do transitions from: [:priced], to: :wip end event :mark_as_completed do transitions from: [:wip], to: :completed end event :pay_for do transitions from: [:completed], to: :paid end event :cancel do transitions from: [:waiting, :priced], to: :canceled end end end
<reponame>jay6697117/tinyimg-webpack-plugin<filename>test/webpack.config.js const Path = require('path'); const BarPlugin = require('webpackbar'); const CleanPlugin = require('clean-webpack-plugin').CleanWebpackPlugin; const HtmlPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const Fibers = require('fibers'); const Sass = require('sass'); const TinyimgPlugin = require('../src'); console.log(`TinyimgPlugin:`, TinyimgPlugin) console.log(`__dirname:`, __dirname) const PATH = { entryHtml: Path.join(__dirname, 'src/index.html'), entryIco: Path.join(__dirname, 'src/IMG/favicon.ico'), entryJs: Path.join(__dirname, 'src/index.js'), output: Path.join(__dirname, 'dist') }; const LOADER_OPTS = { babel: { babelrc: false, cacheDirectory: true, presets: ['@babel/preset-env'] }, css: { importLoaders: 2 }, imgurl: { esModule: false, limit: 10240, name: '[name].[ext]', outputPath: 'img' }, minicss: { publicPath: '../' }, sass: { implementation: Sass, sassOptions: { fiber: Fibers } } }; module.exports = { devtool: false, entry: PATH.entryJs, mode: 'production', module: { rules: [ { exclude: /node_modules/, test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, options: LOADER_OPTS.minicss }, { loader: 'css-loader', options: LOADER_OPTS.css } ] }, { exclude: /node_modules/, test: /\.(sass|scss)$/, use: [ { loader: MiniCssExtractPlugin.loader, options: LOADER_OPTS.minicss }, { loader: 'css-loader', options: LOADER_OPTS.css }, { loader: 'sass-loader', options: LOADER_OPTS.sass } ] }, { exclude: /node_modules/, test: /\.js$/, use: [{ loader: 'babel-loader', options: LOADER_OPTS.babel }] }, { exclude: /node_modules/, test: /\.(jpe?g|png)$/, use: [{ loader: 'url-loader', options: LOADER_OPTS.imgurl }] } ] }, output: { filename: 'js/[name].bundle.js', path: PATH.output, publicPath: '' }, plugins: [ new BarPlugin({ name: 'Webpack Build' }), new CleanPlugin({ cleanOnceBeforeBuildPatterns: [PATH.output], dry: true }), new HtmlPlugin({ favicon: PATH.entryIco, filename: 'index.html', minify: { collapseWhitespace: true, removeComments: true }, template: PATH.entryHtml }), new MiniCssExtractPlugin({ filename: 'css/[name].bundle.css' }), new TinyimgPlugin({ enabled: true, logged: true }) ], stats: 'errors-only' };
CREATE TABLE BlogPost ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, content TEXT NOT NULL, author TEXT NOT NULL, date DATETIME NOT NULL );
#!/usr/bin/env sh #Sample comment let "a=16 << 2"; b="Sample text"; function foo() { if [ $string1 == $string2 ]; then for url in `cat example.txt`; do curl $url > result.html done fi } rm -f $(find / -name core) &> /dev/null mkdir -p "${AGENT_USER_HOME_${PLATFORM}}" multiline='first line second line third line' cat << EOF Sample text EOF
import axios from "axios"; const userApiUrl="https://jsonplaceholder.typicode.com/users/"; const userPostUrl="https://jsonplaceholder.typicode.com/posts?userId=" async function GetUserAndPostById(user_id){ try{ const {data:user}=await axios(`${userApiUrl}${user_id}`); const {data:userpost}=await axios(`${userPostUrl}${user_id}`); return {user,userpost}; } catch(e){ console.log(e) } } export default GetUserAndPostById;
IMAGE_SIZE=224 ARCHITECTURE="mobilenet_0.50_${IMAGE_SIZE}" python -m scripts.retrain --bottleneck_dir=tf_files/bottlenecks --how_many_training_steps=500 --model_dir=tf_files/models/ --summaries_dir=tf_files/training_summaries/"${ARCHITECTURE}" --output_graph=tf_files/retrained_graph.pb --output_labels=tf_files/retrained_labels.txt --architecture="${ARCHITECTURE}" --image_dir=tf_files/flower_photos
import pandas as pd from sklearn import tree data = pd.read_csv("data.csv") X = data.iloc[:, :-1] y = data.iloc[:, 9] clf = tree.DecisionTreeClassifier(max_depth=2) clf = clf.fit(X, y) print(clf.predict([[0, 2.5, 3.1, 4.2, 0.5, 1.2, 1.3, 0.4, 0.9]]))
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.client; import static org.junit.Assert.assertEquals; import alluxio.BaseIntegrationTest; import alluxio.LocalAlluxioClusterResource; import alluxio.master.MasterClientConfig; import alluxio.wire.MasterInfo; import alluxio.wire.MasterInfo.MasterInfoField; import org.junit.Rule; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; /** * Integration tests for the meta master. */ public final class MetaMasterIntegrationTest extends BaseIntegrationTest { @Rule public LocalAlluxioClusterResource mResource = new LocalAlluxioClusterResource.Builder().build(); @Test public void getInfoAllFields() throws Exception { try (MetaMasterClient client = new RetryHandlingMetaMasterClient(MasterClientConfig.defaults())) { int webPort = mResource.get().getLocalAlluxioMaster().getMasterProcess().getWebAddress().getPort(); MasterInfo info = client.getInfo(null); assertEquals(webPort, info.getWebPort()); } } @Test public void getInfoWebPort() throws Exception { try (MetaMasterClient client = new RetryHandlingMetaMasterClient(MasterClientConfig.defaults())) { int webPort = mResource.get().getLocalAlluxioMaster().getMasterProcess().getWebAddress().getPort(); MasterInfo info = client.getInfo(new HashSet<>(Arrays.asList(MasterInfoField.WEB_PORT))); assertEquals(webPort, info.getWebPort()); } } }