text stringlengths 1 1.05M |
|---|
#!/usr/bin/env bash
if [ -z "${UWSGI_PROCESSES}" ];then
UWSGI_PROCESSES=1
fi
echo UWSGI_PROCESSES=$UWSGI_PROCESSES
if [ -z "$UWSGI_THREADS" ];then
UWSGI_THREADS=1
fi
echo UWSGI_THREADS=$UWSGI_THREADS
if [ -z "$PORT" ];then
PORT=10000
fi
echo PORT=$PORT
uwsgi --http-socket :${PORT} --enable-threads --threads=${UWSGI_THREADS} --processes=${UWSGI_PROCESSES} --wsgi-file service.py --buffer-size 32768 --chmod-socket=666 --gevent-monkey-patch --disable-logging --callable app
|
<filename>js/scenes/demo.js
class Demo extends Phaser.Scene {
constructor() {
super('demo');
}
create(data) {
const TILESIZE = data.tilesize;
const vTiles = Math.floor(((this.game.config.height / TILESIZE) - 1));
const hTiles = Math.floor(((this.game.config.width / TILESIZE) - 1));
const mapHeight = Math.floor((vTiles - 1) / 2);
const mapWidth = Math.floor((hTiles - 1) / 2);
// New Maze object
const mymaze = new Maze(mapWidth, mapHeight);
// Maze start
mymaze.gateway(0, 1);
// Maze exit
mymaze.gateway(mapWidth - 1, mapHeight - 3);
// Generates the maze map
const mazeMap = mymaze.tiles();
// Center map on screen
const x = Math.round((this.game.config.width - TILESIZE * hTiles) / 2);
const y = Math.round((this.game.config.height - TILESIZE * vTiles) / 2);
// Gets Solution
this.solution = mymaze.getRoute(mazeMap,0,1,mapWidth - 1,mapHeight - 3);
// Display the maze map
this.renderTiles(x, y, mazeMap, TILESIZE);
}
swapZeros(arr) {
arr.forEach((row, i) => {
row.forEach((v, i, a) => {
a[i] = a[i] ? 0 : 1;
});
});
}
renderTiles(x, y, maze, tilesize) {
const width = tilesize * maze[0].length;
const height = tilesize * maze.length;
// Walls
let wallsMap = this.make.tilemap({ data: maze, tileWidth: 50, tileHeight: 50 });
let wallTile = wallsMap.addTilesetImage('wall');
let wallsLayer = wallsMap.createStaticLayer(0, wallTile, x, y);
wallsLayer.setDisplaySize(width, height);
// Floor
this.swapZeros(maze); // swaps 0 - 1
let map = this.make.tilemap({ data: maze, tileWidth: 50, tileHeight: 50 });
let floorTile = map.addTilesetImage('floor');
let floorLayer = map.createDynamicLayer(0, floorTile, x, y);
floorLayer.setDisplaySize(width, height);
// Shadows
const offset = 0.2 * tilesize;
let rt = this.add.renderTexture(x + offset, y + offset, width, height);
rt.draw(wallsLayer, 0, 0);
rt.setAlpha(0.4);
rt.setTint(0);
// Move walls to front
wallsLayer.setDepth(rt.depth + 1);
// Renders solution
this.renderSolution(map);
}
renderSolution(mazeMap){
let path = this.solution;
path.forEach((v) => {
mazeMap.getTileAt(v[0],v[1],true).tint = 0xffff00;
});
}
} |
<gh_stars>0
const SchoolCreate = () => import('../../../pages/administration/schools/Create.vue');
export default {
name: 'administration.schools.create',
path: 'create',
component: SchoolCreate,
meta: {
breadcrumb: 'create',
title: 'Create School',
},
};
|
<filename>src/binarySearch.tsx
function binarySearch(arr, value){
let start = 0
let end = arr.length() -1
let guess
while(start <= end){
let mid = Math.ceil((start + end)/2)
guess = arr[mid]
if(guess == value)return mid
if(guess > value) end = mid -1
if(guess < value) start = mid + 1
}
return -1
}
|
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
var WebSocketServer = require('ws').Server;
var RED = '\033[31m';
var RESET = '\033[0m';
function _logError(error) {
"use strict";
console.error(RED + "[server] " + error.stack + RESET);
}
function _handleMessage(ws, message) {
"use strict";
var messageObj = JSON.parse(message);
console.log(messageObj.module + "." + messageObj.method + "(" + messageObj.args.join() + ")");
var module = require("./" + messageObj.module);
var handler = module[messageObj.method];
var response = handler.apply(null, messageObj.args);
if (response && typeof response.then === "function") {
response.then(function (response) {
ws.send(JSON.stringify({ id: messageObj.id, response: response }));
}, function (error) {
_logError(error);
});
} else {
ws.send(JSON.stringify({ id: messageObj.id, response: response }));
}
}
// set up the web socket server
var wss = new WebSocketServer({ port:8080 });
wss.on('connection', function (ws) {
"use strict";
ws.on('message', function (message) {
try {
_handleMessage(ws, message);
} catch (error) {
_logError(error);
}
});
});
|
SELECT c.customer_name, MAX(p.price) AS max_price
FROM products p
INNER JOIN orders o ON o.product_id = p.product_id
INNER JOIN customers c ON c.customer_id=o.customer_id
GROUP BY c.customer_name
ORDER BY max_price DESC |
#!/bin/bash
#Copyright (c) Citrix Systems, Inc.
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without modification,
#are permitted provided that the following conditions are met:
#
#1. Redistributions of source code must retain the above copyright notice, this
#list of conditions and the following disclaimer.
#
#2. Redistributions in binary form must reproduce the above copyright notice,
#this list of conditions and the following disclaimer in the documentation and/or
#other materials provided with the distribution.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
#IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
#INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
#NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#POSSIBILITY OF SUCH DAMAGE.
echo Entered re-branding.sh
set -u
GLOBAL_BUILD_NUMBER=$1
ROOT_DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )/../.." && pwd )"
REPO="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )"
version_cpp()
{
num=$(echo "${BRANDING_XC_PRODUCT_VERSION}.${GLOBAL_BUILD_NUMBER}" | sed 's/\./, /g')
sed -b -i -e "s/1,0,0,1/${num}/g" \
-e "s/1, 0, 0, 1/${num}/g" \
-e "s/@BUILD_NUMBER@/${GLOBAL_BUILD_NUMBER}/g" \
$1
}
version_csharp()
{
sed -b -i -e "s/0\.0\.0\.0/${BRANDING_XC_PRODUCT_VERSION}.${GLOBAL_BUILD_NUMBER}/g" \
-e "s/0000/${BRANDING_XC_PRODUCT_VERSION}.${GLOBAL_BUILD_NUMBER}/g" \
$1
}
rebranding_global()
{
sed -b -i -e "s#\[BRANDING_COMPANY_NAME_LEGAL\]#${BRANDING_COMPANY_NAME_LEGAL}#g" \
-e "s#\[Citrix\]#${BRANDING_COMPANY_NAME_SHORT}#g" \
-e "s#\[Citrix XenServer\]#${BRANDING_COMPANY_AND_PRODUCT}#g" \
-e "s#\[Citrix VM Tools\]#${BRANDING_PV_TOOLS}#g" \
-e "s#\[XenServer product\]#${BRANDING_PRODUCT_BRAND}#g" \
-e "s#\[BRANDING_PRODUCT_VERSION\]#${BRANDING_XC_PRODUCT_VERSION}#g" \
-e "s#\[BRANDING_PRODUCT_VERSION_TEXT\]#${BRANDING_PRODUCT_VERSION_TEXT}#g" \
-e "s#\[BRANDING_BUILD_NUMBER\]#${GLOBAL_BUILD_NUMBER}#g" \
-e "s#\[XenServer\]#${BRANDING_SERVER}#g" \
-e "s#\[XenCenter\]#${BRANDING_BRAND_CONSOLE}#g" \
$1
}
RESX_rebranding()
{
for resx in $1
do
rebranding_global ${resx}.resx
rebranding_global ${resx}.zh-CN.resx
rebranding_global ${resx}.ja.resx
done
}
#splace rebranding
for file in splash.rc main.cpp splash.vcproj splash.vcxproj util.cpp
do
version_cpp "${REPO}/splash/${file}" && rebranding_global "${REPO}/splash/${file}"
done
#AssemblyInfo rebranding
for projectName in CommandLib xe XenAdmin XenAdminTests XenCenterLib XenCenterVNC XenModel XenOvfApi XenOvfTransport XenServerHealthCheck xva_verify
do
assemblyInfo="${REPO}/${projectName}/Properties/AssemblyInfo.cs"
version_csharp ${assemblyInfo} && rebranding_global ${assemblyInfo}
done
#XenAdmin controls
XENADMIN_RESXS=$(/usr/bin/find ${REPO}/XenAdmin -name \*.resx)
for XENADMIN_RESX in ${XENADMIN_RESXS}
do
rebranding_global ${XENADMIN_RESX}
done
#xenadmin resouces
RESX_rebranding "${REPO}/XenAdmin/Properties/Resources"
rebranding_global ${REPO}/XenAdmin/app.config
#XenModel
rebranding_global ${REPO}/XenModel/BrandManager.cs
RESX_rebranding "${REPO}/XenModel/Messages ${REPO}/XenModel/InvisibleMessages ${REPO}/XenModel/FriendlyNames ${REPO}/XenModel/XenAPI/FriendlyErrorNames"
rebranding_global "${REPO}/XenModel/Utils/Helpers.cs"
#XenOvfApi rebranding
RESX_rebranding "${REPO}/XenOvfApi/Messages ${REPO}/XenOvfApi/Content"
rebranding_global ${REPO}/XenOvfApi/app.config
#XenOvfTransport XenOvfTransport
RESX_rebranding ${REPO}/XenOvfTransport/Messages
rebranding_global ${REPO}/XenOvfTransport/app.config
PRODUCT_GUID=$(uuidgen | tr [a-z] [A-Z] | tr -d [:space:])
sed -b -i -e "s/@AUTOGEN_PRODUCT_GUID@/${PRODUCT_GUID}/g" \
-e "s/@PRODUCT_VERSION@/${BRANDING_XC_PRODUCT_VERSION}/g" \
-e "s/@COMPANY_NAME_LEGAL@/${BRANDING_COMPANY_NAME_LEGAL}/g" \
-e "s/@COMPANY_NAME_SHORT@/${BRANDING_COMPANY_NAME_SHORT}/g" \
-e "s/@BRAND_CONSOLE@/${BRANDING_BRAND_CONSOLE}/g" \
-e "s/@PRODUCT_BRAND@/${BRANDING_PRODUCT_BRAND}/g" \
${REPO}/WixInstaller/branding.wxi
#XenAdminTests
rebranding_global ${REPO}/XenAdminTests/TestResources/ContextMenuBuilderTestResults.xml
rebranding_global ${REPO}/XenAdminTests/app.config
rebranding_global ${REPO}/XenAdminTests/XenAdminTests.csproj
#XenServerHealthCheck
rebranding_global ${REPO}/XenServerHealthCheck/app.config
set +u
|
/**
* CreateQuery generates a jsonpath based query
* @param {string} query jsonpath query
* @param {boolean} isKubernetes is the query to be generated for K8s CRD
* @returns {string} generated query
*/
function CreateQuery(query = "", isKubernetes = true) {
if (isKubernetes || !query)
return `$[?(@.kind=="CustomResourceDefinition")]..validation.openAPIV3Schema`;
return query;
}
module.exports = CreateQuery;
|
class BankAccount:
def __init__(self, account_number, initial_balance):
self.account_number = account_number
self.balance = initial_balance
def deposit(self, amount):
if amount < 0:
raise InvalidAmountException("Invalid amount for deposit")
self.balance += amount
def withdraw(self, amount):
if amount < 0:
raise InvalidAmountException("Invalid amount for withdrawal")
if amount > self.balance:
raise InvalidTransactionException("Insufficient funds for withdrawal")
self.balance -= amount
def get_balance(self):
return self.balance
class InvalidTransactionException(Exception):
pass
class InvalidAmountException(Exception):
pass |
<filename>src/index.ts
export * from './ng2-busy.module';
export * from './ng2-busy.directive';
export * from './ng2-busy.service';
export * from './ng2-busy-config';
|
<filename>include/socket.h
#include <sockio.h>
#define PF_UNSPEC 0
#define PF_LOCAL 1
#define PF_INET 2
#define AF_UNSPEC PF_UNSPEC
#define AF_LOCAL PF_LOCAL
#define AF_INET PF_INET
#define SOCK_STREAM 1
#define SOCK_DGRAM 2
#define IPPROTO_TCP 0
#define IPPROTO_UDP 0
#define INADDR_ANY ((ip_addr_t)0)
struct sockaddr {
unsigned short sa_family;
char sa_data[14];
};
struct sockaddr_in {
unsigned short sin_family;
uint16_t sin_port;
ip_addr_t sin_addr;
};
#define IFNAMSIZ 16
struct ifreq {
char ifr_name[IFNAMSIZ]; /* Interface name */
union {
struct sockaddr ifr_addr;
struct sockaddr ifr_dstaddr;
struct sockaddr ifr_broadaddr;
struct sockaddr ifr_netmask;
struct sockaddr ifr_hwaddr;
short ifr_flags;
int ifr_ifindex;
int ifr_metric;
int ifr_mtu;
// struct ifmap ifr_map;
char ifr_slave[IFNAMSIZ];
char ifr_newname[IFNAMSIZ];
char *ifr_data;
};
};
|
public class LinkedList {
// Head of the list
Node head;
// Linked list Node.
// This inner class is made static
// so that main() can access it
static class Node {
int data;
Node next;
// Constructor
Node(int d) {
data = d;
next = null;
}
}
// Method to insert a new node
public LinkedList insert(LinkedList list, int data) {
// Create a new node with given data
Node new_node = new Node(data);
new_node.next = null;
// If the Linked List is empty,
// then make the new node as head
if (list.head == null) {
list.head = new_node;
}
else {
// Else traverse till the last node
// and insert the new_node there
Node last = list.head;
while (last.next != null) {
last = last.next;
}
// Insert the new_node at last node
last.next = new_node;
}
// Return the list by head
return list;
}
// Method to print the LinkedList.
public void printList(LinkedList list) {
Node currNode = list.head;
System.out.print("LinkedList: ");
// Traverse through the LinkedList
while (currNode != null) {
// Print the data at current node
System.out.print(currNode.data + " ");
// Go to next node
currNode = currNode.next;
}
}
} |
#!/usr/bin/env bash
#copy the /usr/bin directory listing to a log file
today=`date +%y%m%d`
ls /usr/bin -al > log.$today
|
#!/bin/sh
main()
{
check_shadowsocks_libev_installed || warning
netzone_str=`cat $DOCUMENT_ROOT/apps/netzone/netzone.conf`
shadowsocks_libev_str=`cat $DOCUMENT_ROOT/apps/shadowsocks-libev/shadowsocks_libev.json`
shadowsocks_libev_server_pid=`ps aux | grep "ss-server" | grep -v grep | grep "\-a shadowsocks" | awk {'print $2'}`
if
echo $shadowsocks_libev_server_pid | grep -qE '[0-9]'
then
status_icon="<span class=\"glyphicon glyphicon-play alert-success\"></span>"
else
status_icon="<span class=\"glyphicon glyphicon-pause\"></span>"
fi
eval `main.sbin pid_uptime $shadowsocks_libev_server_pid`
if
grep -q "enable=1" $DOCUMENT_ROOT/apps/shadowsocks-libev/S700shadowsocks_server.init
then
server_on_selected="selected=\"selected\""
else
server_off_selected="selected=\"selected\""
fi
server_config_str=`cat /usr/local/shadowsocks-libev/etc/server.json`
cat <<EOF
<script>
\$(function(){
\$('#shadowsocks_libev_server_service').on('submit', function(e){
e.preventDefault();
var data = "app=shadowsocks-libev&"+\$(this).serialize();
var url = 'index.cgi';
Ha.common.ajax(url, 'json', data, 'post', 'ajax-service');
setTimeout("window.location.reload();", 3000);
});
});
\$(function(){
\$('#shadowsocks_libev_local_service').on('submit', function(e){
e.preventDefault();
var data = "app=shadowsocks-libev&"+\$(this).serialize();
var url = 'index.cgi';
Ha.common.ajax(url, 'json', data, 'post', 'ajax-service');
setTimeout("window.location.reload();", 3000);
});
});
\$(function(){
\$('#shadowsocks_libev_redir_service').on('submit', function(e){
e.preventDefault();
var data = "app=shadowsocks-libev&"+\$(this).serialize();
var url = 'index.cgi';
Ha.common.ajax(url, 'json', data, 'post', 'ajax-service');
setTimeout("window.location.reload();", 3000);
});
});
\$(function(){
\$('#shadowsocks_libev_server_basesetting').on('submit', function(e){
e.preventDefault();
var data = "app=shadowsocks-libev&"+\$(this).serialize();
var url = 'index.cgi';
Ha.common.ajax(url, 'json', data, 'post', 'ajax-fluid');
});
});
\$(function(){
\$('#shadowsocks_libev_local_basesetting').on('submit', function(e){
e.preventDefault();
var data = "app=shadowsocks-libev&"+\$(this).serialize();
var url = 'index.cgi';
Ha.common.ajax(url, 'json', data, 'post', 'ajax-fluid');
});
});
\$(function(){
\$('#shadowsocks_libev_redir_basesetting').on('submit', function(e){
e.preventDefault();
var data = "app=shadowsocks-libev&"+\$(this).serialize();
var url = 'index.cgi';
Ha.common.ajax(url, 'json', data, 'post', 'ajax-fluid');
});
});
\$(function(){
\$('#shadowsocks_libev_redir_dest').on('submit', function(e){
e.preventDefault();
var data = "app=shadowsocks-libev&"+\$(this).serialize();
var url = 'index.cgi';
Ha.common.ajax(url, 'json', data, 'post', 'ajax-fluid');
});
});
\$(function(){
\$('#shadowsocks_libev_local_dest').on('submit', function(e){
e.preventDefault();
var data = "app=shadowsocks-libev&"+\$(this).serialize();
var url = 'index.cgi';
Ha.common.ajax(url, 'json', data, 'post', 'ajax-fluid');
});
});
\$(function(){
\$('#shadowsocks_libev_server_dest').on('submit', function(e){
e.preventDefault();
var data = "app=shadowsocks-libev&"+\$(this).serialize();
var url = 'index.cgi';
Ha.common.ajax(url, 'json', data, 'post', 'ajax-fluid');
});
});
</script>
<div class="col-md-6">
<legend>Shadowsocks Server</legend>
<p>
<form class="form-inline" role="form" id="shadowsocks_libev_server_dest">
<label>Wan in use</label>
EOF
for dest in `echo "$netzone_str" | jq '.["wan_zone"] | keys' | grep -Po '[\w].*[\w]'`
do
wan_used=`echo "$shadowsocks_libev_str" | jq '.["shadowsocks_server"]["wan_zone"]' | grep -Po '[\w].*[\w]'`
cat <<EOF
<label class="checkbox-inline">
<input type="checkbox" name="wan_zone_${dest}" value="${dest}" `echo "$wan_used" | grep -qE "[ ]*${dest}[ ]*" && echo checked`>${dest}</label>
EOF
done
cat <<EOF
<input type="hidden" name="action" value="shadowsocks_libev_server_dest">
<button class="btn btn-primary" id="_submit" type="submit">$_LANG_Save</button>
</form>
<p>
<div class="controls">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">$_LANG_Service_Status</h3>
</div>
<div class="panel-body">
<div id="ajax-service">
<form id="shadowsocks_libev_server_service">
<table class="table">
<tr>
<td>
$status_icon
$_LANG_Start_at:$pid_start_date
</td>
<td>
$_LANG_Runed:$pid_runs
</td>
</tr>
<tr>
<td>
$_LANG_Shadowsocks_libev_server_service
<select name="shadowsocks_libev_server_enable">
<option value="1" $server_on_selected>$_LANG_On</option>
<option value="0" $server_off_selected>$_LANG_Off</option>
</select>
</td>
<td>
<input type="hidden" name="action" value="shadowsocks_libev_server_service">
<button class="btn btn-primary" id="_submit" type="submit">$_LANG_Save</button>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
<legend>Shadowsocks Server Setting</legend>
<form id="shadowsocks_libev_server_basesetting">
<table class="table">
<tr>
<td>
server
</td>
<td>
<input type="text" class="form-control" name="server" placeholder="Enter Server IP" value="`echo "$server_config_str" | jq -r '.["server"]'`">
</td>
</tr>
<tr>
<td>
server_port
</td>
<td>
<input type="text" class="form-control" name="server_port" placeholder="Enter Server Port" value="`echo "$server_config_str" | jq -r '.["server_port"]'`">
</td>
</tr>
<tr>
<td>
password
</td>
<td>
<input type="text" class="form-control" name="password" placeholder="Enter Password" value="`echo "$server_config_str" | jq -r '.["password"]'`">
</td>
</tr>
<tr>
<td>
timeout
</td>
<td>
<input type="text" class="form-control" name="timeout" placeholder="Enter Time Secends" value="`echo "$server_config_str" | jq -r '.["timeout"]'`">
</td>
</tr>
<tr>
<td>
method
</td>
<td>
<select class="form-control" name="method">
<option value="table" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "table" ] && echo selected=\"selected\"`>TABLE</option>
<option value="rc4" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "rc4" ] && echo selected=\"selected\"`>RC4</option>
<option value="rc4-md5" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "rc4-md5" ] && echo selected=\"selected\"`>RC4-MD5</option>
<option value="aes-128-cfb" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "aes-128-cfb" ] && echo selected=\"selected\"`>AES-128-CFB</option>
<option value="aes-192-cfb" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "aes-192-cfb" ] && echo selected=\"selected\"`>AES-192-CFB</option>
<option value="aes-256-cfb" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "aes-256-cfb" ] && echo selected=\"selected\"`>AES-256-CFB</option>
<option value="bf-cfb" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "bf-cfb" ] && echo selected=\"selected\"`>BF-CFB</option>
<option value="camellia-128-cfb" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "camellia-128-cfb" ] && echo selected=\"selected\"`>CAMELLIA-128-CFB</option>
<option value="camellia-192-cfb" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "camellia-192-cfb" ] && echo selected=\"selected\"`>CAMELLIA-192-CFB</option>
<option value="camellia-256-cfb" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "camellia-256-cfb" ] && echo selected=\"selected\"`>CAMELLIA-256-CFB</option>
<option value="cast5-cfb" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "cast5-cfb" ] && echo selected=\"selected\"`>CAST5-CFB</option>
<option value="des-cfb" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "des-cfb" ] && echo selected=\"selected\"`>DES-CFB</option>
<option value="idea-cfb" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "idea-cfb" ] && echo selected=\"selected\"`>IDEA-CFB</option>
<option value="rc2-cfb" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "rc2-cfb" ] && echo selected=\"selected\"`>RC2-CFB</option>
<option value="seed-cfb" `[ "$(echo "$server_config_str" | jq -r '.["method"]')" = "seed-cfb" ] && echo selected=\"selected\"`>SEED-CFB</option>
<option value="salsa20" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "salsa20" ] && echo selected=\"selected\"`>SALSA20</option>
<option value="chacha20" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "chacha20" ] && echo selected=\"selected\"`>CHACHA20</option>
</select>
</td>
</tr>
<tr>
<td>
Option
</td>
<td>
<input type="hidden" name="action" value="shadowsocks_libev_server_basesetting">
<button class="btn btn-primary" id="_submit" type="submit">$_LANG_Save</button>
</td>
</tr>
</table>
</form>
</div>
EOF
shadowsocks_libev_local_pid=`ps aux | grep "ss-local" | grep -v grep | grep "\-a shadowsocks" | awk {'print $2'}`
if
echo $shadowsocks_libev_local_pid | grep -qE '[0-9]'
then
status_icon="<span class=\"glyphicon glyphicon-play alert-success\"></span>"
else
status_icon="<span class=\"glyphicon glyphicon-pause\"></span>"
fi
eval `main.sbin pid_uptime $shadowsocks_libev_local_pid`
if
grep -q "enable=1" $DOCUMENT_ROOT/apps/shadowsocks-libev/S701shadowsocks_local.init
then
local_on_selected="selected=\"selected\""
else
local_off_selected="selected=\"selected\""
fi
local_config_str=`cat /usr/local/shadowsocks-libev/etc/local.json`
cat <<EOF
<div class="col-md-6">
<legend>Shadowsocks Local</legend>
<p>
<form class="form-inline" role="form" id="shadowsocks_libev_local_dest">
<label>Wan in use</label>
EOF
EOF
for dest in `echo "$netzone_str" | jq '.["wan_zone"] | keys' | grep -Po '[\w].*[\w]'`
do
wan_used=`echo "$shadowsocks_libev_str" | jq '.["shadowsocks_local"]["wan_zone"]' | grep -Po '[\w].*[\w]'`
cat <<EOF
<label class="checkbox-inline">
<input type="checkbox" name="wan_zone_${dest}" value="${dest}" `echo "$wan_used" | grep -qE "[ ]*${dest}[ ]*" && echo checked`>${dest}</label>
EOF
done
cat <<EOF
<input type="hidden" name="action" value="shadowsocks_libev_local_dest">
<button class="btn btn-primary" id="_submit" type="submit">$_LANG_Save</button>
</form>
<p>
<div class="controls">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">$_LANG_Service_Status</h3>
</div>
<div class="panel-body">
<div id="ajax-service">
<form id="shadowsocks_libev_local_service">
<table class="table">
<tr>
<td>
$status_icon
$_LANG_Start_at:$pid_start_date
</td>
<td>
$_LANG_Runed:$pid_runs
</td>
</tr>
<tr>
<td>
$_LANG_Shadowsocks_libev_local_service
<select name="shadowsocks_libev_local_enable">
<option value="1" $local_on_selected>$_LANG_On</option>
<option value="0" $local_off_selected>$_LANG_Off</option>
</select>
</td>
<td>
<input type="hidden" name="action" value="shadowsocks_libev_local_service">
<button class="btn btn-primary" id="_submit" type="submit">$_LANG_Save</button>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
<legend>Shadowsocks Local Setting</legend>
<form id="shadowsocks_libev_local_basesetting">
<table class="table">
<tr>
<td>
server
</td>
<td>
<input type="text" class="form-control" name="server" placeholder="Enter Server IP" value="`echo "$local_config_str" | jq -r '.["server"]'`">
</td>
</tr>
<tr>
<td>
server_port
</td>
<td>
<input type="text" class="form-control" name="server_port" placeholder="Enter Server Port" value="`echo "$local_config_str" | jq -r '.["server_port"]'`">
</td>
</tr>
<tr>
<td>
local_port
</td>
<td>
<input type="text" class="form-control" name="local_port" placeholder="Enter Local Port" value="`echo "$local_config_str" | jq -r '.["local_port"]'`">
</td>
</tr>
<tr>
<td>
password
</td>
<td>
<input type="text" class="form-control" name="password" placeholder="Enter Password" value="`echo "$local_config_str" | jq -r '.["password"]'`">
</td>
</tr>
<tr>
<td>
timeout
</td>
<td>
<input type="text" class="form-control" name="timeout" placeholder="Enter Time Secends" value="`echo "$local_config_str" | jq -r '.["timeout"]'`">
</td>
</tr>
<tr>
<td>
method
</td>
<td>
<select class="form-control" name="method">
<option value="table" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "table" ] && echo selected=\"selected\"`>TABLE</option>
<option value="rc4" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "rc4" ] && echo selected=\"selected\"`>RC4</option>
<option value="rc4-md5" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "rc4-md5" ] && echo selected=\"selected\"`>RC4-MD5</option>
<option value="aes-128-cfb" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "aes-128-cfb" ] && echo selected=\"selected\"`>AES-128-CFB</option>
<option value="aes-192-cfb" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "aes-192-cfb" ] && echo selected=\"selected\"`>AES-192-CFB</option>
<option value="aes-256-cfb" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "aes-256-cfb" ] && echo selected=\"selected\"`>AES-256-CFB</option>
<option value="bf-cfb" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "bf-cfb" ] && echo selected=\"selected\"`>BF-CFB</option>
<option value="camellia-128-cfb" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "camellia-128-cfb" ] && echo selected=\"selected\"`>CAMELLIA-128-CFB</option>
<option value="camellia-192-cfb" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "camellia-192-cfb" ] && echo selected=\"selected\"`>CAMELLIA-192-CFB</option>
<option value="camellia-256-cfb" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "camellia-256-cfb" ] && echo selected=\"selected\"`>CAMELLIA-256-CFB</option>
<option value="cast5-cfb" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "cast5-cfb" ] && echo selected=\"selected\"`>CAST5-CFB</option>
<option value="des-cfb" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "des-cfb" ] && echo selected=\"selected\"`>DES-CFB</option>
<option value="idea-cfb" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "idea-cfb" ] && echo selected=\"selected\"`>IDEA-CFB</option>
<option value="rc2-cfb" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "rc2-cfb" ] && echo selected=\"selected\"`>RC2-CFB</option>
<option value="seed-cfb" `[ "$(echo "$local_config_str" | jq -r '.["method"]')" = "seed-cfb" ] && echo selected=\"selected\"`>SEED-CFB</option>
<option value="salsa20" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "salsa20" ] && echo selected=\"selected\"`>SALSA20</option>
<option value="chacha20" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "chacha20" ] && echo selected=\"selected\"`>CHACHA20</option>
</select>
</td>
</tr>
<tr>
<td>
Option
</td>
<td>
<input type="hidden" name="action" value="shadowsocks_libev_local_basesetting">
<button class="btn btn-primary" id="_submit" type="submit">$_LANG_Save</button>
</td>
</tr>
</table>
</form>
</div>
EOF
shadowsocks_libev_redir_pid=`ps aux | grep "ss-redir" | grep -v grep | grep "\-a shadowsocks" | awk {'print $2'}`
if
echo $shadowsocks_libev_redir_pid | grep -qE '[0-9]'
then
status_icon="<span class=\"glyphicon glyphicon-play alert-success\"></span>"
else
status_icon="<span class=\"glyphicon glyphicon-pause\"></span>"
fi
eval `main.sbin pid_uptime $shadowsocks_libev_redir_pid`
if
grep -q "enable=1" $DOCUMENT_ROOT/apps/shadowsocks-libev/S702shadowsocks_redir.init
then
redir_on_selected="selected=\"selected\""
else
redir_off_selected="selected=\"selected\""
fi
redir_config_str=`cat /usr/local/shadowsocks-libev/etc/redir.json`
cat <<EOF
<div class="col-md-6">
<legend>Shadowsocks Redir</legend>
<p>
<form class="form-inline" role="form" id="shadowsocks_libev_redir_dest">
<label>Lan in use</label>
EOF
for dest in `echo "$netzone_str" | jq '.["lan_zone"] | keys' | grep -Po '[\w].*[\w]'`
do
lan_used=`echo "$shadowsocks_libev_str" | jq -r '.["shadowsocks_redir"]["lan_zone"]' | grep -Po '[\w].*[\w]'`
cat <<EOF
<label class="checkbox-inline">
<input type="checkbox" name="lan_zone_${dest}" value="${dest}" `echo "$lan_used" | grep -qE "[ ]*${dest}[ ]*" && echo checked`>${dest}</label>
EOF
done
cat <<EOF
<input type="hidden" name="action" value="shadowsocks_libev_redir_dest">
<button class="btn btn-primary" id="_submit" type="submit">$_LANG_Save</button>
</form>
<p>
<div class="controls">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">$_LANG_Service_Status</h3>
</div>
<div class="panel-body">
<div id="ajax-service">
<form id="shadowsocks_libev_redir_service">
<table class="table">
<tr>
<td>
$status_icon
$_LANG_Start_at:$pid_start_date
</td>
<td>
$_LANG_Runed:$pid_runs
</td>
</tr>
<tr>
<td>
$_LANG_Shadowsocks_libev_redir_service
<select name="shadowsocks_libev_redir_enable">
<option value="1" $redir_on_selected>$_LANG_On</option>
<option value="0" $redir_off_selected>$_LANG_Off</option>
</select>
</td>
<td>
<input type="hidden" name="action" value="shadowsocks_libev_redir_service">
<button class="btn btn-primary" id="_submit" type="submit">$_LANG_Save</button>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
<legend>Shadowsocks Redir Setting</legend>
<form id="shadowsocks_libev_redir_basesetting">
<table class="table">
<tr>
<td>
server
</td>
<td>
<input type="text" class="form-control" name="server" placeholder="Enter Server IP" value="`echo "$redir_config_str" | jq -r '.["server"]'`">
</td>
</tr>
<tr>
<td>
server_port
</td>
<td>
<input type="text" class="form-control" name="server_port" placeholder="Enter Server Port" value="`echo "$redir_config_str" | jq -r '.["server_port"]'`">
</td>
</tr>
<tr>
<td>
local_port
</td>
<td>
<input type="text" class="form-control" name="local_port" placeholder="Enter Local Port" value="`echo "$redir_config_str" | jq -r '.["local_port"]'`">
</td>
</tr>
<tr>
<td>
password
</td>
<td>
<input type="text" class="form-control" name="password" placeholder="Enter Password" value="`echo "$redir_config_str" | jq -r '.["password"]'`">
</td>
</tr>
<tr>
<td>
timeout
</td>
<td>
<input type="text" class="form-control" name="timeout" placeholder="Enter Time Secends" value="`echo "$redir_config_str" | jq -r '.["timeout"]'`">
</td>
</tr>
<tr>
<td>
method
</td>
<td>
<select class="form-control" name="method">
<option value="table" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "table" ] && echo selected=\"selected\"`>TABLE</option>
<option value="rc4" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "rc4" ] && echo selected=\"selected\"`>RC4</option>
<option value="rc4-md5" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "rc4-md5" ] && echo selected=\"selected\"`>RC4-MD5</option>
<option value="aes-128-cfb" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "aes-128-cfb" ] && echo selected=\"selected\"`>AES-128-CFB</option>
<option value="aes-192-cfb" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "aes-192-cfb" ] && echo selected=\"selected\"`>AES-192-CFB</option>
<option value="aes-256-cfb" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "aes-256-cfb" ] && echo selected=\"selected\"`>AES-256-CFB</option>
<option value="bf-cfb" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "bf-cfb" ] && echo selected=\"selected\"`>BF-CFB</option>
<option value="camellia-128-cfb" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "camellia-128-cfb" ] && echo selected=\"selected\"`>CAMELLIA-128-CFB</option>
<option value="camellia-192-cfb" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "camellia-192-cfb" ] && echo selected=\"selected\"`>CAMELLIA-192-CFB</option>
<option value="camellia-256-cfb" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "camellia-256-cfb" ] && echo selected=\"selected\"`>CAMELLIA-256-CFB</option>
<option value="cast5-cfb" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "cast5-cfb" ] && echo selected=\"selected\"`>CAST5-CFB</option>
<option value="des-cfb" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "des-cfb" ] && echo selected=\"selected\"`>DES-CFB</option>
<option value="idea-cfb" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "idea-cfb" ] && echo selected=\"selected\"`>IDEA-CFB</option>
<option value="rc2-cfb" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "rc2-cfb" ] && echo selected=\"selected\"`>RC2-CFB</option>
<option value="seed-cfb" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "seed-cfb" ] && echo selected=\"selected\"`>SEED-CFB</option>
<option value="salsa20" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "salsa20" ] && echo selected=\"selected\"`>SALSA20</option>
<option value="chacha20" `[ "$(echo "$redir_config_str" | jq -r '.["method"]')" = "chacha20" ] && echo selected=\"selected\"`>CHACHA20</option>
</select>
</td>
</tr>
<tr>
<td>
Transparent Proxy Dest
</td>
<td>
<textarea style="width:100%;height:140px" name="transparent_proxy_dest" placeholder="10.0.0.0/8" class="bg-warning">`cat $DOCUMENT_ROOT/apps/shadowsocks-libev/transparent_proxy_dest.conf`</textarea>
</td>
</tr>
<tr>
<td>
Option
</td>
<td>
<input type="hidden" name="action" value="shadowsocks_libev_redir_basesetting">
<button class="btn btn-primary" id="_submit" type="submit">$_LANG_Save</button>
</td>
</tr>
</table>
</form>
</div>
EOF
cat <<'EOF'
<script>
$(function(){
$('#del_prog_bin').on('click', function(e){
e.preventDefault();
if (confirm('Do you confirm to del del prog bin')) {
var data = "app=shadowsocks-libev&action=del_prog_bin";
var url = 'index.cgi';
Ha.common.ajax(url, 'json', data, 'post', 'del_prog_bin');
setTimeout("window.location.reload();", 3000);
}
});
});
</script>
EOF
cat <<EOF
<div class="col-md-6" id="del_prog_bin">
<legend>$_LANG_Reinstall</legend>
<p>$_LANG_Del_prog_bin</p>
<button class="btn btn-primary">$_LANG_Del</button>
</div>
EOF
}
del_prog_bin()
{
rm -f /usr/local/shadowsocks-libev/bin/*
(echo "$_LANG_Save_success" | main.sbin output_json 0) || exit 0
}
warning()
{
cat <<EOF
<div class="container">
<div class="modal fade" id="fix_Modal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">$_PS_Install_Shadowsocks_libev</h4>
</div>
<div class="modal-body" style="overflow-y: auto;height: 480px;">
<p id="fix_content"></p>
</div>
<div class="modal-footer">
<button type="button" onclick="javascript:history.go(0)" class="btn btn-default" data-dismiss="modal">$_LANG_Close</button>
<input type="hidden" name="action">
<button type="button" href="javascript:;" class="btn btn-info" id="install_shadowsocks_libev" data-loading-text="Loading...">$_LANG_Install_or_View_Progress</button>
</div>
</div>
</div>
</div>
<div class="col-md-10">
<p class="bg-danger">$_LANG_Shadowsocks_libev_binary_need_install<p>
</div>
<div class="col-md-2">
<a class="btn btn-info" href="javascript:;" id="fixer">$_LANG_Fixer</a>
</div>
</div>
EOF
cat <<'EOF'
<script>
$('#fixer').on('click', function(){
var url = 'index.cgi?app=shadowsocks-libev&action=pre_install_shadowsocks_libev';
Ha.common.ajax(url, 'html', '', 'get', 'applist', function(data){
$('#fix_content').html(data);
$('#fix_Modal').modal('show');
}, 1);
});
function do_install_shadowsocks_libev()
{
var url = 'index.cgi?app=shadowsocks-libev&action=install_shadowsocks_libev';
Ha.common.ajax(url, 'html', '', 'get', 'applist', function(data){
$('#fix_content').html(data);
$('#fix_Modal').modal('show');
}, 1);
}
$('#install_shadowsocks_libev').on('click', function(){
var $btn = $(this);
$btn.button('loading');
setInterval("do_install_shadowsocks_libev()", 5000);
});
</script>
EOF
}
lang=`main.sbin get_client_lang`
eval `cat $DOCUMENT_ROOT/apps/$FORM_app/i18n/$lang/i18n.conf`
. $DOCUMENT_ROOT/apps/sysinfo/sysinfo_lib.sh
. $DOCUMENT_ROOT/apps/shadowsocks-libev/shadowsocks_libev_lib.sh
if
[ $is_main_page = 1 ]
then
main
elif [ -n "$FORM_action" ]
then
$FORM_action
fi |
def sum_of_elements(list):
sum = 0
for item in list:
sum += item
return sum |
<filename>src/app/components/pages/software-projects/software-projects.component.spec.ts<gh_stars>0
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { SoftwareProjectsComponent } from './software-projects.component';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
describe('SoftwareProjectsComponent', () => {
let component: SoftwareProjectsComponent;
let fixture: ComponentFixture<SoftwareProjectsComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ RouterTestingModule ],
declarations: [ SoftwareProjectsComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SoftwareProjectsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('html should contain app-title-header', () => {
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('app-title-header')).not.toBe(null);
})
it("component should contain title 'Software Engineering Projects'", () => {
const projects = fixture.debugElement.componentInstance;
expect(projects.title).toEqual('Software Engineering Projects');
})
}); |
<filename>app/lib/github_linkback_access_token_setting_validator.rb
# frozen_string_literal: true
class GithubLinkbackAccessTokenSettingValidator
def initialize(opts = {})
@opts = opts
end
def valid_value?(val)
return true if val.blank?
client = Octokit::Client.new(access_token: val, per_page: 1)
DiscourseGithubPlugin::GithubRepo.repos.each do |repo|
client.branches(repo.name)
end
true
rescue Octokit::Unauthorized
false
end
def error_message
I18n.t("site_settings.errors.invalid_github_linkback_access_token")
end
end
|
import React, { useState, useRef } from 'react';
import { Paper, makeStyles, useTheme } from '@material-ui/core';
const useStyles = makeStyles({
canvas: {
background: '#fff',
},
});
const Paint = () => {
const classes = useStyles();
const canvasRef = useRef(null);
const theme = useTheme();
const [objects, setObjects] = useState([]);
// handle object selection and movement
useEffect(() => {
// handle drawing on the canvas
const context = canvasRef.current.getContext('2d');
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
// access every shape in the canvas
objects.forEach((object) => {
switch (object.type) {
case 'rectangle':
const { x, y, width, height } = object;
context.fillStyle = theme.palette.primary.main ;
context.fillRect(x, y, width, height);
break;
// more shape types implementation here
}
});
}, [objects, theme.palette.primary.main]);
return (
<Paper style={{ padding: theme.spacing(2) }}>
<canvas
ref={canvasRef}
width="300"
height="200"
className={classes.canvas}
onMouseDown={handleObjectSelection}
onMouseMove={handleObjectMovement}
onMouseUp={handleObjectReselection}
/>
</Paper>
);
};
export default Paint; |
<filename>src/app.module.ts
import { Logger, Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { GraphQLModule } from '@nestjs/graphql';
import { AuthenticationError } from 'apollo-server-core';
import { ConnectionParams } from 'subscriptions-transport-ws';
import { getEnvVariables as e, mapKeysToLowerCase } from './common';
import { GqlContext, GqlContextPayload } from './common/types';
import { AuthModule } from './auth/auth.module';
import { AuthService } from './auth/auth.service';
import { UserModule } from './user/user.module';
import { Neo4jModule } from './neo4j/neo4j.module';
import { NetworkModule } from './network/network.module';
@Module({
imports: [
// config module
ConfigModule.forRoot({
isGlobal: true,
}),
GraphQLModule.forRootAsync({
// import AuthModule
imports: [AuthModule],
// inject authService
useFactory: async (authService: AuthService) => ({
debug: true,
playground: true,
installSubscriptionHandlers: true,
autoSchemaFile: 'schema.gql',
// pass the original req and res object into the graphql context,
// get context with decorator `@Context() { req, res, payload, connection }: GqlContext`
// req, res used in http/query&mutations, connection used in webSockets/subscriptions
context: ({ req, res, payload, connection }: GqlContext) => ({ req, res, payload, connection }),
// configure graphql cors here
cors: {
origin: e().corsOriginReactFrontend,
credentials: true,
},
// subscriptions/webSockets authentication
subscriptions: {
// get headers
onConnect: (connectionParams: ConnectionParams) => {
// convert header keys to lowercase
const connectionParamsLowerKeys = mapKeysToLowerCase(connectionParams);
// get authToken from authorization header
const authToken: string = ('authorization' in connectionParamsLowerKeys)
&& connectionParamsLowerKeys.authorization.split(' ')[1];
if (authToken) {
// verify authToken/getJwtPayLoad
const jwtPayload: GqlContextPayload = authService.getJwtPayLoad(authToken);
// the user/jwtPayload object found will be available as context.currentUser/jwtPayload in your GraphQL resolvers
return { currentUser: jwtPayload.username, jwtPayload, headers: connectionParamsLowerKeys };
}
throw new AuthenticationError('authToken must be provided');
},
},
}),
// inject: AuthService
inject: [AuthService],
}),
// apolloServer config: use forRootAsync to import AuthModule and inject AuthService
// old without ConfigService
// AuthModule,
// auth module
AuthModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
accessTokenJwtSecret: configService.get('ACCESS_TOKEN_JWT_SECRET'),
accessTokenExpiresIn: configService.get('ACCESS_TOKEN_EXPIRES_IN'),
refreshTokenJwtSecret: configService.get('REFRESH_TOKEN_JWT_SECRET'),
refreshTokenExpiresIn: configService.get('REFRESH_TOKEN_EXPIRES_IN'),
refreshTokenSkipIncrementVersion: configService.get('REFRESH_TOKEN_SKIP_INCREMENT_VERSION'),
}),
}),
// old without ConfigService
// UserModule,
// users Module
UserModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
useMokeData: Boolean(
configService.get('USER_SERVICE_USE_MOKE_DATA') === 'true' ? true : false,
),
}),
}),
// neo4j
Neo4jModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
scheme: configService.get('NEO4J_SCHEME'),
host: configService.get('NEO4J_HOST'),
port: configService.get('NEO4J_PORT'),
username: configService.get('NEO4J_USERNAME'),
password: configService.get('<PASSWORD>'),
database: configService.get('NEO4J_DATABASE'),
options: {
maxConnectionPoolSize: configService.get('NEO4J_CONFIG_LOGGING_MAX_CONNECTION_POOL_SIZE'),
maxConnectionLifetime: configService.get('NEO4J_CONFIG_LOGGING_MAX_CONNECTION_LIFETIME'),
logging: {
level: configService.get('NEO4J_CONFIG_LOGGING_LEVEL'),
logger: (level, message) => Logger.log(`${level}:${message}`, Neo4jModule.name),
}
}
}),
}),
// fabric network
NetworkModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
connectionFile: configService.get('NETWORK_CONNECTION_FILE'),
walletPath: configService.get('NETWORK_WALLET_PATH') || 'network/wallets',
chaincodeName: configService.get('NETWORK_CHAINCODE_NAME'),
channelName: configService.get('NETWORK_CHANNEL_NAME'),
appAdmin: configService.get('NETWORK_APP_ADMIN'),
appAdminSecret: configService.get('NETWORK_APP_ADMIN_SECRET'),
orgMSPID: configService.get('NETWORK_ORG_MSPID'),
caName: configService.get('NETWORK_CA_NAME'),
peer: configService.get('NETWORK_PEER'),
orderer: configService.get('NETWORK_ORDERER'),
peerIdentity: configService.get('NETWORK_PEER_IDENTITY'),
gatewayDiscovery: {
enabled: Boolean(
configService.get('NETWORK_GATEWAY_DISCOVERY_ENABLED') === 'true' ? true : false,
),
asLocalhost: Boolean(
configService.get('NETWORK_GATEWAY_DISCOVERY_AS_LOCALHOST') === 'true' ? true : false,
),
},
nodePriority: Number(configService.get('NETWORK_NODE_PRIORITY')) || 0,
nodePriorityTimeout: Number(configService.get('NETWORK_NODE_PRIORITY_TIMEOUT')) || 250,
saveEventsPath: configService.get('NETWORK_SAVE_EVENTS_PATH'),
}),
}),
],
})
export class AppModule { }
|
<reponame>swoogles/ScalaFixDemos
/*
rule = NamedBooleansRule
*/
object NamingSchemeChange {
def complete(isSuccess: Boolean): Unit = ()
complete(true)
val myOldName = true
println(true)
def finish(isError: Boolean): Unit = ()
finish(true)
}
|
/*
* 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
///////////////
package org.apache.jena.ontology.impl;
// Imports
///////////////
import java.util.Iterator;
import org.apache.jena.enhanced.* ;
import org.apache.jena.graph.* ;
import org.apache.jena.ontology.* ;
import org.apache.jena.rdf.model.* ;
import org.apache.jena.util.iterator.ExtendedIterator ;
/**
* <p>
* Default implementation of the interface that defines a closed enumeration
* of concrete values for the range of a property.
* </p>
*/
public class DataRangeImpl
extends OntResourceImpl
implements DataRange
{
// Constants
//////////////////////////////////
// Static variables
//////////////////////////////////
/**
* A factory for generating DataRange facets from nodes in enhanced graphs.
* Note: should not be invoked directly by user code: use
* {@link org.apache.jena.rdf.model.RDFNode#as as()} instead.
*/
@SuppressWarnings("hiding")
public static Implementation factory = new Implementation() {
@Override
public EnhNode wrap( Node n, EnhGraph eg ) {
if (canWrap( n, eg )) {
return new DataRangeImpl( n, eg );
}
else {
throw new ConversionException( "Cannot convert node " + n + " to DataRange");
}
}
@Override
public boolean canWrap( Node node, EnhGraph eg ) {
// node will support being an DataRange facet if it has rdf:type owl:Datarange and is a bNode
Profile profile = (eg instanceof OntModel) ? ((OntModel) eg).getProfile() : null;
return (profile != null) && profile.isSupported( node, eg, DataRange.class );
}
};
// Instance variables
//////////////////////////////////
// Constructors
//////////////////////////////////
/**
* <p>
* Construct a data range node represented by the given node in the given graph.
* </p>
*
* @param n The node that represents the resource
* @param g The enh graph that contains n
*/
public DataRangeImpl( Node n, EnhGraph g ) {
super( n, g );
}
// External signature methods
//////////////////////////////////
// External signature methods
//////////////////////////////////
// oneOf
/**
* <p>Assert that this data range is exactly the enumeration of the given individuals. Any existing
* statements for <code>oneOf</code> will be removed.</p>
* @param en A list of literals that defines the permissible values for this datarange
* @exception ProfileException If the {@link Profile#ONE_OF()} property is not supported in the current language profile.
*/
@Override
public void setOneOf( RDFList en ) {
setPropertyValue( getProfile().ONE_OF(), "ONE_OF", en );
}
/**
* <p>Add a literal to the enumeration that defines the permissible values of this class.</p>
* @param lit A literal to add to the enumeration
* @exception ProfileException If the {@link Profile#ONE_OF()} property is not supported in the current language profile.
*/
@Override
public void addOneOf( Literal lit ) {
addListPropertyValue( getProfile().ONE_OF(), "ONE_OF", lit );
}
/**
* <p>Add each literal from the given iteratation to the
* enumeration that defines the permissible values of this datarange.</p>
* @param literals An iterator over literals
* @exception ProfileException If the {@link Profile#ONE_OF()} property is not supported in the current language profile.
*/
@Override
public void addOneOf( Iterator<Literal> literals ) {
while( literals.hasNext() ) {
addOneOf( literals.next() );
}
}
/**
* <p>Answer a list of literals that defines the extension of this datarange.</p>
* @return A list of literals that is the permissible values
* @exception ProfileException If the {@link Profile#ONE_OF()} property is not supported in the current language profile.
*/
@Override
public RDFList getOneOf() {
return objectAs( getProfile().ONE_OF(), "ONE_OF", RDFList.class );
}
/**
* <p>Answer an iterator over all of the literals that are declared to be the permissible values for
* this class. Each element of the iterator will be an {@link Literal}.</p>
* @return An iterator over the literals that are the permissible values
* @exception ProfileException If the {@link Profile#ONE_OF()} property is not supported in the current language profile.
*/
@Override
public ExtendedIterator<Literal> listOneOf() {
return getOneOf().iterator().mapWith( n -> n.as( Literal.class ) );
}
/**
* <p>Answer true if the given literal is one of the enumerated literals that are the permissible values
* of this datarange.</p>
* @param lit A literal to test
* @return True if the given literal is in the permissible values for this class.
* @exception ProfileException If the {@link Profile#ONE_OF()} property is not supported in the current language profile.
*/
@Override
public boolean hasOneOf( Literal lit ) {
return getOneOf().contains( lit );
}
/**
* <p>Remove the statement that this enumeration includes <code>lit</code> among its members. If this statement
* is not true of the current model, nothing happens.</p>
* @param lit A literal that may be declared to be part of this data range, and which is
* no longer to be one of the data range values.
*/
@Override
public void removeOneOf( Literal lit ) {
setOneOf( getOneOf().remove( lit ) );
}
// Internal implementation methods
//////////////////////////////////
//==============================================================================
// Inner class definitions
//==============================================================================
}
|
<gh_stars>1-10
/*-
* Copyright (c) 2012 UPLEX Nils Goroll Systemoptimierung
* Copyright (c) 2012 Otto Gmbh & Co KG
* All rights reserved
* Use only with permission
*
* Author: <NAME> <<EMAIL>>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "minunit.h"
#include "../strfTIM.h"
int tests_run = 0;
static char
*test_strfTIM_strftime(void)
{
time_t now;
struct tm *tm;
char strftime_s[BUFSIZ], strfTIM_s[BUFSIZ];
const char *fmt =
"%a %A %b %B %c %C %d %D %e %F %g %G %h %H %I %J %m %M %n %p %r %R %S "\
"%t %T %u %U %V %w %W %x %X %y %Y %z %Z %% %Ec %EC %Ex %EX %Ey %Ey "\
"%Od %Oe %OH %OI %Om %OM %OS %Ou %OU %OV %Ow %OW %Oy";
size_t strftime_n, strfTIM_n;
printf("... testing strfTIM equivalence to strftime\n");
time(&now);
tm = localtime(&now);
assert(tm != NULL);
strftime_n = strftime(strftime_s, BUFSIZ, fmt, tm);
strfTIM_n = strfTIM(strfTIM_s, BUFSIZ, fmt, tm, 0);
VMASSERT(strfTIM_n == strftime_n, "strfTIM return value %zu (expected %zu)",
strfTIM_n, strftime_n);
VMASSERT(strcmp(strfTIM_s, strftime_s) == 0,
"strfTIM result '%s' (expected '%s')", strfTIM_s, strftime_s);
return NULL;
}
static char
*test_strfTIM_N(void)
{
size_t n;
time_t t = 1382804827;
long usec = 112625;
const char *exp = "2013-10-26-16:27:07.112625";
char s[BUFSIZ];
struct tm *tm;
printf("... testing strfTIM %%i conversion specifier\n");
tm = gmtime(&t);
MAN(tm);
n = strfTIM(s, BUFSIZ, "%F-%T.%i", tm, usec);
VMASSERT(n == strlen(exp), "strfTIM return value %zu (expected %zu)", n,
strlen(exp));
VMASSERT(strcmp(s, exp) == 0, "strfTIM result '%s' (expected '%s')", s,
exp);
n = strfTIM(s, BUFSIZ, "%%i", tm, usec);
VMASSERT(n == strlen("%i"), "strfTIM return value %zu (expected %zu)", n,
strlen("%i"));
VMASSERT(strcmp(s, "%i") == 0, "strfTIM result '%s' (expected '%s')", s,
"%i");
n = strfTIM(s, BUFSIZ, "%%%i", tm, usec);
VMASSERT(n == strlen("%112625"), "strfTIM return value %zu (expected %zu)",
n, strlen("%112625"));
VMASSERT(strcmp(s, "%112625") == 0, "strfTIM result '%s' (expected '%s')",
s, "%112625");
return NULL;
}
static char
*test_strfTIMlocal(void)
{
size_t n;
time_t t = 1382804820;
struct tm *tm;
char s[BUFSIZ], exp[BUFSIZ];
printf("... testing strfTIMlocal\n");
n = strfTIMlocal(s, BUFSIZ, "%F-%T.%i", 1382804820.112625);
tm = localtime(&t);
MAN(tm);
strftime(exp, BUFSIZ, "%F-%T.112625", tm);
VMASSERT(n == strlen(exp), "strfTIMlocal return value %zu (expected %zu)",
n, strlen(exp));
/* Not accurate at the last decimal place, due to floating point
* precision */
s[n - 1] = exp[n - 1] = '\0';
VMASSERT(strcmp(s, exp) == 0, "strfTIMlocal result '%s' (expected '%s')",
s, exp);
return NULL;
}
static char
*test_strfTIMgm(void)
{
size_t n;
char s[BUFSIZ], exp[BUFSIZ];
printf("... testing strfTIMgm\n");
n = strfTIMgm(s, BUFSIZ, "%F-%T.%i", 1382804820.112625);
sprintf(exp, "2013-10-26-16:27:0%.6f", 0.112625);
VMASSERT(n == strlen(exp), "strfTIMgm return value %zu (expected %zu)",
n, strlen(exp));
/* As above */
s[n - 1] = exp[n - 1] = '\0';
VMASSERT(strcmp(s, exp) == 0, "strfTIMgm result '%s' (expected '%s')",
s, exp);
return NULL;
}
static const char
*all_tests(void)
{
mu_run_test(test_strfTIM_strftime);
mu_run_test(test_strfTIM_N);
mu_run_test(test_strfTIMlocal);
mu_run_test(test_strfTIMgm);
return NULL;
}
TEST_RUNNER
|
import React from 'react';
import PropTypes from 'prop-types';
import { compose, graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { Alert } from 'modules/common/utils';
import { Row } from '../components';
const RowContainer = props => {
const { refetch, duplicateMutation } = props;
const duplicateForm = _id => {
duplicateMutation({ variables: { _id } })
.then(() => {
Alert.success('Congrats');
refetch();
})
.catch(error => {
Alert.success(error.message);
});
};
const updatedProps = {
...props,
duplicateForm
};
return <Row {...updatedProps} />;
};
RowContainer.propTypes = {
duplicateMutation: PropTypes.func,
refetch: PropTypes.func
};
export default compose(
graphql(
gql`
mutation formsDuplicate($_id: String!) {
formsDuplicate(_id: $_id) {
_id
}
}
`,
{
name: 'duplicateMutation'
}
)
)(RowContainer);
|
def calculate_unique_pairs(cty_list):
if len(cty_list) == 1:
return 0
elif len(cty_list) == 2:
return len(cty_list[0]) * len(cty_list[1])
else:
cty_len_list = list(map(len, cty_list))
total_pairs = 0
for i in range(len(cty_len_list)):
for j in range(i+1, len(cty_len_list)):
total_pairs += cty_len_list[i] * cty_len_list[j]
return total_pairs |
#!/bin/bash
set -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
ROOT="$(cd $DIR/../ && pwd)"
ARCH=$(uname -m)
if [[ $SHELL == "/bin/zsh" ]]; then
RC_FILE="$HOME/.zshrc"
elif [[ $SHELL == "/bin/bash" ]]; then
RC_FILE="$HOME/.bashrc"
fi
# Install brew if required
if [[ $(command -v brew) == "" ]]; then
echo "Installing Hombrew"
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
echo "[ ] installed brew t=$SECONDS"
# make brew available now
if [[ $ARCH == "x86_64" ]]; then
echo 'eval "$(/usr/local/homebrew/bin/brew shellenv)"' >> $RC_FILE
eval "$(/usr/local/homebrew/bin/brew shellenv)"
else
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> $RC_FILE
eval "$(/opt/homebrew/bin/brew shellenv)"
fi
fi
# TODO: remove protobuf,protobuf-c,swig when casadi can be pip installed
brew bundle --file=- <<-EOS
brew "catch2"
brew "cmake"
brew "cppcheck"
brew "git-lfs"
brew "zlib"
brew "bzip2"
brew "capnp"
brew "coreutils"
brew "eigen"
brew "ffmpeg"
brew "glfw"
brew "libarchive"
brew "libusb"
brew "libtool"
brew "llvm"
brew "openssl"
brew "pyenv"
brew "qt@5"
brew "zeromq"
brew "protobuf"
brew "protobuf-c"
brew "swig"
EOS
# Install gcc-arm-embedded 10.3-2021.10. 11.x is broken on M1 Macs with Xcode 13.3~
brew uninstall gcc-arm-embedded || true
curl -L https://github.com/Homebrew/homebrew-cask/raw/d407663b8017a0a062c7fc0b929faf2e16abd1ff/Casks/gcc-arm-embedded.rb > /tmp/gcc-arm-embedded.rb
brew install --cask /tmp/gcc-arm-embedded.rb
rm /tmp/gcc-arm-embedded.rb
echo "[ ] finished brew install t=$SECONDS"
BREW_PREFIX=$(brew --prefix)
# archive backend tools for pip dependencies
export LDFLAGS="$LDFLAGS -L${BREW_PREFIX}/opt/zlib/lib"
export LDFLAGS="$LDFLAGS -L${BREW_PREFIX}/opt/bzip2/lib"
export CPPFLAGS="$CPPFLAGS -I${BREW_PREFIX}/opt/zlib/include"
export CPPFLAGS="$CPPFLAGS -I${BREW_PREFIX}/opt/bzip2/include"
# pycurl curl/openssl backend dependencies
export LDFLAGS="$LDFLAGS -L${BREW_PREFIX}/opt/openssl@3/lib"
export CPPFLAGS="$CPPFLAGS -I${BREW_PREFIX}/opt/openssl@3/include"
export PYCURL_SSL_LIBRARY=openssl
# openpilot environment
if [ -z "$OPENPILOT_ENV" ] && [ -n "$RC_FILE" ] && [ -z "$CI" ]; then
echo "source $ROOT/tools/openpilot_env.sh" >> $RC_FILE
source "$ROOT/tools/openpilot_env.sh"
echo "Added openpilot_env to RC file: $RC_FILE"
fi
# install python dependencies
$ROOT/update_requirements.sh
eval "$(pyenv init --path)"
echo "[ ] installed python dependencies t=$SECONDS"
# install casadi
VENV=`pipenv --venv`
PYTHON_VER=3.8
PYTHON_VERSION=$(cat $ROOT/.python-version)
if [ ! -f "$VENV/include/casadi/casadi.hpp" ]; then
echo "-- casadi manual install"
cd /tmp/ && curl -L https://github.com/casadi/casadi/archive/refs/tags/ge6.tar.gz --output casadi.tar.gz
tar -xzf casadi.tar.gz
cd casadi-ge6/ && mkdir -p build && cd build
cmake .. \
-DWITH_PYTHON=ON \
-DWITH_EXAMPLES=OFF \
-DCMAKE_INSTALL_PREFIX:PATH=$VENV \
-DPYTHON_PREFIX:PATH=$VENV/lib/python$PYTHON_VER/site-packages \
-DPYTHON_LIBRARY:FILEPATH=$HOME/.pyenv/versions/$PYTHON_VERSION/lib/libpython$PYTHON_VER.dylib \
-DPYTHON_EXECUTABLE:FILEPATH=$HOME/.pyenv/versions/$PYTHON_VERSION/bin/python \
-DPYTHON_INCLUDE_DIR:PATH=$HOME/.pyenv/versions/$PYTHON_VERSION/include/python$PYTHON_VER \
-DCMAKE_CXX_FLAGS="-ferror-limit=0" -DCMAKE_C_FLAGS="-ferror-limit=0"
CFLAGS="-ferror-limit=0" make -j$(nproc) && make install
else
echo "---- casadi found in venv. skipping build ----"
fi
echo
echo "---- OPENPILOT SETUP DONE ----"
echo "Open a new shell or configure your active shell env by running:"
echo "source $RC_FILE"
|
#!/bin/bash
#SBATCH --gres=gpu:2 # request GPU "generic resource"
#SBATCH --cpus-per-task=6 # maximum CPU cores per GPU request: 6 on Cedar, 16 on Graham.
#SBATCH --mem=10000M # memory per node
#SBATCH --time=0-00:10 # time (DD-HH:MM)
#SBATCH --output=scripts/caps_r/cifar10/test-1-adv_in_f_clean_mdls/o_t1_ILLCM_ep1_iter8.out # %N for node name, %j for jobID
source ~/tfp363/bin/activate
REPO_DIR=/home/xuc/Adversarial-Attack-on-CapsNets
SUMMARY_DIR=/home/xuc/scratch/xuc/summary/
MODEL=caps_r
DATASET=cifar10
ADVERSARIAL_METHOD=ILLCM
EPSILON=1
ITERATION_N=8
TEST_FILE=test_$ADVERSARIAL_METHOD\_eps$EPSILON\_iter$ITERATION_N.npz
python $REPO_DIR/experiment.py --mode=test --summary_dir=$SUMMARY_DIR/$MODEL/$DATASET/Default/ --load_test_path=$REPO_DIR/data/$MODEL/$DATASET/$TEST_FILE
|
setCurrency(unit: string) {
this.unitSubject.next(unit);
} |
<filename>src/main/java/pl/allegro/tech/opel/IdentifiersListNode.java<gh_stars>10-100
package pl.allegro.tech.opel;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class IdentifiersListNode implements OpelNode {
private final List<OpelNode> identifiers;
public IdentifiersListNode(List<OpelNode> identifiers) {
this.identifiers = identifiers;
}
@Override
public CompletableFuture<?> getValue(EvalContext context) {
throw new UnsupportedOperationException("Can't get value on ArgumentsListExpressionNode");
}
public static OpelNode empty() {
return new IdentifiersListNode(Collections.emptyList());
}
public List<OpelNode> getIdentifiers() {
return identifiers;
}
}
|
<gh_stars>0
#pragma once
#include "components/Component.hh"
#include <typed-geometry/types/objects/box.hh>
#include <typed-geometry/types/objects/sphere.hh>
namespace gamedev
{
// Oriented Bounding Box or Bounding Circle
struct BoxShape : public Component
{
using Component::Component;
tg::box3 box;
};
struct CircleShape : public Component
{
using Component::Component;
tg::sphere3 circle;
};
} |
from graphviz import Digraph
import json
import os
import logging
def view_source_dependency(source_file):
with open(f'../maps/{source_file}', 'r') as f:
view_source = json.load(f)
return view_source
def gen_graph(explore_name, join_list, connection, view_source_payload):
dot = Digraph(f'{explore_name}')
dot.node(explore_name, explore_name)
view_list = join_list
for view in view_list:
join_node = f'view_{view}'
dot.node(join_node, join_node)
dot.edge(explore_name, join_node, label=connection)
try:
with open(f'../maps/view-{view}.json', 'r') as f:
payload = json.load(f)
if payload['view_type'] == 'derived_table':
base_node = "Need further investigation"
elif payload['view_type'] == 'extension':
base_node = view_source_payload[payload['view_name']]['base_view_name']
else:
base_node = payload['source_table']
dot.node(base_node, base_node)
dot.edge(join_node, base_node)
except:
pass
dot.render(f'../graphs/{explore_name}.gv', view=False)
return logging.info(f'Successfully generated dependency graph for Explore {explore_name}.')
def main():
for model_folder in next(os.walk(f'../maps'))[1]:
for map_path in os.listdir(f'../maps/{model_folder}'):
if map_path.startswith('explore-'):
map_path = map_path.split('.')[0]
logging.info(f"Generating dependency graph for explore {map_path}...")
with open(f'../maps/{model_folder}/{map_path}.json', 'r') as f:
map_explore = json.load(f)
try:
view_source = view_source_dependency(f'{model_folder}/map-model-{model_folder}-{map_path}-source.json')
gen_graph(explore_name=map_explore['explore_name'], join_list=map_explore['explore_joins'], \
connection="", view_source_payload=view_source)
except:
pass
if __name__ == '__main__':
main()
|
#!/bin/bash
apt-get update && apt-get upgrade -y
apt-get install curl -y
apt-get install apache2 -y
apt-get install php5 libapache2-mod-php5 php5-mcrypt -y
service apache2 restart
apt-get install mysql-server php5-mysql -y
mysql_install_db
mysql_secure_installation
apt-get install phpmyadmin -y
php5enmod mcrypt
service apache2 restart
ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin
apt-get install libssh2-1-dev libssh2-php -y
mysql -h localhost -u root -proot -e "CREATE DATABASE ssh"
php -m |grep ssh2
service apache2 restart
cp painelssh.zip /var/www/html
cd /var/www/html
apt-get install unzip -y
unzip painelssh.zip
rm painelssh.zip index.html
clear |
<filename>src/human/service/lnw-human.service.ts
import { typeHuman } from "src/core/enum";
import { HumanDto } from "../dto/human.dto";
import { HumanService } from "./human.service";
export class LnwHumanService extends HumanService {
constructor() {
super()
}
createLnwHuman(humanDto: HumanDto) {
return this.create(typeHuman.lnw, humanDto)
}
readLnwHuman() {
return this.read(typeHuman.lnw)
}
updateLnwHuman(humanId: string, humanDto: HumanDto) {
return this.update(+humanId, humanDto)
}
deleteLnwHuman(humanId: string) {
return this.delete(+humanId)
}
} |
<filename>src/pages/Home.js<gh_stars>0
import React from 'react';
import styled from 'styled-components';
// components
import Container from '../components/Container';
import SocialMedia from '../components/SocialMedia';
// data
import content from '../data/home';
export default function Home() {
return (
<Container main>
<Heading>{content.heading}</Heading>
<Text dangerouslySetInnerHTML={{ __html: content.text }} />
<SocialMedia />
</Container>
);
}
const Heading = styled.h1`
text-align: center;
color: #1f1f2f;
font-size: 2em;
`;
const Text = styled.p`
text-align: center;
color: #1f1f2f;
font-size: 1.2em;
max-width: 770px;
@media (max-width: 480px) {
font-size: 1em;
}
a {
color: #ad9300;
text-decoration: none;
}
`;
|
#!/bin/bash
EXE=brusselator_radau
# convergence study
STEPS=100
Nx=1000
echo "running radau with with nt = ${STEPS}, neq=${Nx}" >> ${EXE}.log
time ./${EXE} ${STEPS} ${Nx} > n1.dat
STEPS=200
echo "running radau with with nt = ${STEPS}, neq=${Nx}" >> ${EXE}.log
time ./${EXE} ${STEPS} ${Nx} > n2.dat
STEPS=400
echo "running radau with with nt = ${STEPS}, neq=${Nx}" >> ${EXE}.log
time ./${EXE} ${STEPS} ${Nx} > n3.dat
STEPS=800
echo "running radau with with nt = ${STEPS}, neq=${Nx}" >> ${EXE}.log
time ./${EXE} ${STEPS} ${Nx} > n4.dat
STEPS=1600
echo "running radau with with nt = ${STEPS}, neq=${Nx}" >> ${EXE}.log
time ./${EXE} ${STEPS} ${Nx} > n5.dat
|
class ApplicationController < ActionController::Base
# Make the current_user method available to views also, not just controllers:
helper_method :current_user
helper_method :current_identifier
# Define the current_user method:
def current_user
# Look up the current user based on user_id in the session cookie:
User.find(session[:user_id]) if session[:user_id]
end
def current_identifier
user = current_user
if user.nil?
"Relatório Exemplo"
else
user.identifier
end
end
# authroize method redirects user to login page if not logged in:
def authorize
if current_user.nil?
redirect_to login_path, alert: 'You must be logged in to access this page.'
false
else
true
end
end
end
|
<filename>src/string_handle/Boj2743.java
package string_handle;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Boj2743 {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(br.readLine().length());
}
}
|
<reponame>buffrr/letsdane<filename>resolver/unboundna.go
//go:build !unbound
// +build !unbound
package resolver
type Recursive struct {
DefaultResolver
}
func NewRecursive() (r *Recursive, err error) {
return nil, ErrUnboundNotAvail
}
func (r *Recursive) SetFwd(addr string) error {
return ErrUnboundNotAvail
}
func (r *Recursive) ResolvConf(name string) error {
return ErrUnboundNotAvail
}
func (r *Recursive) AddTA(ta string) error {
return ErrUnboundNotAvail
}
func (r *Recursive) AddTAFile(file string) error {
return ErrUnboundNotAvail
}
func (r *Recursive) Destroy() {
}
|
package com.example.service;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.example.model.Greeting;
@Service
public class CompletableFutureEmailServiceBean implements EmailService {
/**
* The Logger for this class.
*/
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* Synchronous send method.
*/
@Override
public Boolean send(final Greeting greeting) {
logger.info("> send");
Boolean success = Boolean.FALSE;
// Simulate method execution time
final long pause = 5000;
try {
Thread.sleep(pause);
} catch (final Exception e) {
// do nothing
}
logger.info("Processing time was {} seconds.", pause / 1000);
success = Boolean.TRUE;
logger.info("< send");
return success;
}
@Async
@Override
public void sendAsync(final Greeting greeting) {
logger.info("> sendAsync");
try {
send(greeting);
} catch (final Exception e) {
logger.warn("Exception caught sending asynchronous mail.", e);
}
logger.info("< sendAsync");
}
@Async
@Override
public Future<Boolean> sendAsyncWithResult(final Greeting greeting) {
logger.info("> sendAsyncWithResult");
final CompletableFuture<Boolean> response = new CompletableFuture<Boolean>();
try {
final Boolean success = send(greeting);
response.complete(success);
} catch (final Exception e) {
logger.warn("Exception caught sending asynchronous mail.", e);
response.completeExceptionally(e);
}
logger.info("< sendAsyncWithResult");
return response;
}
}
|
// events.rs
// Define the event types, event handlers, and event dispatchers
pub mod events {
pub struct Event {
// Define the event structure
}
pub struct EventHandler {
// Define the event handler structure
}
pub struct EventDispatcher {
// Define the event dispatcher structure
}
// Export all items from the events module
pub use self::{Event, EventHandler, EventDispatcher};
} |
#!/bin/bash
##############################################################################
# The script parses the output from filemon and creates prolog facts that
# contains the mapping of process-file-operationType
##############################################################################
IFS=$'\n'
for fileAccessEntry in $(cat iOracle.out); do
processId=`echo $fileAccessEntry | awk '{print $1}'`
pathToProcessExecutable=`cat pid_uid_gid_comm.out | grep -w $processId | awk '{print substr($0, index($0, $4))}'`
processName=`echo $fileAccessEntry | cut -d$'\t' -f1 | awk '{print substr($0, index($0, $2))}'`
# Check if PID is a number
if [[ ! $processId == ?(-)+([0-9]) ]]; then
continue
fi
# Check if path is null
if [[ -z $pathToProcessExecutable ]]; then
continue
fi
# Process name has two words
if [[ `echo $processName | wc -w` == 2 ]]; then
operationType=`echo $fileAccessEntry | awk '{print $4}'`
pathToSourceFile=`echo $fileAccessEntry | awk '{print substr($0, index($0, $5))}' | cut -d$'\t' -f1 | xargs`
pathToDestinationFile=`echo $fileAccessEntry | awk '{print substr($0, index($0, $5))}' | cut -d$'\t' -f2 | xargs`
# Operation with multiple words; ex:"Changed xattr/stat"
if [[ $operationType == "Changed" ]]; then
operationType=`echo $fileAccessEntry | awk '{print $4" "$5}'`
pathToSourceFile=`echo $fileAccessEntry | awk '{print substr($0, index($0, $6))}' | cut -d$'\t' -f1 | xargs`
pathToDestinationFile=`echo $fileAccessEntry | awk '{print substr($0, index($0, $6))}' | cut -d$'\t' -f2 | xargs`
fi
# Operation "Created dir"
if [[ `echo $fileAccessEntry | awk '{print $4" "$5}'` == "Created dir" ]]; then
operationType=`echo $fileAccessEntry | awk '{print $4" "$5}'`
pathToSourceFile=`echo $fileAccessEntry | awk '{print substr($0, index($0, $6))}' | cut -d$'\t' -f1 | xargs`
pathToDestinationFile=`echo $fileAccessEntry | awk '{print substr($0, index($0, $6))}' | cut -d$'\t' -f2 | xargs`
fi
else # Process name has one word
operationType=`echo $fileAccessEntry | awk '{print $3}'`
pathToSourceFile=`echo $fileAccessEntry | awk '{print substr($0, index($0, $4))}' | cut -d$'\t' -f1 | xargs`
pathToDestinationFile=`echo $fileAccessEntry | awk '{print substr($0, index($0, $4))}' | cut -d$'\t' -f2 | xargs`
# Operation with multiple words; ex:"Changed xattr/stat"
if [[ $operationType == "Changed" ]]; then
operationType=`echo $fileAccessEntry | awk '{print $3" "$4}'`
pathToSourceFile=`echo $fileAccessEntry | awk '{print substr($0, index($0, $5))}' | cut -d$'\t' -f1 | xargs`
pathToDestinationFile=`echo $fileAccessEntry | awk '{print substr($0, index($0, $5))}' | cut -d$'\t' -f2 | xargs`
fi
# Operation "Created dir"
if [[ `echo $fileAccessEntry | awk '{print $3" "$4}'` == "Created dir" ]]; then
operationType=`echo $fileAccessEntry | awk '{print $3" "$4}'`
pathToSourceFile=`echo $fileAccessEntry | awk '{print substr($0, index($0, $5))}' | cut -d$'\t' -f1 | xargs`
pathToDestinationFile=`echo $fileAccessEntry | awk '{print substr($0, index($0, $5))}' | cut -d$'\t' -f2 | xargs`
fi
fi
# Destination file does not exist -> write dummy text
if [[ -z $pathToDestinationFile ]]; then
pathToDestinationFile=`echo No destination`
fi
# Write the facts to file
echo "fileAccessObservation(process(\"$pathToProcessExecutable\"),sourceFile(\"$pathToSourceFile\"),destinationFile(\"$pathToDestinationFile\"),operation(\"$operationType\"))."
done 2> /dev/null
|
<html>
<head>
<title>Preferred Color</title>
<script>
function setBackground(){
let color = document.getElementById("color").value
document.body.style.background = color
}
</script>
</head>
<body>
<h1>Preferred Color</h1>
<input type="color" id="color" />
<input type="button" value="Set Background" onclick="setBackground()" />
</body>
</html> |
#! /bin/sh
# $Id: ip6tables_init.sh,v 1.1 2012/04/24 22:13:41 nanard Exp $
IPTABLES=/sbin/ip6tables
#change this parameters :
EXTIF=eth0:0
#adding the MINIUPNPD chain for filter
$IPTABLES -t filter -N MINIUPNPD
#adding the rule to MINIUPNPD
$IPTABLES -t filter -A FORWARD -i $EXTIF ! -o $EXTIF -j MINIUPNPD
|
class ApplicationMailer < ActionMailer::Base
## このファイルのソースコードは非公開です。
## Sources in this file are hidden, because of security reason.
end
|
#!/bin/bash
set -e
HOST="0.0.0.0"
PORT="8080"
while [[ $# > 1 ]]
do
key="$1"
case $key in
-l|--license-key)
LICENSE="$2"
shift # past argument
;;
-p|--password)
PASSWORD="$2"
shift # past argument
;;
-u|--username)
USERNAME="$2"
shift # past argument
;;
-h|--host)
HOST="$2"
shift # past argument
;;
--port)
PORT="$2"
shift # past argument
;;
*)
# unknown option
;;
esac
shift # past argument or value
done
if [ -z ${LICENSE+x} ]; then echo "A license for AMP from cubecoders.com is required and must be specified as --license_key xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; exit 1; fi
if [ -z ${USERNAME+x} ]; then echo "A username must be specified. eg --username amp_user"; exit 1; fi
if [ -z ${PASSWORD+x} ]; then echo "A password must be specified. eg --password P4$$w0Rd"; exit 1; fi
exec ./ampinstmgr CreateInstance ADS ADSInstance $HOST $PORT $LICENSE $PASSWORD +Core.Login.Username $USERNAME
exec ./ampinstmgr StartInstance ADSInstance
|
<gh_stars>0
from os import path, listdir
import re
import pandas as pd
# Define folder where the input files are kept
my_dir = './data/wos/'
# List all files in the specified folder
my_files = [f for f in listdir(my_dir) if path.isfile(path.join(my_dir, f))]
# Data dictionary based on Zoological Records documentation, used to translate
# the output fields into meaningful columns. Link:
# https://images.webofknowledge.com/images/help/ZOOREC/hs_zoorec_fieldtags.html
zr_fields = {
'FN': 'File Name',
'VR': 'Version Number',
'PT': 'Publication Type',
'AN': 'Zoological Record Accession Number',
'DT': 'Document Type',
'TI': 'Title',
'FT': 'Foreign Title',
'AU': 'Authors',
'BA': 'Book Authors',
'GP': 'Group Authors',
'ED': 'Editors',
'SO': 'Source',
'VL': 'Volume',
'IS': 'Issue',
'SU': 'Supplement',
'PS': 'Page Span',
'PD': 'Publication Date',
'PY': 'Year Published',
'UR': 'Journal URL',
'AW': 'Item URL',
'NT': 'Notes',
'LA': 'Language',
'AB': 'Abstract',
'C1': 'Author Address',
'EM': 'E-mail Address',
'RI': 'ResearcherID Number',
'OI': 'ORCID Identifier (Open Researcher and Contributor ID)',
'U1': 'Usage Count (Last 180 Days)',
'U2': 'Usage Count (Since 2013)',
'PU': 'Publisher',
'PA': 'Publisher Address',
'SC': 'Research Areas',
'SN': 'International Standard Serial Number (ISSN)',
'BN': 'International Standard Book Number (ISBN)',
'BD': 'Broad Terms',
'DE': 'Descriptors Data',
'TN': 'Taxa Notes',
'ST': 'Super Taxa',
'OR': 'Systematics',
'DI': 'Digital Object Identifier (DOI)',
'UT': 'Unique Article Identifier',
'OA': 'Open Access Indicator',
'HP': 'ESI Hot Paper. Note that this field is valued only for ESI subscribers',
'HC': 'ESI Highly Cited Paper. Note that this field is valued only for ESI subscribers',
'DA': 'Date this report was generated',
'ER': '[End of Record]',
'EF': '[End of File]',
}
def zr_parser(filepath):
"""Parse the plain text output format from Clarivate's Zoological Record
Args:
filepath (str): String with the filepath to the Zoological Record's
output file.
Returns:
list: List of dictionaries, each dictionary containing one record from
Zoological Record's output files.
"""
with open(filepath, mode='r', encoding="Utf-8") as input_file:
record_list = list()
record = dict()
for line in input_file:
# Avoid the first two lines of the file
if line[1:3] != 'FN' and line[:2] != 'VR':
# If the line means 'End of Record', then add the dict to the
# list, and renew the dict
if line[:2] == 'ER':
record_list.append(record)
record = dict()
# Search for lines that start with a field. If so, create the
# key on the current dictionary
elif re.search('[A-Z]+', line[:2]) != None:
cur = line[:2]
record[zr_fields.get(cur)] = line[3:].strip()
# If not, check if there are two spaces at the beginning. These
# are associated with multi-value fields, like Authors. Plus,
# the lines in between records are singled spaced, which means,
# this also avoids them.
elif line[:2] == " ":
record[zr_fields.get(cur)] += ", " + line[3: ].strip()
return record_list
def create_df(files_list=my_files):
"""Return a Pandas DataFrame from Zoological Record's output file(s).
Args:
files_list (list): List with the output file names to be processed.
Returns:
pandas.DataFrame: DataFrame with all data, saved in different files, combined.
"""
all_records = list()
for file in files_list:
all_records += zr_parser(path.join(my_dir, file))
return pd.DataFrame(all_records)
def to_pickle(df, dir=dir):
df.to_pickle(dir) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from os import name
import sys
sys.path.append(".")
# Import der Bibliotheken
from RFEM.enums import *
from RFEM.dataTypes import *
from RFEM.initModel import *
from RFEM.LoadCasesAndCombinations.staticAnalysisSettings import *
from RFEM.LoadCasesAndCombinations.loadCase import *
from RFEM.LoadCasesAndCombinations.designSituation import *
def test_design_situation():
clientModel.service.begin_modification('new')
StaticAnalysisSettings()
# Testing: Automatic naming, design situation keys and manual comments
DesignSituation(no= 1, user_defined_name= False, design_situation_type= 6122, comment= 'ULS (EQU) - Permanent and transient')
ds = clientModel.service.get_design_situation(1)
assert ds.no == 1
DesignSituation(no= 2, user_defined_name= False, design_situation_type= 6993, comment= 'ULS (EQU) - Accidental - psi-1,1')
ds = clientModel.service.get_design_situation(2)
assert ds.no == 2
DesignSituation(no= 3, user_defined_name= False, design_situation_type= 6994, comment= 'ULS (EQU) - Accidental - psi-2,1')
ds = clientModel.service.get_design_situation(3)
assert ds.no == 3
DesignSituation(no= 4, user_defined_name= False, design_situation_type= 6995, comment= 'ULS (EQU) - Accidental - Snow - psi-1,1')
ds = clientModel.service.get_design_situation(4)
assert ds.no == 4
# Testing: Manual naming, design situation keys
DesignSituation(no= 5, user_defined_name= True, name= 'MANUAL NAME: ULS (EQU) - Accidental - Snow - psi-2,1', design_situation_type= 6996)
ds = clientModel.service.get_design_situation(5)
assert ds.no == 5
DesignSituation(no= 6, user_defined_name= True, name= 'MANUAL NAME: ULS (EQU) - Seismic', design_situation_type= 6997)
ds = clientModel.service.get_design_situation(6)
assert ds.no == 6
# Testing: Design situation keys
DesignSituation(7, design_situation_type= 7007)
ds = clientModel.service.get_design_situation(7)
assert ds.no == 7
DesignSituation(8, design_situation_type= 7010)
ds = clientModel.service.get_design_situation(8)
assert ds.no == 8
DesignSituation(9, design_situation_type= 7011)
ds = clientModel.service.get_design_situation(9)
assert ds.no == 9
DesignSituation(10, design_situation_type= 7012)
ds = clientModel.service.get_design_situation(10)
assert ds.no == 10
DesignSituation(11, design_situation_type= 7013)
ds = clientModel.service.get_design_situation(11)
assert ds.no == 11
# Testing: Active toggle and design situation keys
DesignSituation(12, design_situation_type= 7014, active= True)
ds = clientModel.service.get_design_situation(12)
assert ds.no == 12
DesignSituation(13, design_situation_type= 6193, active= True)
ds = clientModel.service.get_design_situation(13)
assert ds.no == 13
DesignSituation(14, design_situation_type= 6194, active= False)
ds = clientModel.service.get_design_situation(14)
assert ds.no == 14
DesignSituation(15, design_situation_type= 6195, active= False)
ds = clientModel.service.get_design_situation(15)
assert ds.no == 15
clientModel.service.finish_modification() |
function updateListNameById(listId, newTitle) {
// Assume there is a data structure or database where vocabulary lists are stored
// Update the title of the vocabulary list identified by listId with the newTitle
// Example using an array of vocabulary lists:
for (let i = 0; i < vocabularyLists.length; i++) {
if (vocabularyLists[i].id === listId) {
vocabularyLists[i].title = newTitle;
break;
}
}
// Example using a database query:
// Update vocabulary list title in the database using SQL or NoSQL query
} |
import React, {ReactNode} from 'react';
import {toast} from 'react-toastify';
import Toast, {ToastType} from '@renderer/components/Toast';
export const displayErrorToast = (error: any) => {
let errorStr: string;
if (typeof error === 'string') {
errorStr = error;
} else if (error?.response?.data) {
errorStr = JSON.stringify(error.response.data);
} else if (error?.message) {
errorStr = error.message;
} else {
errorStr = JSON.stringify(error);
}
displayToast(errorStr);
};
export const displayToast = (message: ReactNode, type: ToastType = 'warning', className?: string): void => {
toast(
<Toast className={className} type={type}>
{message}
</Toast>,
);
};
|
module Elibri
module ONIX
module Release_3_0
class AudienceRange
#from ONIX documentation:
#An optional and repeatable group of data elements which together describe an audience or readership range for which a product
#is intended.
#:nodoc:
ATTRIBUTES = [
:qualifier, :precision, :value
]
#:nodoc:
RELATIONS = []
attr_reader :qualifier, :precision, :value, :to_xml
def initialize(data)
@old_xml = data.to_s
@qualifier = data.at_css('AudienceRangeQualifier').try(:text)
@precision = data.at_css('AudienceRangePrecision').try(:text)
@value = data.at_css('AudienceRangeValue').try(:text).try(:to_i)
end
end
end
end
end
|
#!/bin/bash
#
# Deploy a jar, source jar, and javadoc jar to Sonatype's snapshot repo.
#
# Adapted from https://coderwall.com/p/9b_lfq and
# http://benlimmer.com/2013/12/26/automatically-publish-javadoc-to-gh-pages-with-travis-ci/
SLUG="bobymicroby/elmo"
JDK="oraclejdk8"
BRANCH="master"
set -e
if [ "$TRAVIS_REPO_SLUG" != "$SLUG" ]; then
echo "Skipping snapshot deployment: wrong repository. Expected '$SLUG' but was '$TRAVIS_REPO_SLUG'."
elif [ "$TRAVIS_JDK_VERSION" != "$JDK" ]; then
echo "Skipping snapshot deployment: wrong JDK. Expected '$JDK' but was '$TRAVIS_JDK_VERSION'."
elif [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
echo "Skipping snapshot deployment: was pull request."
elif [ "$TRAVIS_BRANCH" != "$BRANCH" ]; then
echo "Skipping snapshot deployment: wrong branch. Expected '$BRANCH' but was '$TRAVIS_BRANCH'."
else
echo "Deploying snapshot..."
./gradlew clean uploadArchives
echo "Snapshot deployed!"
fi
|
// 16395. 파스칼의 삼각형
// 2019.05.22
// 수학
#include <iostream>
using namespace std;
// 조합 구하는 함수
int nCk(int n, int k)
{
if (n == k || k == 0)
{
return 1;
}
else
{
return nCk(n - 1, k - 1) + nCk(n - 1, k);
}
}
int main()
{
int n, k;
cin >> n >> k;
cout << nCk(n - 1, k - 1) << endl;
return 0;
}
|
func moveToRoom(player: Player, direction: String) -> String {
guard let nextRoom = player.currentRoom.exits[direction] else {
return "You cannot go that way."
}
player.currentRoom = nextRoom
return nextRoom.description
} |
# -*- coding: utf-8 -*-
from django.utils.http import is_safe_url
from django.http import HttpResponseRedirect
from django.views.decorators.cache import never_cache
from .models import Currency
from .conf import SESSION_KEY
@never_cache
def set_currency(request):
next, currency_code = (
request.POST.get('next') or request.GET.get('next'),
request.POST.get('currency_code', None) or
request.GET.get('currency_code', None))
if not is_safe_url(url=next, host=request.get_host()):
next = request.META.get('HTTP_REFERER')
if not is_safe_url(url=next, host=request.get_host()):
next = '/'
response = HttpResponseRedirect(next)
if currency_code and Currency.active.filter(code=currency_code).exists():
if hasattr(request, 'session'):
request.session[SESSION_KEY] = currency_code
else:
response.set_cookie(SESSION_KEY, currency_code)
return response
|
<gh_stars>0
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.fhwa.c2cri.reports;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* Captures all information related to Message event in a log file. *
* @author TransCore ITS, LLC
*/
@Entity
@Table(name = "Messages")
@NamedQueries({
@NamedQuery(name = "Messages.findAll", query = "SELECT m FROM Messages m"),
@NamedQuery(name = "Messages.findByMessageID", query = "SELECT m FROM Messages m WHERE m.messageID = :messageID"),
@NamedQuery(name = "Messages.findByEventID", query = "SELECT m FROM Messages m WHERE m.eventID = :eventID"),
@NamedQuery(name = "Messages.findByEventType", query = "SELECT m FROM Messages m WHERE m.eventType = :eventType"),
@NamedQuery(name = "Messages.findByEventTypeID", query = "SELECT m FROM Messages m WHERE m.eventTypeID = :eventTypeID"),
@NamedQuery(name = "Messages.findByDebugInfo", query = "SELECT m FROM Messages m WHERE m.debugInfo = :debugInfo")})
public class Messages implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "MessageID")
private Integer messageID;
@Column(name = "EventID")
private Integer eventID;
@Column(name = "eventType")
private String eventType;
@Column(name = "eventTypeID")
private Integer eventTypeID;
@Column(name = "debugInfo")
private String debugInfo;
public Messages() {
}
public Messages(Integer messageID) {
this.messageID = messageID;
}
public Integer getMessageID() {
return messageID;
}
public void setMessageID(Integer messageID) {
this.messageID = messageID;
}
public Integer getEventID() {
return eventID;
}
public void setEventID(Integer eventID) {
this.eventID = eventID;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public Integer getEventTypeID() {
return eventTypeID;
}
public void setEventTypeID(Integer eventTypeID) {
this.eventTypeID = eventTypeID;
}
public String getDebugInfo() {
return debugInfo;
}
public void setDebugInfo(String debugInfo) {
this.debugInfo = debugInfo;
}
@Override
public int hashCode() {
int hash = 0;
hash += (messageID != null ? messageID.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Messages)) {
return false;
}
Messages other = (Messages) object;
if ((this.messageID == null && other.messageID != null) || (this.messageID != null && !this.messageID.equals(other.messageID))) {
return false;
}
return true;
}
@Override
public String toString() {
return "org.fhwa.c2cri.reports.Messages[messageID=" + messageID + "]";
}
}
|
<filename>Exams/JavaScript-Software-University-master/JavaScript-Software-University-master/JavaScript-Fundamentals/Functions-and-Logic Flow/Lab/01_Multiplication-Table/solution.js
function solve() {
let firstNumber = +document.getElementById('num1').value;
let secondNumber = +document.getElementById('num2').value;
let resultElement = document.getElementById('result');
if (firstNumber > secondNumber) {
resultElement.innerHTML = 'Try with other numbers.';
} else {
for (let i = firstNumber; i <= secondNumber; i++) {
let pElement = document.createElement('p');
pElement.textContent = `${i} * ${secondNumber} = ${i * secondNumber}`;
resultElement.appendChild(pElement);
}
}
} |
<reponame>werliefertwas/dashing_resque
module DashingResque
module Job
def schedule(interval, options = {})
rufus_opts = options.reverse_merge(first_in: 0)
SCHEDULER.every(interval, **rufus_opts) do
send_event("resque_#{ancestors.first.name.demodulize.underscore}", **data)
end
end
end
end
|
#!/bin/bash
[ -z "$URL" ] && { echo "URL not specified"; exit 1; }
[ -z "INSTALL_TO" ] && { echo "INSTALL_TO not specified"; exit 1; }
set -e
echo "Downloading $URL"
curl $CURL_OPTS -o /tmp/disk $URL
echo "Converting to RAW and installing to $INSTALL_TO"
qemu-img convert -O raw /tmp/disk $INSTALL_TO
|
import logging
import numpy as np
import pandas as pd
from .. import ctd_plots, get_ctdcal_config
cfg = get_ctdcal_config()
log = logging.getLogger(__name__)
btl_file = "data/scratch_folder/report_data.csv"
btl_df = pd.read_csv(btl_file)
# TODO: these were in old plots module; worth adding?
# (BTLCOND - C1) vs. BTLCOND
# (BTLCOND - C2) vs. BTLCOND
# (C1 - C2) vs. BTLCOND
# (BTLCOND - C1_uncorrected) vs. STNNBR
# (BTLCOND - C2_uncorrected) vs. STNNBR
# (C1_uncorrected - C2_uncorrected) vs. STNNBR
# T1 vs. (OXYGEN - CTDOXY)
# (OXYGEN - CTDOXY) vs. STNNBR (c=T1)
# deep(OXYGEN - CTDOXY) vs. STNNBR (c=T1)
# OXYGEN vs. (OXYGEN - CTDOXY) (c=STNNBR)
# OXYGEN vs. (OXYGEN - CTDOXY) (c=CTDPRS)
def plot_residuals(outdir="data/report_figs/", ext=".pdf"):
#################################################################
##### Here lies the temperature plots, long may they rest. #####
#################################################################
log.info("Generating temperature residual plots")
for param, ref in zip(["t1", "t2", "t2"], ["refT", "refT", "t1"]):
ctd_plots.residual_vs_pressure(
btl_df[cfg.column[param]],
btl_df[cfg.column[ref]],
btl_df["CTDPRS"],
stn=btl_df["STNNBR"],
xlabel=f"{cfg.column[param]} Residual (T90 C)",
f_out=f"{outdir}{ref}-{param}_vs_p{ext}",
)
ctd_plots.residual_vs_station(
btl_df[cfg.column[param]],
btl_df[cfg.column[ref]],
btl_df["CTDPRS"],
btl_df["STNNBR"],
ylabel=f"{cfg.column[param]} Residual (T90 C)",
f_out=f"{outdir}{ref}-{param}_vs_stn{ext}",
)
ctd_plots.residual_vs_station(
btl_df[cfg.column[param]],
btl_df[cfg.column[ref]],
btl_df["CTDPRS"],
btl_df["STNNBR"],
ylabel=f"{cfg.column[param]} Residual (T90 C)",
deep=True,
f_out=f"{outdir}{ref}-{param}_vs_stn_deep{ext}",
)
#################################################################
##### Here lies the conductivity plots, long may they rest. #####
#################################################################
log.info("Generating conductivity residual plots")
for param, ref in zip(["c1", "c2", "c2"], ["refC", "refC", "c1"]):
ctd_plots.residual_vs_pressure(
btl_df[cfg.column[param]],
btl_df[cfg.column[ref]],
btl_df["CTDPRS"],
stn=btl_df["STNNBR"],
xlabel=f"{cfg.column[param]} Residual (mS/cm)",
f_out=f"{outdir}{ref}-{param}_vs_p{ext}",
)
ctd_plots.residual_vs_station(
btl_df[cfg.column[param]],
btl_df[cfg.column[ref]],
btl_df["CTDPRS"],
btl_df["STNNBR"],
ylabel=f"{cfg.column[param]} Residual (mS/cm)",
f_out=f"{outdir}{ref}-{param}_vs_stn{ext}",
)
ctd_plots.residual_vs_station(
btl_df[cfg.column[param]],
btl_df[cfg.column[ref]],
btl_df["CTDPRS"],
btl_df["STNNBR"],
ylabel=f"{cfg.column[param]} Residual (mS/cm)",
deep=True,
f_out=f"{outdir}{ref}-{param}_vs_stn_deep{ext}",
)
# coherence plot doesn't have its own function...
import matplotlib.pyplot as plt
plt.figure(figsize=(7, 6))
plt.scatter(
btl_df["CTDTMP1"] - btl_df["CTDTMP2"],
btl_df["CTDCOND1"] - btl_df["CTDCOND2"],
c=btl_df["CTDPRS"],
marker="+",
)
plt.xticks(rotation=45)
cbar = plt.colorbar(pad=0.1)
cbar.set_label("Pressure (dbar)")
plt.xlim((-0.05, 0.05))
plt.ylim((-0.05, 0.05))
plt.xlabel("CTDTMP1-CTDTMP2 Residual (T90 C)", fontsize=12)
plt.ylabel("CTDCOND1-CTDCOND2 Residual (mS/cm)", fontsize=12)
plt.title("CTDCOND1-CTDCOND2 vs. CTDTMP1-CTDTMP2", fontsize=12)
plt.tight_layout()
plt.savefig(f"{outdir}c_t_coherence{ext}")
plt.close()
# salinity plots
log.info("Generating salinity residual plots")
ctd_plots.residual_vs_pressure(
btl_df["CTDSAL"],
btl_df["SALNTY"],
btl_df["CTDPRS"],
stn=btl_df["STNNBR"],
xlabel="CTDSAL Residual (PSU)",
f_out=f"{outdir}btlsal-sal_vs_p{ext}",
)
ctd_plots.residual_vs_station(
btl_df["CTDSAL"],
btl_df["SALNTY"],
btl_df["CTDPRS"],
btl_df["STNNBR"],
ylabel="CTDSAL Residual (PSU)",
f_out=f"{outdir}btlsal-sal_vs_stn{ext}",
)
ctd_plots.residual_vs_station(
btl_df["CTDSAL"],
btl_df["SALNTY"],
btl_df["CTDPRS"],
btl_df["STNNBR"],
ylabel="CTDSAL Residual (PSU)",
deep=True,
f_out=f"{outdir}btlsal-sal_vs_stn_deep{ext}",
)
#################################################################
######## Here lies the oxygen plots, long may they rest. ########
#################################################################
# SBE43 oxygen plots
log.info("Generating oxygen (SBE43) residual plots")
ctd_plots.residual_vs_pressure(
btl_df["CTDOXY"],
btl_df["OXYGEN"],
btl_df["CTDPRS"],
stn=btl_df["STNNBR"],
xlim=(-10, 10),
xlabel="CTDOXY Residual (umol/kg)",
f_out=f"{outdir}oxy-43_vs_p{ext}",
)
ctd_plots.residual_vs_station(
btl_df["CTDOXY"],
btl_df["OXYGEN"],
btl_df["CTDPRS"],
btl_df["STNNBR"],
ylim=(-10, 10),
ylabel="CTDOXY Residual (umol/kg)",
f_out=f"{outdir}oxy-43_vs_stn{ext}",
)
ctd_plots.residual_vs_station(
btl_df["CTDOXY"],
btl_df["OXYGEN"],
btl_df["CTDPRS"],
btl_df["STNNBR"],
deep=True,
ylim=(-10, 10),
ylabel="CTDOXY Residual (umol/kg)",
f_out=f"{outdir}oxy-43_vs_stn_deep{ext}",
)
# RINKO oxygen plots
log.info("Generating oxygen (RINKO) residual plots")
ctd_plots.residual_vs_pressure(
btl_df["CTDRINKO"],
btl_df["OXYGEN"],
btl_df["CTDPRS"],
stn=btl_df["STNNBR"],
xlim=(-10, 10),
xlabel="CTDRINKO Residual (umol/kg)",
f_out=f"{outdir}oxy-rinko_vs_p{ext}",
)
ctd_plots.residual_vs_station(
btl_df["CTDRINKO"],
btl_df["OXYGEN"],
btl_df["CTDPRS"],
btl_df["STNNBR"],
ylim=(-10, 10),
ylabel="CTDRINKO Residual (umol/kg)",
f_out=f"{outdir}oxy-rinko_vs_stn{ext}",
)
ctd_plots.residual_vs_station(
btl_df["CTDRINKO"],
btl_df["OXYGEN"],
btl_df["CTDPRS"],
btl_df["STNNBR"],
deep=True,
ylim=(-10, 10),
ylabel="CTDRINKO Residual (umol/kg)",
f_out=f"{outdir}oxy-rinko_vs_stn_deep{ext}",
)
def pressure_offset():
data = pd.read_csv("data/logs/ondeck_pressure.csv")
print(f"Average deck pressure:\n{data.describe().loc[['min', 'max', 'mean']]}\n")
print(
f"Average offset:\n{(data['ondeck_end_p'] - data['ondeck_start_p']).describe()}\n"
)
def fit_coefficients():
"""Write code to build table for fit groups?"""
pass
def calculate_residuals():
log.info("Calculating T/C/O residuals\n")
low_grad_rows = (btl_df["CTDTMP1"] - btl_df["CTDTMP2"]).abs() < 0.002
deep_rows = btl_df["CTDPRS"] > 2000
T_flag2 = (btl_df["CTDTMP1_FLAG_W"] == 2) | (btl_df["CTDTMP2_FLAG_W"] == 2)
C_flag2 = (btl_df["CTDCOND1_FLAG_W"] == 2) | (btl_df["CTDCOND2_FLAG_W"] == 2)
S_flag2 = (btl_df["CTDSAL_FLAG_W"] == 2) | (btl_df["CTDSAL_FLAG_W"] == 2)
O_flag2 = btl_df["CTDOXY_FLAG_W"] == 2
R_flag2 = btl_df["CTDRINKO_FLAG_W"] == 2
def fmt(x):
return np.format_float_positional(x, precision=5)
# Temperature
low_grad = btl_df[low_grad_rows & T_flag2]
deep = btl_df[deep_rows & T_flag2]
print(f"REFT-T1 = {fmt((low_grad['REFTMP'] - low_grad['CTDTMP1']).std() * 2)}")
print(f"REFT-T2 = {fmt((low_grad['REFTMP'] - low_grad['CTDTMP2']).std() * 2)}")
print(f"T1-T2 = {fmt((low_grad['CTDTMP1'] - low_grad['CTDTMP2']).std() * 2)}")
print(f"REFT-T1 (deep) = {fmt((deep['REFTMP'] - deep['CTDTMP1']).std() * 2)}")
print(f"REFT-T2 (deep) = {fmt((deep['REFTMP'] - deep['CTDTMP2']).std() * 2)}")
print(f"T1-T2 (deep) = {fmt((deep['CTDTMP1'] - deep['CTDTMP2']).std() * 2)}")
print("")
# Conductivity
low_grad = btl_df[low_grad_rows & C_flag2]
deep = btl_df[deep_rows & C_flag2]
print(f"REFC-C1 = {fmt((low_grad['BTLCOND'] - low_grad['CTDCOND1']).std() * 2)}")
print(f"REFC-C2 = {fmt((low_grad['BTLCOND'] - low_grad['CTDCOND2']).std() * 2)}")
print(f"C1-C2 = {fmt((low_grad['CTDCOND1'] - low_grad['CTDCOND2']).std() * 2)}")
print(f"REFC-C1 (deep) = {fmt((deep['BTLCOND'] - deep['CTDCOND1']).std() * 2)}")
print(f"REFC-C2 (deep) = {fmt((deep['BTLCOND'] - deep['CTDCOND2']).std() * 2)}")
print(f"C1-C2 (deep) = {fmt((deep['CTDCOND1'] - deep['CTDCOND2']).std() * 2)}")
print("")
# Salinity
low_grad = btl_df[low_grad_rows & S_flag2]
deep = btl_df[deep_rows & S_flag2]
print(f"REFS-SAL = {fmt((low_grad['SALNTY'] - low_grad['CTDSAL']).std() * 2)}")
print(f"REFS-SAL (deep) = {fmt((deep['SALNTY'] - deep['CTDSAL']).std() * 2)}")
print("")
# SBE43
# low_grad = btl_df[low_grad_rows & O_flag2]
flag2 = btl_df[O_flag2]
deep = btl_df[deep_rows & O_flag2]
print(f"OXY-SBE43 = {fmt((flag2['OXYGEN'] - flag2['CTDOXY']).std() * 2)}")
print(f"OXY-SBE43 (deep) = {fmt((deep['OXYGEN'] - deep['CTDOXY']).std() * 2)}")
print("")
# RINKO
# low_grad = btl_df[low_grad_rows & R_flag2]
flag2 = btl_df[R_flag2]
deep = btl_df[deep_rows & R_flag2]
print(f"OXY-RINKO = {fmt((flag2['OXYGEN'] - flag2['CTDRINKO']).std() * 2)}")
print(f"OXY-RINKO (deep) = {fmt((deep['OXYGEN'] - deep['CTDRINKO']).std() * 2)}")
print("")
def cruise_report_residuals():
"""Do all the things for cruise report"""
plot_residuals()
pressure_offset()
fit_coefficients()
calculate_residuals()
# if __name__ == "__main__":
# make_cruise_report_plots()
|
<gh_stars>1-10
import * as NS from '../../namespace';
import { makeCommunicationActionCreators } from 'shared/helpers/redux';
export const { execute: verify, completed: verifySuccess, failed: verifyFail } =
makeCommunicationActionCreators<NS.IVerify, NS.IVerifySuccess, NS.IVerifyFail>(
'PROTECTOR:VERIFY', 'PROTECTOR:VERIFY_SUCCESS', 'PROTECTOR:VERIFY_FAIL',
);
|
package jadx.core.dex.nodes.utils;
import java.util.ArrayList;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import jadx.core.clsp.ClspClass;
import jadx.core.clsp.ClspMethod;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.MethodBridgeAttr;
import jadx.core.dex.attributes.nodes.MethodOverrideAttr;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.MethodInfo;
import jadx.core.dex.instructions.BaseInvokeNode;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.IMethodDetails;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.RootNode;
public class MethodUtils {
private final RootNode root;
public MethodUtils(RootNode rootNode) {
this.root = rootNode;
}
@Nullable
public IMethodDetails getMethodDetails(BaseInvokeNode invokeNode) {
IMethodDetails methodDetails = invokeNode.get(AType.METHOD_DETAILS);
if (methodDetails != null) {
return methodDetails;
}
return getMethodDetails(invokeNode.getCallMth());
}
@Nullable
public IMethodDetails getMethodDetails(MethodInfo callMth) {
MethodNode mthNode = root.deepResolveMethod(callMth);
if (mthNode != null) {
return mthNode;
}
return root.getClsp().getMethodDetails(callMth);
}
/**
* Search methods with same name and args count in class hierarchy starting from {@code startCls}
* Beware {@code startCls} can be different from {@code mthInfo.getDeclClass()}
*/
public boolean isMethodArgsOverloaded(ArgType startCls, MethodInfo mthInfo) {
return processMethodArgsOverloaded(startCls, mthInfo, null);
}
public List<IMethodDetails> collectOverloadedMethods(ArgType startCls, MethodInfo mthInfo) {
List<IMethodDetails> list = new ArrayList<>();
processMethodArgsOverloaded(startCls, mthInfo, list);
return list;
}
@Nullable
public ArgType getMethodGenericReturnType(BaseInvokeNode invokeNode) {
IMethodDetails methodDetails = getMethodDetails(invokeNode);
if (methodDetails != null) {
ArgType returnType = methodDetails.getReturnType();
if (returnType != null && returnType.containsGeneric()) {
return returnType;
}
}
return null;
}
private boolean processMethodArgsOverloaded(ArgType startCls, MethodInfo mthInfo, @Nullable List<IMethodDetails> collectedMths) {
if (startCls == null || !startCls.isObject()) {
return false;
}
boolean isMthConstructor = mthInfo.isConstructor() || mthInfo.isClassInit();
ClassNode classNode = root.resolveClass(startCls);
if (classNode != null) {
for (MethodNode mth : classNode.getMethods()) {
if (mthInfo.isOverloadedBy(mth.getMethodInfo())) {
if (collectedMths == null) {
return true;
}
collectedMths.add(mth);
}
}
if (!isMthConstructor) {
if (processMethodArgsOverloaded(classNode.getSuperClass(), mthInfo, collectedMths)) {
if (collectedMths == null) {
return true;
}
}
for (ArgType parentInterface : classNode.getInterfaces()) {
if (processMethodArgsOverloaded(parentInterface, mthInfo, collectedMths)) {
if (collectedMths == null) {
return true;
}
}
}
}
} else {
ClspClass clsDetails = root.getClsp().getClsDetails(startCls);
if (clsDetails == null) {
// class info not available
return false;
}
for (ClspMethod clspMth : clsDetails.getMethodsMap().values()) {
if (mthInfo.isOverloadedBy(clspMth.getMethodInfo())) {
if (collectedMths == null) {
return true;
}
collectedMths.add(clspMth);
}
}
if (!isMthConstructor) {
for (ArgType parent : clsDetails.getParents()) {
if (processMethodArgsOverloaded(parent, mthInfo, collectedMths)) {
if (collectedMths == null) {
return true;
}
}
}
}
}
return false;
}
@Nullable
public IMethodDetails getOverrideBaseMth(MethodNode mth) {
MethodOverrideAttr overrideAttr = mth.get(AType.METHOD_OVERRIDE);
if (overrideAttr == null) {
return null;
}
return overrideAttr.getBaseMth();
}
public ClassInfo getMethodOriginDeclClass(MethodNode mth) {
IMethodDetails baseMth = getOverrideBaseMth(mth);
if (baseMth != null) {
return baseMth.getMethodInfo().getDeclClass();
}
MethodBridgeAttr bridgeAttr = mth.get(AType.BRIDGED_BY);
if (bridgeAttr != null) {
return getMethodOriginDeclClass(bridgeAttr.getBridgeMth());
}
return mth.getMethodInfo().getDeclClass();
}
}
|
#!/bin/bash
set -e
docker build -t jupyterlab:1.0 ./docker/jupyterlab
|
from collections import defaultdict
def return_default():
return 0
def dd():
return defaultdict(return_default)
CHALLENGE_DAY = "7"
REAL = open(CHALLENGE_DAY + ".txt").read()
SAMPLE = open(CHALLENGE_DAY + ".sample2.txt").read()
SAMPLE_EXPECTED = 126
# SAMPLE_EXPECTED =
def parse_lines(raw):
# Groups.
# split = raw.split("\n\n")
# return list(map(lambda group: group.split("\n"), split))
split = raw.split("\n")
ret = {}
for l in split:
ls = l.split(" contain ")
name = ls[0].replace(" bags", "")
if ls[1] == "no other bags.":
ret[name] = None
continue
bags = ls[1].split(",")
here = {}
for bag in bags:
bag = bag.strip()
qty, n1, n2, _ = bag.split(" ")
nh = n1 + " " + n2
here[nh] = int(qty)
ret[name] = here
return ret
# return split
# return list(map(int, lines))
# return list(map(lambda l: l.strip(), split)) # beware leading / trailing WS
def contains_num(target, bags, at):
cbags = bags[at]
if cbags == None:
return 1
num = 1
for ck in cbags.keys():
cnum = cbags[ck]
crec = contains_num(target, bags, ck)
num += cnum * crec
return num
def solve(raw):
parsed = parse_lines(raw)
# Debug here to make sure parsing is good.
ret = 0
SHINY = "shiny gold"
return contains_num(SHINY, parsed, SHINY) - 1
sample = solve(SAMPLE)
if SAMPLE_EXPECTED is None:
print("*** SKIPPING SAMPLE! ***")
else:
assert sample == SAMPLE_EXPECTED
print("*** SAMPLE PASSED ***")
solved = solve(REAL)
print("SOLUTION: ", solved)
# assert solved
|
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<string> strings = {"apple", "desk", "third", "table"};
sort(strings.begin(), strings.end());
for (auto str : strings)
cout << str << " ";
return 0;
} |
<reponame>chrisprice/honesty-store-1<filename>aws/xray/node_modules/aws-xray-sdk-core/test/unit/sampling/sampling_rules.test.js
var assert = require('chai').assert;
var chai = require('chai');
var fs = require('fs');
var sinon = require('sinon');
var sinonChai = require('sinon-chai');
chai.should();
chai.use(sinonChai);
var SamplingRules = require('../../../lib/middleware/sampling/sampling_rules');
var Sampler = require('../../../lib/middleware/sampling/sampler');
var Utils = require('../../../lib/utils');
describe('SamplingRules', function() {
var sandbox, stubIsSampled;
beforeEach(function() {
sandbox = sinon.sandbox.create();
stubIsSampled = sandbox.stub(Sampler.prototype, 'isSampled').returns(true);
});
afterEach(function() {
sandbox.restore();
});
describe('#constructor', function() {
var sandbox;
beforeEach(function() {
sandbox = sinon.sandbox.create();
sandbox.stub(Sampler.prototype, 'init').returns();
});
afterEach(function() {
sandbox.restore();
});
describe('by default', function() {
it('should return a SamplingRules object loaded with the default JSON document', function() {
var samplingRules = new SamplingRules();
assert(samplingRules);
assert.isTrue(samplingRules.rules[0].default);
});
});
describe('by supplying a config file', function() {
var jsonDoc = {
rules: [
{
description: 'moop',
http_method: 'GET',
service_name: '*.foo.com',
url_path: '/signin/*',
fixed_target: 0,
rate: 0
},
{
description: '',
http_method: 'POST',
service_name: '*.moop.com',
url_path: '/login/*',
fixed_target: 10,
rate: 0.05
}
],
default: {
fixed_target: 10,
rate: 0.05
},
version: 1
};
beforeEach(function() {
sandbox = sinon.sandbox.create();
});
afterEach(function() {
sandbox.restore();
});
it('should parse the matchers rules', function() {
sandbox.stub(fs, 'readFileSync').returns();
sandbox.stub(JSON, 'parse').returns(jsonDoc);
var samplingRules = new SamplingRules('/path/here');
var rule0 = samplingRules.rules[0];
var rule1 = samplingRules.rules[1];
var rule2 = samplingRules.rules[2];
assert.equal(rule0.service_name, jsonDoc.rules[0].service_name);
assert.equal(rule0.http_method, jsonDoc.rules[0].http_method);
assert.equal(rule0.url_path, jsonDoc.rules[0].url_path);
assert.instanceOf(rule0.sampler, Sampler);
assert.equal(rule1.service_name, jsonDoc.rules[1].service_name);
assert.equal(rule1.http_method, jsonDoc.rules[1].http_method);
assert.equal(rule1.url_path, jsonDoc.rules[1].url_path);
assert.instanceOf(rule1.sampler, Sampler);
assert.isTrue(rule2.default);
assert.instanceOf(rule2.sampler, Sampler);
});
});
it('should accept a default fixed_target of 0 and a rate of 0', function() {
sandbox.stub(fs, 'readFileSync');
sandbox.stub(JSON, 'parse').returns({
default: {
fixed_target: 0,
rate: 0
},
version: 1
});
var samplingRules = new SamplingRules('/path/here');
assert.isTrue(samplingRules.rules[0].default);
});
it('should throw an error if the file is missing a "version" attribute', function() {
sandbox.stub(fs, 'readFileSync');
sandbox.stub(JSON, 'parse').returns({ rules: [] });
assert.throws(function () { new SamplingRules('/custom/path'); }, 'Missing "version" attribute.');
});
it('should throw an error if the file the version is not valid', function() {
sandbox.stub(fs, 'readFileSync');
sandbox.stub(JSON, 'parse').returns({ rules: [], version: 'moop' });
assert.throws(function () { new SamplingRules('/custom/path'); }, 'Unknown version "moop".');
});
it('should throw an error if the file is missing a "default" object', function() {
sandbox.stub(fs, 'readFileSync');
sandbox.stub(JSON, 'parse').returns({ rules: [], version: 1 });
assert.throws(function () { new SamplingRules('/custom/path'); },
'Expecting "default" object to be defined with attributes "fixed_target" and "rate".');
});
it('should throw an error if the "default" object contains an invalid attribute', function() {
sandbox.stub(fs, 'readFileSync');
sandbox.stub(JSON, 'parse').returns({ default: { fixed_target: 10, rate: 0.05, url_path: '/signin/*' }, version: 1});
assert.throws(function () { new SamplingRules('/custom/path'); },
'Invalid attributes for default: url_path. Valid attributes for default are "fixed_target" and "rate".');
});
it('should throw an error if the "default" object is missing required attributes', function() {
sandbox.stub(fs, 'readFileSync');
sandbox.stub(JSON, 'parse').returns({ default: { fixed_target: 10 }, version: 1});
assert.throws(function () { new SamplingRules('/custom/path'); }, 'Missing required attributes for default: rate.');
});
it('should throw an error if any rule contains invalid attributes', function() {
sandbox.stub(fs, 'readFileSync');
sandbox.stub(JSON, 'parse').returns({
rules: [{
service_name: 'www.worththewait.io',
http_method: 'PUT',
url_path: '/signin/*',
moop: 'moop',
fixed_target: 10,
rate: 0.05
}],
default: {
fixed_target: 10,
rate: 0.05
},
version: 1
});
assert.throws(function () { new SamplingRules(); }, 'has invalid attribute: moop.');
});
it('should throw an error if any rule is missing required attributes', function() {
sandbox.stub(fs, 'readFileSync');
sandbox.stub(JSON, 'parse').returns({
rules: [{
url_path: '/signin/*',
fixed_target: 10,
rate: 0.05
}],
default: {
fixed_target: 10,
rate: 0.05
},
version: 1
});
assert.throws(function () { new SamplingRules(); }, 'is missing required attributes: service_name,http_method.');
});
it('should throw an error if any rule attributes have an invalid value', function() {
sandbox.stub(fs, 'readFileSync');
sandbox.stub(JSON, 'parse').returns({
rules: [{
service_name: 'www.worththewait.io',
http_method: null,
url_path: '/signin/*',
fixed_target: 10,
rate: 0.05
}],
default: {
fixed_target: 10,
rate: 0.05
},
version: 1
});
assert.throws(function () { new SamplingRules(); }, 'attribute "http_method" has invalid value: null.');
});
});
describe('#shouldSample', function() {
var sandbox, fakeSampler;
beforeEach(function() {
sandbox = sinon.sandbox.create();
fakeSampler = new Sampler(10, 0.05);
});
afterEach(function() {
sandbox.restore();
});
it('should match the default rule and return true', function() {
var samplingRules = new SamplingRules();
samplingRules.rules = [{
default: true,
sampler: fakeSampler
}];
assert.isTrue(samplingRules.shouldSample('hello.moop.com', 'GET', '/home/moop/hello'));
stubIsSampled.should.have.been.calledOnce;
});
it('should match the customer rule by calling Utils.wildcardMatch on each attribute', function() {
var matchStub = sandbox.stub(Utils, 'wildcardMatch').returns(true);
var samplingRules = new SamplingRules();
samplingRules.rules = [{
http_method: 'POST',
service_name: '*.moop.com',
url_path: '/login/*',
sampler: fakeSampler
}];
samplingRules.shouldSample('hello.moop.com', 'POST', '/login/moop/hello');
stubIsSampled.should.have.been.calledOnce;
matchStub.should.have.been.calledThrice;
matchStub.should.have.been.calledWithExactly('/login/*', '/login/moop/hello');
matchStub.should.have.been.calledWithExactly('POST', 'POST');
matchStub.should.have.been.calledWithExactly('*.moop.com', 'hello.moop.com');
});
it('should fail to match the customer rule and not call isSampled', function() {
sandbox.stub(Utils, 'wildcardMatch').returns(false);
var samplingRules = new SamplingRules();
samplingRules.rules = [{
http_method: '.',
service_name: '.',
url_path: '.',
sampler: fakeSampler
}];
assert.isFalse(samplingRules.shouldSample('hello.moop.com', 'GET', '/login/moop/hello'));
stubIsSampled.should.not.have.been.called;
});
});
});
|
import Head from 'next/head';
import Page from 'components/layout/Page';
import withLang from 'components/hocs/withLang';
import withTranslate from 'components/hocs/withTranslate';
import Link from 'next/link';
import ContentGrid from 'components/blocks/ContentGrid';
import SearchBlock from 'components/blocks/SearchBlock';
//import dateSortDesc from 'utils/date_st';
import { makeAuthorsLinks } from 'components/blocks/ArticleHead';
import { makeAuthorsTitle } from 'utils/authors';
import { getContentList, findInOtherLanguage } from 'cms/content';
const textTranslations = {
pageName: {
en: 'Lectures',
ru: 'Лекции'
},
description: {
en: 'Lectures',
ru: 'Лекции'
},
keywords: {
en: ['Lectures'],
ru: ['Лекции']
},
readMore: {
en: 'Open',
ru: 'Открыть'
},
author: {
en: 'Lecturer',
ru: 'Лектор'
},
authorsPluralEnding: {
en: 's',
ru: 'ы'
}
};
const contentType = 'lectures';
function Lectures({ contentList, lang, otherLangLink, texts }) {
return (
<Page
title={texts['pageName']}
description={texts['description']}
keywords={texts['keywords']}
otherLangLink={otherLangLink}>
<Page.Header>
{texts['pageName']}
</Page.Header>
<SearchBlock lang={lang} type={contentType}>
<ContentGrid
content={contentList}
highlightFirst={false}
imageOnTop={true}
HeaderLink={linkProps => (
<Link href={linkProps.route}>
<a>{linkProps.children}</a>
</Link>
)}
Link={linkProps => (
<Link href={linkProps.route}>
<a>{texts['readMore']} →</a>
</Link>
)}
Footer={footerProps => (
<small>
{makeAuthorsTitle(footerProps.meta.authors, lang, textTranslations)}:
{makeAuthorsLinks(footerProps.meta.authors, lang, textTranslations)}
</small>
)}
/>
</SearchBlock>
</Page>
);
}
export async function getStaticProps(context) {
const contextParams = {
locale: context.locale,
contentType: 'lectures'
};
const otherLangLink = findInOtherLanguage(contextParams);
const contentList = await getContentList(contextParams);
return {
props: {
contentList,
otherLangLink
},
}
}
export default withLang(withTranslate(Lectures, textTranslations));
|
// pages/cart/cart.js
var postData = require("../../data/post-data.js");
Page({
data: {
cartListShow: true,
showModal: false,
postList: postData.postList
},
onLoad: function (options) {
//this.setData({
// postList: postData.postList
//});
if (this.data.postList.length < 1) {
this.setData({
showModal: true
});
}
},
plus: function (e) {
var that = this;
var index = e.currentTarget.dataset.index;
var num = that.data.postList[index].num;
if (num > 1) {
num--;
} else {
wx.showModal({
title: '',
content: '是否删除此菜品?',
success: function (res) {
if (res.confirm) {
carts.splice(index, 1);
that.setData({
postList: carts
});
if (that.data.postList.length < 1) {
that.setData({
cartListShow: false,
showModal: true
});
}
} else if (res.cancel) {
return;
}
}
})
}
var carts = that.data.postList;
carts[index].num = num;
that.setData({
postList: carts
});
//this.data.postList[index].num;
},
add: function (e) {
var index = e.currentTarget.dataset.index;
var num = this.data.postList[index].num;
num++;
var carts = this.data.postList;
carts[index].num = num;
this.setData({
postList: carts
});
},
delThisFood: function (e) {
var that = this;
var index = e.currentTarget.dataset.index;
var carts = that.data.postList;
wx.showModal({
title: '',
content: '是否删除此菜品?',
success: function (res) {
if (res.confirm) {
carts.splice(index, 1);
that.setData({
postList: carts
});
if (that.data.postList.length < 1) {
that.setData({
cartListShow: false,
showModal: true
});
}
} else if (res.cancel) {
return;
}
}
})
}
}) |
<gh_stars>0
"""Initialize the Gruvbox package."""
from pkg_resources import declare_namespace
declare_namespace(".")
from .ptgruvbox import PtGruvboxStyle
from .gruvbox import GruvboxStyle
|
from flask import Flask, request, Response, jsonify
import boto3
import botocore
import base64
import logging
from log_filter import HealthcheckFilter
app = Flask(__name__)
healthcheck_filter = HealthcheckFilter()
log = logging.getLogger('werkzeug')
log.addFilter(healthcheck_filter)
log.setLevel(logging.INFO)
logging.basicConfig(level=logging.INFO)
client = boto3.client('rekognition')
@app.route('/healthcheck', methods=["GET"])
def healthcheck():
'''
Checks that the app is properly running.
'''
return 'shazongress'
@app.route('/recognize', methods=["POST"])
def recongize():
'''
Receives POST request from Twilio. Sends data from request to Amazon Rekognize and receives the API's analysis.
Returns the resulting analysis as JSON.
'''
# Reads image data from incoming request
r = request
data = r.files['file'].read()
# Sends image data to Amazon Rekognize for analysis. Returns JSON response of results.
try:
results = client.recognize_celebrities(Image={'Bytes': data})
except botocore.exceptions.ClientError as e:
results = {"Rekognition Client Error": str(e)}
logging.info(results)
return jsonify(results)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8888, debug=True) |
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
# [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
# autoload -U add-zsh-hook
# load-nvmrc() {
# local node_version="$(nvm version)"
# local nvmrc_path="$(nvm_find_nvmrc)"
# if [ -n "$nvmrc_path" ]; then
# local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")
# if [ "$nvmrc_node_version" = "N/A" ]; then
# nvm install
# elif [ "$nvmrc_node_version" != "$node_version" ]; then
# nvm use
# fi
# elif [ "$node_version" != "$(nvm version default)" ]; then
# echo "Reverting to nvm default version"
# nvm use default
# fi
# }
# add-zsh-hook chpwd load-nvmrc
# load-nvmrc |
// 此配置为系统默认设置,需修改的设置项,在src/config/config.js中添加修改项即可。也可直接在此文件中修改。
module.exports = {
lang: 'CN', //语言,可选 CN(简体)、HK(繁体)、US(英语),也可扩展其它语言
theme: { //主题
color: '#1890ff', //主题色
mode: 'dark', //主题模式 可选 dark、 light 和 night
success: '#52c41a', //成功色
warning: '#faad14', //警告色
error: '#f5222d', //错误色
},
layout: 'side', //导航布局,可选 side 和 head,分别为侧边导航和顶部导航
fixedHeader: false, //固定头部状态栏,true:固定,false:不固定
fixedSideBar: true, //固定侧边栏,true:固定,false:不固定
weekMode: false, //色弱模式,true:开启,false:不开启
multiPage: false, //多页签模式,true:开启,false:不开启
hideSetting: false, //隐藏设置抽屉,true:隐藏,false:不隐藏
systemName: 'Vue Antd Admin', //系统名称
copyright: '2018 ICZER 工作室出品', //copyright
asyncRoutes: false, //异步加载路由,true:开启,false:不开启
animate: { //动画设置
disabled: true, //禁用动画,true:禁用,false:启用
name: 'bounce', //动画效果,支持的动画效果可参考 ./animate.config.js
direction: 'left' //动画方向,切换页面时动画的方向,参考 ./animate.config.js
},
footerLinks: [ //页面底部链接,{link: '链接地址', name: '名称/显示文字', icon: '图标,支持 ant design vue 图标库'}
{ link: '/', name: 'Pro首页' },
{ link: '/', name: 'Ant Design' }
],
} |
<filename>project/database/database.sql
CREATE TABLE `user` (
`userID` int NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`fullname` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`status` tinyint DEFAULT NULL,
`isAdmin` tinyint DEFAULT NULL,
PRIMARY KEY (`userID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
CREATE TABLE `activitytype` (
`idActivityType` int NOT NULL AUTO_INCREMENT,
`Name` varchar(255) NOT NULL,
`Description` varchar(255) NOT NULL,
`Points` int NOT NULL,
PRIMARY KEY (`idActivityType`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
CREATE TABLE `activity` (
`idActivity` int NOT NULL AUTO_INCREMENT,
`idActivityType` int NOT NULL,
`Name` varchar(255) NOT NULL,
`Points` int NOT NULL,
`Description` varchar(255) NOT NULL,
PRIMARY KEY (`idActivity`),
KEY `fkActivityType_idx` (`idActivityType`),
CONSTRAINT `fkActivityType` FOREIGN KEY (`idActivityType`) REFERENCES `activitytype` (`idActivityType`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `score` (
`idScore` int NOT NULL AUTO_INCREMENT,
`idActivity` int NOT NULL,
`userID` int NOT NULL,
`date` datetime NOT NULL,
`points` int NOT NULL,
PRIMARY KEY (`idScore`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `progra3db`.`email` (
`idemail` INT NOT NULL AUTO_INCREMENT,
`emailName` VARCHAR(255) NOT NULL,
`Subject` VARCHAR(255) NOT NULL,
`Message` VARCHAR(4096) NOT NULL,
`template` VARCHAR(255) NOT NULL,
PRIMARY KEY (`idemail`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO User (username, fullname, email,password,status, isAdmin) VALUES ('Felipe','<NAME>','<EMAIL>','asdf',true, true);
INSERT INTO User (username, fullname, email,password,status, isAdmin) VALUES ('Alberto','<NAME>','<EMAIL>','asdf',true, false);
INSERT INTO User (username, fullname, email,password,status, isAdmin) VALUES ('Pablo','<NAME>','<EMAIL>','asdf',true, false);
INSERT INTO User (username, fullname, email,password,status, isAdmin) VALUES ('Melany','<NAME>','<EMAIL>','asdf',true, true);
INSERT INTO `progra3db`.`email`
(`emailName`,
`Subject`,
`Message`,
`Template`)
VALUES
('Welcome Email', '', '', 'WelcomeUser.html');
INSERT INTO `progra3db`.`email`
(`emailName`,
`Subject`,
`Message`,
`Template`)
VALUES
('New Activity Created', '', '', 'NewActivity.html');
INSERT INTO `progra3db`.`email`
(`emailName`,
`Subject`,
`Message`,
`Template`)
VALUES
('Scoreboard Updates', '', '', 'ScoreBoard.html');
|
#!/bin/bash
################################################
# Copyright (c) 2015-18 zibernetics, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
################################################
SCRIPT=$(readlink -f $0)
SCRIPTPATH=$(dirname ${SCRIPT})
DIRNAME=$(basename ${SCRIPTPATH})
SAVE_DIR=$(pwd)
cd ${SCRIPTPATH}
if [[ $(id -un) != root ]]; then
echo "This script must be run as root."
exit 1
fi
localHostName=$(hostname)
localDirMgrDN=
localDirMgrPasswd=
: ${instanceRoot=}
localAdminPasswd=
localSecretsFile=
USAGE=" Usage: `basename $0` -D Directory Manager DN -Y localSecretsFile [ -I instanceRoot ]"
while getopts hD:Y:I: OPT; do
case "$OPT" in
h)
echo $USAGE
cd ${SAVE_DIR}
exit 0
;;
D)
localDirMgrDN="$OPTARG"
;;
Y)
localSecretsFile="$OPTARG"
;;
I)
instanceRoot="$OPTARG"
;;
\?)
# getopts issues an error message
echo $USAGE >&2
cd ${SAVE_DIR}
exit 1
;;
esac
done
if [ -z "${localDirMgrDN}" ]; then
echo "Must pass a valid admin bind dn"
echo $USAGE >&2
cd ${SAVE_DIR}
exit 1
fi
if [ -z "${localSecretsFile}" ] || [ ! -f "${localSecretsFile}" ]; then
echo "Must pass a valid secrets file"
echo $USAGE >&2
cd ${SAVE_DIR}
exit 1
fi
source "${localSecretsFile}"
localDirMgrPasswd="${OPENDJ_DS_DIRMGRPASSWD}"
localAdminPasswd="${OPENDJ_ADM_PASSWD}"
if [ -z "${localDirMgrPasswd}" ]; then
echo "Must pass a valid directory manager password or password file"
echo $USAGE >&2
cd ${SAVE_DIR}
exit 1
fi
if [ -z "${localAdminPasswd}" ]; then
echo "Must pass a valid admin password or password file"
echo $USAGE >&2
cd ${SAVE_DIR}
exit 1
fi
################################################
#
# Functions
#
################################################
##################################################
#
# Main program
#
##################################################
OPENDJ_HOME_DIR=
declare -A OPENDJ_BASE_DNS=()
echo "#### loading ziNet - $SCRIPT"
source /etc/default/zinet 2>/dev/null
if [ $? -ne 0 ]; then
echo "Error reading zinet default runtime"
exit 1
fi
# if [[ $(id -un) != "${ziAdmin}" ]]; then
# echo "This script must be run as ${ziAdmin}."
# exit 1
# fi
for f in ${ziNetEtcDir}/*.functions; do source $f; done 2> /dev/null
for f in ${ziNetEtcDir}/*.properties; do source $f; done 2> /dev/null
opendjCfgDir=${ziNetEtcDir}/opendj
if [ ! -z ${instanceRoot} ]; then
opendjCfgDir="${opendjCfgDir}/${instanceRoot}"
fi
for f in ${opendjCfgDir}/*.functions; do source $f; done 2> /dev/null
for f in ${opendjCfgDir}/opendj-*-default.properties; do source $f; done 2> /dev/null
for f in ${opendjCfgDir}/opendj-*-override.properties; do source $f; done 2> /dev/null
instanceOpts=
[ ! -z "${instanceRoot}" ] && instanceOpts="-I ${instanceRoot}"
fileList="$(ls ${opendjCfgDir}/config/*.sh 2>/dev/null)"
for f in ${fileList}; do
echo "#### Setting up custom prerequisite script: $f"
source $f
done
echo
echo "#### Creating backends"
sudo -u "${ziAdmin}" ${OPENDJ_TOOLS_DIR}/bin/opendj-setup-backend.sh -n ${localHostName} ${instanceOpts}
echo
echo "#### Creating backend indexes"
sudo -u "${ziAdmin}" ${OPENDJ_TOOLS_DIR}/bin/opendj-setup-backend-index.sh -n ${localHostName} ${instanceOpts}
echo
echo "#### Creating Plugins"
sudo -u "${ziAdmin}" ${OPENDJ_TOOLS_DIR}/bin/opendj-setup-plugin.sh -n ${localHostName} ${instanceOpts}
echo
echo "#### Creating Log Publishers"
sudo -u "${ziAdmin}" ${OPENDJ_TOOLS_DIR}/bin/opendj-setup-log-publisher.sh -n ${localHostName} ${instanceOpts}
echo
if [ ! -z "${OPENDJ_GLOBAL_SMTP_SVR}" ]; then
echo "#### Enabling global SMTP server: ${OPENDJ_GLOBAL_SMTP_SVR}"
${OPENDJ_HOME_DIR}/bin/dsconfig set-global-configuration-prop \
--port ${OPENDJ_ADMIN_PORT} \
--hostname ${localHostName} \
--bindDN "${localDirMgrDN}" \
--bindPassword ${localDirMgrPasswd} \
--set smtp-server:${OPENDJ_GLOBAL_SMTP_SVR} \
-f -X -n
fi
if [ -z "${OPENDJ_LDAP_PORT}" ]; then
echo "#### Removing unused protocol handler: LDAP"
${OPENDJ_HOME_DIR}/bin/dsconfig delete-connection-handler \
--port ${OPENDJ_ADMIN_PORT} \
--hostname ${localHostName} \
--bindDN "${localDirMgrDN}" \
--bindPassword ${localDirMgrPasswd} \
--handler-name "LDAP Connection Handler" \
-f -X -n
fi
if [ -z "${OPENDJ_LDAPS_PORT}" ]; then
echo "#### Removing unused protocol handler: LDAPS"
${OPENDJ_HOME_DIR}/bin/dsconfig delete-connection-handler \
--port ${OPENDJ_ADMIN_PORT} \
--hostname ${localHostName} \
--bindDN "${localDirMgrDN}" \
--bindPassword ${localDirMgrPasswd} \
--handler-name "LDAPS Connection Handler" \
-f -X -n
fi
if [ -z "${OPENDJ_JMX_PORT}" ]; then
echo "#### Removing unused protocol handler: JMX"
${OPENDJ_HOME_DIR}/bin/dsconfig delete-connection-handler \
--port ${OPENDJ_ADMIN_PORT} \
--hostname ${localHostName} \
--bindDN "${localDirMgrDN}" \
--bindPassword ${localDirMgrPasswd} \
--handler-name "JMX Connection Handler" \
-f -X -n
fi
echo "#### Restarting OpenDJ after reconfiguration"
${OPENDJ_TOOLS_DIR}/bin/opendj-ops-control.sh restartWait ${instanceRoot}
if [ ! -z "${OPENDJ_PSEARCH_GRP}" ]; then
echo "#### Adding global aci for persistent search"
${OPENDJ_HOME_DIR}/bin/dsconfig set-access-control-handler-prop \
--port ${OPENDJ_ADMIN_PORT} \
--hostname ${localHostName} \
--bindDN "${localDirMgrDN}" \
--bindPassword ${localDirMgrPasswd} \
-X -n \
--add global-aci:"(targetcontrol=\"2.16.840.1.113730.3.4.3\") (version 3.0; acl \"Allow persistent search\"; allow (search, read) (groupdn = \"ldap:///${OPENDJ_PSEARCH_GRP}\");)"
fi
if [ ! -z "${OPENDJ_PSEARCH_USER}" ]; then
echo "#### Adding global aci for persistent search"
${OPENDJ_HOME_DIR}/bin/dsconfig set-access-control-handler-prop \
--port ${OPENDJ_ADMIN_PORT} \
--hostname ${localHostName} \
--bindDN "${localDirMgrDN}" \
--bindPassword ${localDirMgrPasswd} \
-X -n \
--add global-aci:"(targetcontrol=\"2.16.840.1.113730.3.4.3\") (version 3.0; acl \"Allow persistent search\"; allow (search, read) (userdn = \"ldap:///${OPENDJ_PSEARCH_USER}\");)"
fi
if [ ! -z "${OPENDJ_MOD_SCHEMA_GRP}" ]; then
echo "#### Adding global aci for modify schema"
${OPENDJ_HOME_DIR}/bin/dsconfig set-access-control-handler-prop \
--port ${OPENDJ_ADMIN_PORT} \
--hostname ${localHostName} \
--bindDN "${localDirMgrDN}" \
--bindPassword ${localDirMgrPasswd} \
-X -n \
--add global-aci:"(target = \"ldap:///cn=schema\")(targetattr = \"attributeTypes || objectClasses\")(version 3.0;acl \"Modify schema\"; allow (search, read, write) (groupdn = \"ldap:///${OPENDJ_MOD_SCHEMA_GRP}\");)"
fi
if [ ! -z "${OPENDJ_MOD_SCHEMA_USER}" ]; then
echo "#### Adding global aci for modify schema"
${OPENDJ_HOME_DIR}/bin/dsconfig set-access-control-handler-prop \
--port ${OPENDJ_ADMIN_PORT} \
--hostname ${localHostName} \
--bindDN "${localDirMgrDN}" \
--bindPassword ${localDirMgrPasswd} \
-X -n \
--add global-aci:"(target = \"ldap:///cn=schema\")(targetattr = \"attributeTypes || objectClasses\")(version 3.0;acl \"Modify schema\"; allow (search, read, write) (userdn = \"ldap:///${OPENDJ_MOD_SCHEMA_USER}\");)"
fi
# echo "#### Creating admin user"
# ${OPENDJ_HOME_DIR}/bin/dsframework create-admin-user \
# --port ${OPENDJ_ADMIN_PORT} \
# --hostname ${localHostName} \
# --bindDN "${localDirMgrDN}" \
# --bindPassword ${localDirMgrPasswd} \
# --userID admin \
# --set password:${localAdminPasswd} \
# -X
echo "#### Listing Backends"
if [ -f "${OPENDJ_HOME_DIR}/bin/list-backends" ]; then
sudo -u "${ziAdmin}" ${OPENDJ_HOME_DIR}/bin/list-backends
else
sudo -u "${ziAdmin}" ${OPENDJ_HOME_DIR}/bin/dsconfig list-backends \
--port ${OPENDJ_ADMIN_PORT} \
--hostname ${localHostName} \
--bindDN "${localDirMgrDN}" \
--bindPassword ${localDirMgrPasswd} \
--trustAll \
--no-prompt
fi
echo "#### Finished setting up OpenDJ"
cd ${SAVE_DIR}
|
<filename>static/microchat.js
// jshint asi:true
function μchatInit(initEvent) {
let updateInterval
let lastMsg
function toast(message, timeout=5000) {
let p = document.createElement("p")
p.innerText = message
document.querySelector("#chattoast").appendChild(p)
setTimeout(e => { p.remove() }, timeout)
}
function input(event) {
event.preventDefault()
let form = event.target
let inp = form.elements.text
let body = new FormData(form)
fetch("say", {
method: "POST",
body: body,
})
.then(resp => {
if (resp.ok) {
// Yay it was okay, reset input
inp.value = ""
} else {
toast("ERROR: DOES NOT COMPUTE")
console.log(resp)
}
})
.catch(err => {
toast("ERROR: DOES NOT COMPUTE")
console.log(err)
})
window.localStorage["who"] = form.elements.who.value
}
function updateLog(log) {
let lastLogMsg = log[log.length - 1]
if (
lastMsg &&
(lastLogMsg.When == lastMsg.When) &&
(lastLogMsg.Who == lastMsg.Who) &&
(lastLogMsg.Text == lastMsg.Text)
) {
return
}
lastMsg = lastLogMsg
let chatlog = document.querySelector("#chatlog")
while (chatlog.firstChild) {
chatlog.firstChild.remove()
}
for (let ll of log) {
let line = chatlog.appendChild(document.createElement("div"))
line.classList.add("line")
let when = line.appendChild(document.createElement("span"))
when.classList.add("when")
when.innerText = (new Date(ll.When * 1000)).toISOString()
let who = line.appendChild(document.createElement("span"))
who.classList.add("who")
who.innerText = ll.Who
let text = line.appendChild(document.createElement("span"))
text.classList.add("text")
text.innerText = ll.Text
}
chatlog.lastChild.scrollIntoView()
// trigger a fetch of chat log so the user gets some feedback
update()
}
function update(event) {
fetch("read")
.then(resp => {
if (resp.ok) {
resp.json()
.then(updateLog)
}
})
.catch(err => {
toast("Server error: " + err)
})
}
for (let f of document.forms) {
let who = window.localStorage["who"]
f.addEventListener("submit", input)
if (who) {
f.elements.who.value = who
}
}
updateInterval = setInterval(update, 3000)
update()
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", μchatInit)
} else {
μchatInit()
}
|
<gh_stars>1-10
# encoding: utf-8
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: apex_buffer.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
import apex_datatype_pb2 as apex__datatype__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='apex_buffer.proto',
package='',
syntax='proto3',
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n\x11\x61pex_buffer.proto\x1a\x13\x61pex_datatype.proto2\xa2\x01\n\x06\x42uffer\x12J\n\x10SendTrajectories\x12\x1a.apex_datatype.ListNDarray\x1a\x16.apex_datatype.Nothing\"\x00(\x01\x12L\n\x0fSendExperiences\x12\x1d.apex_datatype.ExpsAndTDerror\x1a\x16.apex_datatype.Nothing\"\x00(\x01\x62\x06proto3'
,
dependencies=[apex__datatype__pb2.DESCRIPTOR,])
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_BUFFER = _descriptor.ServiceDescriptor(
name='Buffer',
full_name='Buffer',
file=DESCRIPTOR,
index=0,
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_start=43,
serialized_end=205,
methods=[
_descriptor.MethodDescriptor(
name='SendTrajectories',
full_name='Buffer.SendTrajectories',
index=0,
containing_service=None,
input_type=apex__datatype__pb2._LISTNDARRAY,
output_type=apex__datatype__pb2._NOTHING,
serialized_options=None,
create_key=_descriptor._internal_create_key,
),
_descriptor.MethodDescriptor(
name='SendExperiences',
full_name='Buffer.SendExperiences',
index=1,
containing_service=None,
input_type=apex__datatype__pb2._EXPSANDTDERROR,
output_type=apex__datatype__pb2._NOTHING,
serialized_options=None,
create_key=_descriptor._internal_create_key,
),
])
_sym_db.RegisterServiceDescriptor(_BUFFER)
DESCRIPTOR.services_by_name['Buffer'] = _BUFFER
# @@protoc_insertion_point(module_scope)
|
destdir="2-ca-geojson"
rm -rf $destdir
mkdir $destdir
src="1-ca-shapefiles"
for i in $src/*.shp; do
dest=`echo $i | sed s/shp$/json/ | sed s/$src/$destdir/`
echo $dest $i
ogr2ogr -f "GeoJSON" $dest $i
done
|
<reponame>labd/react-abode<gh_stars>10-100
import * as fc from 'fast-check';
import {
getCleanPropName,
getAbodeElements,
getRegisteredComponents,
unPopulatedElements,
setUnpopulatedElements,
getElementProps,
setAttributes,
renderAbode,
register,
unRegisterAllComponents,
components,
populate,
delay,
} from '../src/abode';
// @ts-ignore
import TestComponent from './TestComponent';
import TestComponentProps, { util } from './TestComponentProps';
import 'mutationobserver-shim';
global.MutationObserver = window.MutationObserver;
describe('helper functions', () => {
beforeEach(() => {
document.getElementsByTagName('html')[0].innerHTML = '';
unRegisterAllComponents();
});
it('getCleanPropName', () => {
expect(getCleanPropName('data-prop-some-random-prop')).toEqual(
'someRandomProp'
);
});
it('getAbodeElements', () => {
const abodeElement = document.createElement('div');
abodeElement.setAttribute('data-component', 'TestComponent');
document.body.appendChild(abodeElement);
expect(getAbodeElements()).toHaveLength(0);
register('TestComponent', () => TestComponent);
expect(getAbodeElements()).toHaveLength(1);
});
it('setUnpopulatedElements', () => {
const abodeElement = document.createElement('div');
abodeElement.setAttribute('data-component', 'TestComponent');
document.body.appendChild(abodeElement);
setUnpopulatedElements();
expect(unPopulatedElements).toHaveLength(0);
register('TestComponent', () => TestComponent);
setUnpopulatedElements();
expect(unPopulatedElements).toHaveLength(1);
});
it('getElementProps', () => {
const abodeElement = document.createElement('div');
abodeElement.setAttribute('data-component', 'TestComponent');
abodeElement.setAttribute('data-prop-test-prop', 'testPropValue');
abodeElement.setAttribute('data-prop-number-prop', '12345');
abodeElement.setAttribute('data-prop-null-prop', 'null');
abodeElement.setAttribute('data-prop-true-prop', 'true');
abodeElement.setAttribute('data-prop-leading-zeros', '0012');
abodeElement.setAttribute('data-prop-leading-zero', '012');
abodeElement.setAttribute('data-prop-sku-one', 'B123456');
abodeElement.setAttribute('data-prop-sku-two', 'AW-ARZA18-C0LM-78');
abodeElement.setAttribute('data-prop-sku-three', 'TO-8370-228-770-6.0');
abodeElement.setAttribute('data-prop-float', '10.46');
abodeElement.setAttribute('data-prop-empty-prop', '');
abodeElement.setAttribute(
'data-prop-json-prop',
'{"id": 12345, "product": "keyboard", "variant": {"color": "blue"}}'
);
const props = getElementProps(abodeElement);
expect(props).toEqual({
testProp: 'testPropValue',
numberProp: 12345,
nullProp: null,
trueProp: true,
leadingZeros: '0012',
leadingZero: '012',
skuOne: 'B123456',
skuTwo: 'AW-ARZA18-C0LM-78',
skuThree: 'TO-8370-228-770-6.0',
float: 10.46,
emptyProp: '',
jsonProp: { id: 12345, product: 'keyboard', variant: { color: 'blue' } },
});
});
it('getElementProps parses JSON', () => {
fc.assert(
fc.property(fc.jsonObject({ maxDepth: 10 }), data => {
const abodeElement = document.createElement('div');
abodeElement.setAttribute('data-prop-test-prop', JSON.stringify(data));
const props = getElementProps(abodeElement);
expect(props.testProp).toEqual(data);
})
);
});
it('getElementProps does not parse strings with leading zeros followed by other digits', () => {
const strWithLeadingZeros = fc
.tuple(fc.integer(1, 10), fc.integer())
.map(t => {
const [numberOfZeros, integer] = t;
return '0'.repeat(numberOfZeros) + integer.toString();
});
fc.assert(
fc.property(strWithLeadingZeros, data => {
const abodeElement = document.createElement('div');
abodeElement.setAttribute('data-prop-test-prop', data);
const props = getElementProps(abodeElement);
expect(props.testProp).toEqual(data);
})
);
});
it('setAttributes', () => {
const abodeElement = document.createElement('div');
setAttributes(abodeElement, { classname: 'test-class-name' });
expect(abodeElement.getAttribute('classname')).toBe('test-class-name');
});
it('renderAbode without component name set', async () => {
const abodeElement = document.createElement('div');
abodeElement.setAttribute('data-component', '');
let err;
try {
await renderAbode(abodeElement);
} catch (error) {
err = error;
}
expect(err.message).toEqual(
'not all react-abode elements have a value for data-component'
);
});
it('renderAbode without component registered', async () => {
const abodeElement = document.createElement('div');
abodeElement.setAttribute('data-component', 'TestComponent');
let err;
try {
await renderAbode(abodeElement);
} catch (error) {
err = error;
}
expect(err.message).toEqual('no component registered for TestComponent');
});
});
describe('exported functions', () => {
beforeEach(() => {
document.getElementsByTagName('html')[0].innerHTML = '';
unRegisterAllComponents();
});
it('register', async () => {
register('TestComponent', () => import('./TestComponent'));
expect(Object.keys(components)).toEqual(['TestComponent']);
expect(Object.values(components).length).toEqual(1);
let promise = Object.values(components)[0].module;
expect(typeof promise.then).toEqual('function');
let module = await promise;
expect(typeof module).toEqual('object');
expect(Object.keys(module)).toEqual(['default']);
register('TestComponent2', () => TestComponent);
expect(Object.keys(components)).toEqual([
'TestComponent',
'TestComponent2',
]);
expect(Object.values(components).length).toEqual(2);
promise = Object.values(components)[1].module;
expect(typeof promise.then).toEqual('function');
module = await promise;
expect(typeof module).toEqual('function');
});
it('populate', async () => {
const abodeElement = document.createElement('div');
abodeElement.setAttribute('data-component', 'TestComponent');
const abodeSecondElement = document.createElement('div');
abodeSecondElement.setAttribute('data-component', 'TestComponent2');
document.body.appendChild(abodeElement);
document.body.appendChild(abodeSecondElement);
expect(document.body.innerHTML).toEqual(
`<div data-component="TestComponent"></div><div data-component="TestComponent2"></div>`
);
register('TestComponent', () => import('./TestComponent'));
register('TestComponent2', () => TestComponent);
await populate();
await delay(20);
expect(document.body.innerHTML).toEqual(
`<div data-component="TestComponent" react-abode-populated="true"><div>testing 1 2 3 </div></div>` +
`<div data-component="TestComponent2" react-abode-populated="true"><div>testing 1 2 3 </div></div>`
);
});
it('getRegisteredComponents', () => {
register('TestComponent', () => import('./TestComponent'));
register('TestComponent2', () => TestComponent);
const registeredComponents = getRegisteredComponents();
expect(Object.keys(registeredComponents).length).toEqual(2);
});
it('uses custom prop parsers', async () => {
const spy = jest.spyOn(util, 'getProps');
const abodeElement = document.createElement('div');
abodeElement.setAttribute('data-component', 'TestComponentProps');
abodeElement.setAttribute('data-prop-number', '1');
abodeElement.setAttribute('data-prop-boolean', 'true');
abodeElement.setAttribute('data-prop-number-as-string', '123');
abodeElement.setAttribute('data-prop-float', '1.01');
document.body.appendChild(abodeElement);
register('TestComponentProps', () => TestComponentProps, {
propParsers: {
number: (prop: string) => Number(prop),
boolean: (prop: string) => Boolean(prop),
numberAsString: (prop: string) => prop,
float: (prop: string) => parseFloat(prop),
},
});
await populate();
await delay(20);
expect(document.body.innerHTML).toEqual(
`<div data-component="TestComponentProps" data-prop-number="1" data-prop-boolean="true" data-prop-number-as-string="123" data-prop-float="1.01" react-abode-populated="true"><div>1 2 3</div></div>`
);
expect(spy).toHaveBeenCalled();
expect(spy).toHaveBeenCalledWith({
number: 1,
boolean: true,
numberAsString: '123',
float: 1.01,
});
});
it('uses JSON.parse as a custom prop parser', async () => {
const spy = jest.spyOn(util, 'getProps');
const abodeElement = document.createElement('div');
abodeElement.setAttribute('data-component', 'TestComponentProps');
document.body.appendChild(abodeElement);
fc.assert(
fc.property(fc.anything(), data => {
abodeElement.setAttribute('data-prop-anything', JSON.stringify(data));
register('TestComponentProps', () => TestComponentProps, {
propParsers: {
anything: (prop: string) => JSON.parse(prop),
},
});
populate()
.then(() => delay(20))
.then(() => {
expect(spy).toHaveBeenCalledWith({ anything: data });
});
})
);
});
it.skip('getScriptProps', () => {});
it.skip('getActiveComponents', () => {});
it.skip('setComponentSelector', () => {});
it.skip('register', () => {});
});
|
<reponame>lnemsick-simp/pupmod-simp-nfs<filename>spec/classes/base/config_spec.rb
require 'spec_helper'
# Testing private nfs::base::config class via nfs class
describe 'nfs' do
describe 'private nfs::base::config' do
on_supported_os.each do |os, os_facts|
context "on #{os}" do
let(:facts) {
# to workaround service provider issues related to masking haveged
# when tests are run on GitLab runners which are docker containers
os_facts.merge( { :haveged__rngd_enabled => false } )
}
context 'with default nfs parameters' do
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('nfs::base::config') }
it { is_expected.to create_concat('/etc/nfs.conf').with( {
:owner => 'root',
:group => 'root',
:mode => '0644'
} ) }
it { is_expected.to_not create_concat__fragment('nfs_conf_general') }
it { is_expected.to_not create_concat__fragment('nfs_conf_gssd') }
it { is_expected.to_not create_concat__fragment('nfs_conf_lockd') }
it { is_expected.to_not create_concat__fragment('nfs_conf_sm_notify') }
it { is_expected.to_not create_concat__fragment('nfs_conf_statd') }
if os_facts[:os][:release][:major].to_i < 8
it { is_expected.to create_concat('/etc/sysconfig/nfs').with( {
:owner => 'root',
:group => 'root',
:mode => '0644'
} ) }
it { is_expected.to_not create_concat__fragment('nfs_gss_use_proxy') }
it { is_expected.to_not create_concat__fragment('nfs_GSSDARGS') }
it { is_expected.to_not create_concat__fragment('nfs_SMNOTIFYARGS') }
it { is_expected.to_not create_concat__fragment('nfs_STATDARG') }
else
it { is_expected.to create_file('/etc/sysconfig/nfs').with_ensure('absent') }
end
it { is_expected.to_not create_systemd__dropin_file('simp_unit.conf') }
it { is_expected.to create_file('/etc/modprobe.d/sunrpc.conf').with( {
:owner => 'root',
:group => 'root',
:mode => '0640',
:content => <<~EOM
# This file is managed by Puppet (simp-nfs module). Changes will be overwritten
# at the next puppet run.
#
options sunrpc tcp_slot_table_entries=128 udp_slot_table_entries=128
EOM
} ) }
it { is_expected.to_not create_class('nfs::idmapd::config') }
it { is_expected.to_not create_file('/etc/modprobe.d/lockd.conf') }
end
context "when nfs::custom_nfs_conf_opts has 'general' key" do
let(:params) {{
:custom_nfs_conf_opts => {
'general' => {
'pipefs-directory' => '/some/dir'
}
}
}}
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('nfs::base::config') }
it { is_expected.to create_concat__fragment('nfs_conf_general').with( {
:target => '/etc/nfs.conf',
:content => <<~EOM
[general]
pipefs-directory = /some/dir
EOM
} ) }
end
context 'when nfs::secure_nfs=true' do
context 'when nfs::gssd_use_gss_proxy=false' do
let(:params) {{
:secure_nfs => true,
:gssd_use_gss_proxy => false
}}
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('nfs::base::config') }
it { is_expected.to create_concat__fragment('nfs_conf_gssd').with( {
:target => '/etc/nfs.conf',
:content => <<~EOM
[gssd]
avoid-dns = true
limit-to-legacy-enctypes = false
use-gss-proxy = false
EOM
} ) }
if os_facts[:os][:release][:major].to_i < 8
it { is_expected.to_not create_concat__fragment('nfs_gss_use_proxy') }
it { is_expected.to_not create_concat__fragment('nfs_GSSDARGS') }
end
it { is_expected.to_not create_systemd__dropin_file('simp_unit.conf') }
end
context 'when nfs::gssd_use_gss_proxy=true' do
let(:params) {{
:secure_nfs => true
# nfs::gssd_use_gss_proxy default is true
}}
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('nfs::base::config') }
it { is_expected.to create_concat__fragment('nfs_conf_gssd').with( {
:target => '/etc/nfs.conf',
:content => <<~EOM
[gssd]
avoid-dns = true
limit-to-legacy-enctypes = false
use-gss-proxy = true
EOM
} ) }
if os_facts[:os][:release][:major].to_i < 8
it { is_expected.to create_concat__fragment('nfs_gss_use_proxy').with( {
:target => '/etc/sysconfig/nfs',
:content => "GSS_USE_PROXY=yes"
} ) }
it { is_expected.to_not create_concat__fragment('nfs_GSSDARGS') }
end
it { is_expected.to create_systemd__dropin_file('simp_unit.conf').with( {
:unit => 'gssproxy.service',
:content => <<~EOM
# This file is managed by Puppet (simp-nfs module). Changes will be overwritten
# at the next puppet run.
[Unit]
PartOf=nfs-utils.service
EOM
} ) }
end
context "when nfs::custom_nfs_conf_opts has 'gssd' key" do
let(:params) {{
:secure_nfs => true,
:custom_nfs_conf_opts => {
'gssd' => {
'use-memcache' => true
}
}
}}
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('nfs::base::config') }
it { is_expected.to create_concat__fragment('nfs_conf_gssd').with( {
:target => '/etc/nfs.conf',
:content => <<~EOM
[gssd]
avoid-dns = true
limit-to-legacy-enctypes = false
use-gss-proxy = true
use-memcache = true
EOM
} ) }
end
if os_facts[:os][:release][:major].to_i < 8
context "when nfs::custom_daemon_args has 'GSSDARGS' key" do
let(:params) {{
:secure_nfs => true,
:custom_daemon_args => { 'GSSDARGS' => '-v' }
}}
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('nfs::base::config') }
it { is_expected.to create_concat__fragment('nfs_GSSDARGS').with( {
:target => '/etc/sysconfig/nfs',
:content => 'GSSDARGS="-v"'
} ) }
end
end
end
context 'when nfs::nfsv3=true' do
context 'with default NFSv3-related nfs parameters' do
let(:params) {{ :nfsv3 => true }}
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('nfs::base::config') }
it { is_expected.to create_concat__fragment('nfs_conf_lockd').with( {
:target => '/etc/nfs.conf',
:content => <<~EOM
[lockd]
port = 32803
udp-port = 32769
EOM
} ) }
it { is_expected.to create_concat__fragment('nfs_conf_sm_notify').with( {
:target => '/etc/nfs.conf',
:content => <<~EOM
[sm-notify]
outgoing-port = 2021
EOM
} ) }
it { is_expected.to create_concat__fragment('nfs_conf_statd').with( {
:target => '/etc/nfs.conf',
:content => <<~EOM
[statd]
outgoing-port = 2020
port = 662
EOM
} ) }
it { is_expected.to create_file('/etc/modprobe.d/lockd.conf').with( {
:owner => 'root',
:group => 'root',
:mode => '0640',
:content => <<~EOM
# This file is managed by Puppet (simp-nfs module). Changes will be overwritten
# at the next puppet run.
#
# Set the TCP port that the NFS lock manager should use.
# port must be a valid TCP port value (1-65535).
options lockd nlm_tcpport=32803
# Set the UDP port that the NFS lock manager should use.
# port must be a valid UDP port value (1-65535).
options lockd nlm_udpport=32769
EOM
} ) }
end
context "when nfs::custom_nfs_conf_opts has 'lockd' key" do
let(:params) {{
:nfsv3 => true,
:custom_nfs_conf_opts => {
'lockd' => {
# this isn't a real option yet, but currently only
# two options available are being set
'debug' => 'all'
}
}
}}
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('nfs::base::config') }
it { is_expected.to create_concat__fragment('nfs_conf_lockd').with( {
:target => '/etc/nfs.conf',
:content => <<~EOM
[lockd]
debug = all
port = 32803
udp-port = 32769
EOM
} ) }
end
context "when nfs::custom_nfs_conf_opts has 'sm-notify' key" do
let(:params) {{
:nfsv3 => true,
:custom_nfs_conf_opts => {
'sm-notify' => {
'retry-time' => 10
}
}
}}
it { is_expected.to create_concat__fragment('nfs_conf_sm_notify').with( {
:target => '/etc/nfs.conf',
:content => <<~EOM
[sm-notify]
outgoing-port = 2021
retry-time = 10
EOM
} ) }
end
context "when nfs::custom_nfs_conf_opts has 'statd' key" do
let(:params) {{
:nfsv3 => true,
:custom_nfs_conf_opts => {
'statd' => {
'state-directory-path' => '/some/path'
}
}
}}
it { is_expected.to create_concat__fragment('nfs_conf_statd').with( {
:target => '/etc/nfs.conf',
:content => <<~EOM
[statd]
outgoing-port = 2020
port = 662
state-directory-path = /some/path
EOM
} ) }
end
if os_facts[:os][:release][:major].to_i < 8
context "when nfs::custom_daemon_args has 'SMNOTIFYARGS' key" do
let(:params) {{
:nfsv3 => true,
:custom_daemon_args => { 'SMNOTIFYARGS' => '-f' }
}}
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('nfs::base::config') }
it { is_expected.to create_concat__fragment('nfs_SMNOTIFYARGS').with( {
:target => '/etc/sysconfig/nfs',
:content => 'SMNOTIFYARGS="-f"'
} ) }
end
context "when nfs::custom_daemon_args has 'STATDARG' key" do
let(:params) {{
:nfsv3 => true,
:custom_daemon_args => { 'STATDARG' => '--no-syslog' }
}}
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('nfs::base::config') }
it { is_expected.to create_concat__fragment('nfs_STATDARG').with( {
:target => '/etc/sysconfig/nfs',
:content => 'STATDARG="--no-syslog"'
} ) }
end
end
end
context 'with nfs::idmapd=true' do
let(:params) {{ :idmapd => true }}
it { is_expected.to create_class('nfs::idmapd::config') }
end
end
end
end
end
|
package org.softuni.residentevil.domain.entities;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.softuni.residentevil.domain.validation.annotations.composite.user.ValidUserAuthorities;
import org.softuni.residentevil.domain.validation.annotations.composite.user.ValidUserEmail;
import org.softuni.residentevil.domain.validation.annotations.composite.user.ValidUserEncryptedPassword;
import org.softuni.residentevil.domain.validation.annotations.composite.user.ValidUserUsername;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Getter
@NoArgsConstructor
@Entity
@Table(name = "users")
@NamedQuery(name = "User.findUserEager",
query = "SELECT u FROM User u LEFT JOIN FETCH u.authorities AS a WHERE u.username = :username")
public class User extends BaseUuidEntity implements UserDetails {
private static final long serialVersionUID = 1L;
@ValidUserUsername
@Column(unique = true, nullable = false, updatable = false, length = ValidUserUsername.MAX_LENGTH)
private String username;
@ValidUserEncryptedPassword
@Column(nullable = false, length = ValidUserEncryptedPassword.MAX_LENGTH)
private String password;
@ValidUserEmail
@Column(unique = true, nullable = false, length = ValidUserEmail.MAX_LENGTH)
private String email;
@ValidUserAuthorities
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "users_roles",
joinColumns = {@JoinColumn(name = "user_id")},
inverseJoinColumns = {@JoinColumn(name = "role_id")})
private Set<Role> authorities = new HashSet<>();
private boolean isAccountNonLocked;
private boolean isAccountNonExpired;
private boolean isCredentialsNonExpired;
private boolean isEnabled;
}
|
import random
def get_user_choice():
while True:
user_choice = input("Enter your choice (rock, paper, or scissors): ").lower()
if user_choice in ["rock", "paper", "scissors"]:
return user_choice
else:
print("Invalid choice. Please enter rock, paper, or scissors.")
def get_computer_choice():
return random.choice(["rock", "paper", "scissors"])
def determine_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return "It's a tie! Both chose " + user_choice + "."
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "scissors" and computer_choice == "paper") or \
(user_choice == "paper" and computer_choice == "rock"):
return "You win! " + user_choice.capitalize() + " beats " + computer_choice + "."
else:
return "Computer wins! " + computer_choice.capitalize() + " beats " + user_choice + "."
def play_game():
print("Welcome to Rock-Paper-Scissors!")
while True:
user_choice = get_user_choice()
computer_choice = get_computer_choice()
print("Computer's choice:", computer_choice)
print(determine_winner(user_choice, computer_choice))
play_again = input("Do you want to play again? (yes/no): ").lower()
if play_again != "yes":
print("Thanks for playing Rock-Paper-Scissors!")
break
play_game() |
#!/bin/bash -e
chmod u+x scripts/*
cp -R scripts/* /usr/local/bin
|
<filename>platform-shop/src/main/java/com/platform/entity/example/AftersalesExample.java
package com.platform.entity.example;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 实体
* 表名 nideshop_aftersales
*
* @author xuyang
* @email <EMAIL>
* @date 2018-11-21 09:28:36
*/
public class AftersalesExample extends AbstractExample {
private static final long serialVersionUID = 1L;
@Override
public Criteria or() {
return (Criteria)super.or();
}
@Override
public Criteria createCriteria() {
return (Criteria)super.createCriteria();
}
@Override
protected Criteria createCriteriaInternal() {
return new Criteria();
}
public class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
public Criteria andProductIdIsNull() {
addCriterion("product_id is null");
return (Criteria) this;
}
public Criteria andProductIdIsNotNull() {
addCriterion("product_id is not null");
return (Criteria) this;
}
public Criteria andProductIdEqualTo(Integer value) {
addCriterion("product_id =", value, "productId");
return (Criteria) this;
}
public Criteria andProductIdNotEqualTo(Integer value) {
addCriterion("product_id <>", value, "productId");
return (Criteria) this;
}
public Criteria andProductIdGreaterThan(Integer value) {
addCriterion("product_id >", value, "productId");
return (Criteria) this;
}
public Criteria andProductIdGreaterThanOrEqualTo(Integer value) {
addCriterion("product_id >=", value, "productId");
return (Criteria) this;
}
public Criteria andProductIdLessThan(Integer value) {
addCriterion("product_id <", value, "productId");
return (Criteria) this;
}
public Criteria andProductIdLessThanOrEqualTo(Integer value) {
addCriterion("product_id <=", value, "productId");
return (Criteria) this;
}
public Criteria andProductIdIn(List<Integer> values) {
addCriterion("product_id in", values, "productId");
return (Criteria) this;
}
public Criteria andproductIdNotIn(List<Integer> values) {
addCriterion("product_id not in", values, "productId");
return (Criteria) this;
}
public Criteria andProductIdBetween(Integer value1, Integer value2) {
addCriterion("product_id between", value1, value2, "productId");
return (Criteria) this;
}
public Criteria andProductIdNotBetween(Integer value1, Integer value2) {
addCriterion("product_id not between", value1, value2, "productId");
return (Criteria) this;
}
public Criteria andBuyTimeIsNull() {
addCriterion("buy_time is null");
return (Criteria) this;
}
public Criteria andBuyTimeIsNotNull() {
addCriterion("buy_time is not null");
return (Criteria) this;
}
public Criteria andBuyTimeEqualTo(Date value) {
addCriterion("buy_time =", value, "buyTime");
return (Criteria) this;
}
public Criteria andBuyTimeNotEqualTo(Date value) {
addCriterion("buy_time <>", value, "buyTime");
return (Criteria) this;
}
public Criteria andBuyTimeGreaterThan(Date value) {
addCriterion("buy_time >", value, "buyTime");
return (Criteria) this;
}
public Criteria andBuyTimeGreaterThanOrEqualTo(Date value) {
addCriterion("buy_time >=", value, "buyTime");
return (Criteria) this;
}
public Criteria andBuyTimeLessThan(Date value) {
addCriterion("buy_time <", value, "buyTime");
return (Criteria) this;
}
public Criteria andBuyTimeLessThanOrEqualTo(Date value) {
addCriterion("buy_time <=", value, "buyTime");
return (Criteria) this;
}
public Criteria andBuyTimeIn(List<Date> values) {
addCriterion("buy_time in", values, "buyTime");
return (Criteria) this;
}
public Criteria andbuyTimeNotIn(List<Date> values) {
addCriterion("buy_time not in", values, "buyTime");
return (Criteria) this;
}
public Criteria andBuyTimeBetween(Date value1, Date value2) {
addCriterion("buy_time between", value1, value2, "buyTime");
return (Criteria) this;
}
public Criteria andBuyTimeNotBetween(Date value1, Date value2) {
addCriterion("buy_time not between", value1, value2, "buyTime");
return (Criteria) this;
}
public Criteria andGoodsSpecifitionIdsIsNull() {
addCriterion("goods_specifition_ids is null");
return (Criteria) this;
}
public Criteria andGoodsSpecifitionIdsIsNotNull() {
addCriterion("goods_specifition_ids is not null");
return (Criteria) this;
}
public Criteria andGoodsSpecifitionIdsEqualTo(String value) {
addCriterion("goods_specifition_ids =", value, "goodsSpecifitionIds");
return (Criteria) this;
}
public Criteria andGoodsSpecifitionIdsNotEqualTo(String value) {
addCriterion("goods_specifition_ids <>", value, "goodsSpecifitionIds");
return (Criteria) this;
}
public Criteria andGoodsSpecifitionIdsGreaterThan(String value) {
addCriterion("goods_specifition_ids >", value, "goodsSpecifitionIds");
return (Criteria) this;
}
public Criteria andGoodsSpecifitionIdsGreaterThanOrEqualTo(String value) {
addCriterion("goods_specifition_ids >=", value, "goodsSpecifitionIds");
return (Criteria) this;
}
public Criteria andGoodsSpecifitionIdsLessThan(String value) {
addCriterion("goods_specifition_ids <", value, "goodsSpecifitionIds");
return (Criteria) this;
}
public Criteria andGoodsSpecifitionIdsLessThanOrEqualTo(String value) {
addCriterion("goods_specifition_ids <=", value, "goodsSpecifitionIds");
return (Criteria) this;
}
public Criteria andGoodsSpecifitionIdsLike(String value) {
addCriterion("goods_specifition_ids like", value, "goodsSpecifitionIds");
return (Criteria) this;
}
public Criteria andGoodsSpecifitionIdsNotLike(String value) {
addCriterion("goods_specifition_ids not like", value, "goodsSpecifitionIds");
return (Criteria) this;
}
public Criteria andGoodsSpecifitionIdsIn(List<String> values) {
addCriterion("goods_specifition_ids in", values, "goodsSpecifitionIds");
return (Criteria) this;
}
public Criteria andgoodsSpecifitionIdsNotIn(List<String> values) {
addCriterion("goods_specifition_ids not in", values, "goodsSpecifitionIds");
return (Criteria) this;
}
public Criteria andGoodsSpecifitionIdsBetween(String value1, String value2) {
addCriterion("goods_specifition_ids between", value1, value2, "goodsSpecifitionIds");
return (Criteria) this;
}
public Criteria andGoodsSpecifitionIdsNotBetween(String value1, String value2) {
addCriterion("goods_specifition_ids not between", value1, value2, "goodsSpecifitionIds");
return (Criteria) this;
}
public Criteria andGoodsIdIsNull() {
addCriterion("goods_id is null");
return (Criteria) this;
}
public Criteria andGoodsIdIsNotNull() {
addCriterion("goods_id is not null");
return (Criteria) this;
}
public Criteria andGoodsIdEqualTo(Integer value) {
addCriterion("goods_id =", value, "goodsId");
return (Criteria) this;
}
public Criteria andGoodsIdNotEqualTo(Integer value) {
addCriterion("goods_id <>", value, "goodsId");
return (Criteria) this;
}
public Criteria andGoodsIdGreaterThan(Integer value) {
addCriterion("goods_id >", value, "goodsId");
return (Criteria) this;
}
public Criteria andGoodsIdGreaterThanOrEqualTo(Integer value) {
addCriterion("goods_id >=", value, "goodsId");
return (Criteria) this;
}
public Criteria andGoodsIdLessThan(Integer value) {
addCriterion("goods_id <", value, "goodsId");
return (Criteria) this;
}
public Criteria andGoodsIdLessThanOrEqualTo(Integer value) {
addCriterion("goods_id <=", value, "goodsId");
return (Criteria) this;
}
public Criteria andGoodsIdIn(List<Integer> values) {
addCriterion("goods_id in", values, "goodsId");
return (Criteria) this;
}
public Criteria andgoodsIdNotIn(List<Integer> values) {
addCriterion("goods_id not in", values, "goodsId");
return (Criteria) this;
}
public Criteria andGoodsIdBetween(Integer value1, Integer value2) {
addCriterion("goods_id between", value1, value2, "goodsId");
return (Criteria) this;
}
public Criteria andGoodsIdNotBetween(Integer value1, Integer value2) {
addCriterion("goods_id not between", value1, value2, "goodsId");
return (Criteria) this;
}
public Criteria andOrderIdIsNull() {
addCriterion("order_id is null");
return (Criteria) this;
}
public Criteria andOrderIdIsNotNull() {
addCriterion("order_id is not null");
return (Criteria) this;
}
public Criteria andOrderIdEqualTo(Integer value) {
addCriterion("order_id =", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdNotEqualTo(Integer value) {
addCriterion("order_id <>", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdGreaterThan(Integer value) {
addCriterion("order_id >", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdGreaterThanOrEqualTo(Integer value) {
addCriterion("order_id >=", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdLessThan(Integer value) {
addCriterion("order_id <", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdLessThanOrEqualTo(Integer value) {
addCriterion("order_id <=", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdIn(List<Integer> values) {
addCriterion("order_id in", values, "orderId");
return (Criteria) this;
}
public Criteria andorderIdNotIn(List<Integer> values) {
addCriterion("order_id not in", values, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdBetween(Integer value1, Integer value2) {
addCriterion("order_id between", value1, value2, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdNotBetween(Integer value1, Integer value2) {
addCriterion("order_id not between", value1, value2, "orderId");
return (Criteria) this;
}
public Criteria andProductSnIsNull() {
addCriterion("product_sn is null");
return (Criteria) this;
}
public Criteria andProductSnIsNotNull() {
addCriterion("product_sn is not null");
return (Criteria) this;
}
public Criteria andProductSnEqualTo(String value) {
addCriterion("product_sn =", value, "productSn");
return (Criteria) this;
}
public Criteria andProductSnNotEqualTo(String value) {
addCriterion("product_sn <>", value, "productSn");
return (Criteria) this;
}
public Criteria andProductSnGreaterThan(String value) {
addCriterion("product_sn >", value, "productSn");
return (Criteria) this;
}
public Criteria andProductSnGreaterThanOrEqualTo(String value) {
addCriterion("product_sn >=", value, "productSn");
return (Criteria) this;
}
public Criteria andProductSnLessThan(String value) {
addCriterion("product_sn <", value, "productSn");
return (Criteria) this;
}
public Criteria andProductSnLessThanOrEqualTo(String value) {
addCriterion("product_sn <=", value, "productSn");
return (Criteria) this;
}
public Criteria andProductSnLike(String value) {
addCriterion("product_sn like", value, "productSn");
return (Criteria) this;
}
public Criteria andProductSnNotLike(String value) {
addCriterion("product_sn not like", value, "productSn");
return (Criteria) this;
}
public Criteria andProductSnIn(List<String> values) {
addCriterion("product_sn in", values, "productSn");
return (Criteria) this;
}
public Criteria andproductSnNotIn(List<String> values) {
addCriterion("product_sn not in", values, "productSn");
return (Criteria) this;
}
public Criteria andProductSnBetween(String value1, String value2) {
addCriterion("product_sn between", value1, value2, "productSn");
return (Criteria) this;
}
public Criteria andProductSnNotBetween(String value1, String value2) {
addCriterion("product_sn not between", value1, value2, "productSn");
return (Criteria) this;
}
public Criteria andOrderSnIsNull() {
addCriterion("order_sn is null");
return (Criteria) this;
}
public Criteria andOrderSnIsNotNull() {
addCriterion("order_sn is not null");
return (Criteria) this;
}
public Criteria andOrderSnEqualTo(String value) {
addCriterion("order_sn =", value, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnNotEqualTo(String value) {
addCriterion("order_sn <>", value, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnGreaterThan(String value) {
addCriterion("order_sn >", value, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnGreaterThanOrEqualTo(String value) {
addCriterion("order_sn >=", value, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnLessThan(String value) {
addCriterion("order_sn <", value, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnLessThanOrEqualTo(String value) {
addCriterion("order_sn <=", value, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnLike(String value) {
addCriterion("order_sn like", value, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnNotLike(String value) {
addCriterion("order_sn not like", value, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnIn(List<String> values) {
addCriterion("order_sn in", values, "orderSn");
return (Criteria) this;
}
public Criteria andorderSnNotIn(List<String> values) {
addCriterion("order_sn not in", values, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnBetween(String value1, String value2) {
addCriterion("order_sn between", value1, value2, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnNotBetween(String value1, String value2) {
addCriterion("order_sn not between", value1, value2, "orderSn");
return (Criteria) this;
}
public Criteria andRepairEndTimeIsNull() {
addCriterion("repair_end_time is null");
return (Criteria) this;
}
public Criteria andRepairEndTimeIsNotNull() {
addCriterion("repair_end_time is not null");
return (Criteria) this;
}
public Criteria andRepairEndTimeEqualTo(Date value) {
addCriterion("repair_end_time =", value, "repairEndTime");
return (Criteria) this;
}
public Criteria andRepairEndTimeNotEqualTo(Date value) {
addCriterion("repair_end_time <>", value, "repairEndTime");
return (Criteria) this;
}
public Criteria andRepairEndTimeGreaterThan(Date value) {
addCriterion("repair_end_time >", value, "repairEndTime");
return (Criteria) this;
}
public Criteria andRepairEndTimeGreaterThanOrEqualTo(Date value) {
addCriterion("repair_end_time >=", value, "repairEndTime");
return (Criteria) this;
}
public Criteria andRepairEndTimeLessThan(Date value) {
addCriterion("repair_end_time <", value, "repairEndTime");
return (Criteria) this;
}
public Criteria andRepairEndTimeLessThanOrEqualTo(Date value) {
addCriterion("repair_end_time <=", value, "repairEndTime");
return (Criteria) this;
}
public Criteria andRepairEndTimeIn(List<Date> values) {
addCriterion("repair_end_time in", values, "repairEndTime");
return (Criteria) this;
}
public Criteria andrepairEndTimeNotIn(List<Date> values) {
addCriterion("repair_end_time not in", values, "repairEndTime");
return (Criteria) this;
}
public Criteria andRepairEndTimeBetween(Date value1, Date value2) {
addCriterion("repair_end_time between", value1, value2, "repairEndTime");
return (Criteria) this;
}
public Criteria andRepairEndTimeNotBetween(Date value1, Date value2) {
addCriterion("repair_end_time not between", value1, value2, "repairEndTime");
return (Criteria) this;
}
}
}
|
def filter_greater_than(arr, num):
return [x for x in arr if x > num]
filter_greater_than(arr, num) # returns [5, 6] |
<reponame>GunnarEriksson/space-invaders
/**
* The beams handler in the game.
*
* Creates, removes and handles all beams in the game.
*/
/*global Audio */
/*global Beam */
/*global GroundExplosion */
/*global Vector */
/**
* The beams constructor.
*
* Sets the beams specifications.
*
* @param {Object} cannon - Contains cannon.
* @param {Object} aliens - Contains all aliens.
* @param {Object} cities - the object containing the cities.
*/
function Beams(cannons, aliens, cities) {
this.cannons = cannons;
this.aliens = aliens;
this.cities = cities;
this.beams = [];
this.groundExplosions = [];
this.playAlienMissileSound = 0;
this.alienMissileSound = [];
for (var i = 0; i < 10; i++) {
this.alienMissileSound[i] = new Audio("sound/alien_missile.wav");
this.alienMissileSound[i].volume = 0.4;
}
this.playExplosionSound = 0;
this.groundExplosionsSound = [];
for (var j = 0; j < 10; j++) {
this.groundExplosionsSound[j] = new Audio("sound/ground_explosion.wav");
this.groundExplosionsSound[j].volume = 0.5;
}
}
/**
* The prototype of the beams describing the characteristics of the beams.
*
* @type {Object}
*/
Beams.prototype = {
start: function() {
this.beams = [];
this.groundExplosions = [];
this.playAlienMissileSound = 0;
this.playExplosionSound = 0;
},
/**
* Draws all beams.
*
* Draws all beams that is stored in an array.
*
* @param {Object} ct - The canvas context.
*
* @return {void}
*/
draw: function(ct) {
for (var i = 0; i < this.beams.length; i++) {
this.beams[i].draw(ct);
}
for (var j = 0; j < this.groundExplosions.length; j++) {
this.groundExplosions[j].draw(ct);
}
},
/**
* Fires a beam by creating a beam and store the beam in the array
* of beams. The beams are fired with an delay and it is a randomly choosen
* alien that fires the beam. Only aliens without an another alien below
* could fire a beam.
*
* @param {Objecy} alien - the alien object.
* @return {void}
*/
fire: function(alien) {
var beamPosX = alien.position.x + (alien.alienWidth / 2);
var beamPosY = alien.position.y + alien.alienHeight;
this.beams.push(new Beam(new Vector(beamPosX, beamPosY), this.cannons, this.aliens, this.cities));
this.playAlienMissileSound = (this.playAlienMissileSound + 1) % 10;
if (this.alienMissileSound[this.playAlienMissileSound].currentTime > 0) {
this.alienMissileSound[this.playAlienMissileSound].pause();
this.alienMissileSound[this.playAlienMissileSound].currentTime = 0;
}
this.alienMissileSound[this.playAlienMissileSound].play();
},
/**
* Updates all beams and removes a beam from the array if the beam
* should be removed when hitting the cannon or the city.
*
* @param {number} td - Time difference offset
*
* @return {void}
*/
update: function(td) {
for (var i = this.beams.length -1; i >= 0; i--) {
this.beams[i].update(td);
if (this.beams[i].shouldBeRemoved) {
if (!this.beams[i].cannonHit) {
this.groundExplosions.push(new GroundExplosion(new Vector(this.beams[i].position.x, this.beams[i].position.y + 3)));
this.playExplosionSound = (this.playExplosionSound + 1) % 10;
if (this.groundExplosionsSound[this.playExplosionSound].currentTime > 0) {
this.groundExplosionsSound[this.playExplosionSound].pause();
this.groundExplosionsSound[this.playExplosionSound].currentTime = 0;
}
this.groundExplosionsSound[this.playExplosionSound].play();
}
this.beams.splice(i, 1);
}
}
for (var j = this.groundExplosions.length -1; j >= 0; j--) {
this.groundExplosions[j].update();
if (this.groundExplosions[j].timer === 0) {
this.groundExplosions.splice(j, 1);
}
}
},
};
|
d = {'a':1, 'b':2, 'c':3}
# Using the clear() method
d.clear()
print(d) # Prints an empty dictionary |
#/usr/bin/env bash
# Licensed to Diennea S.r.l. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Diennea S.r.l. 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.
DATE=$(date '+%Y-%m-%d-%H:%M:%S')
VAR=$5
HERE=$(dirname $0)
HERE=$(realpath $HERE)
YCSB_PATH=$1
MYSQL_PATH=$(realpath $3)
MYSQL_PROPERTIES=$2
WORKLOAD=$@
I=5
NARG=0
WORK=
REPORT="Benchmark-"
L=0
LOG="work_files_mysql-$DATE/"
FILE_TEMP="target/$LOG"
FINAL="target/"
FINAL_REPORT="target/report_files_mysql-$DATE/"
JDBC_PATH=$4
MYSQL="MYSQL_"
FORMAT=".log"
mkdir $FINAL
mkdir $FILE_TEMP
mkdir $FINAL_REPORT
argv=("$@");
NARG=$#
while [ $L -lt $VAR ]; do
while [ $I -lt $NARG ]; do
WORK=${argv[$I]}
./full-ycsb_mysql.sh $YCSB_PATH $MYSQL_PROPERTIES $MYSQL_PATH $JDBC_PATH $WORK > $FILE_TEMP$WORK.txt
./parse_report.sh $WORK.txt $WORK$I.txt $WORK $VAR $FILE_TEMP $FINAL_REPORT $MYSQL_PATH
let I=I+1
done
I=5
let L=L+1
done
cat $FINAL_REPORT* > $FINAL$MYSQL$REPORT$DATE$FORMAT
rm -rf ".txt"
|
<filename>src/interfaces/IDragAndDrop.ts
export interface IDragElement {
zoneId: string | null;
data: any | null;
type: string;
}
export interface IDropElement {
zones: string[] | null;
data: any | null;
}
export interface IDragAndDrop {
dragNode: IDragElement;
dropNode: IDropElement;
type: string;
}
|
<filename>leetcode/832/832.py
class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
return [reversed([item ^ 1 for item in line]) for line in A]
|
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
# Load sentiment dictionary
sid = SentimentIntensityAnalyzer()
# Analyze sentiment
def sentiment_analyzer(text):
scores = sid.polarity_scores(text)
polarity = scores['compound']
if polarity > 0:
return "positive"
elif polarity < 0:
return "negative"
else:
return "neutral"
# Print sentiment
print(sentiment_analyzer("I love coding!")) |
<filename>raw/EOD/UAT.sql
-- Verify if Debug is active for any user
SELECT * FROM cstb_debug_users xa where xa.debug = 'Y'
SELECT * FROM STTM_BRANCH WHERE BRANCH_CODE NOT IN
( select BRANCH_CODE from sttb_brn_eodm where RUN_DATE='&DATE' ) order by BRANCH_CODE
--- Branches which are NOT YET completed with EODM ---
SELECT * FROM STTM_BRANCH WHERE BRANCH_CODE NOT IN ( select BRANCH_CODE from sttb_brn_eodm where RUN_DATE='&DATE' ) order by BRANCH_CODE
select * from eivw_pending_items XA
SELECT * FROM FBTB_TILL_MASTER WHERE BALANCED_IND<>'Y' ORDer by branch_code
select * from smtb_current_users order by HOME_BRANCH for update
select * from sttb_record_log where auth_stat = 'U'
SELECT * FROM cstb_clearing_master q where q.auth_stat = 'U'
(select rn from eivw_pending_items XA) for update
UPDATE Actb_Daily_Log SET DELEETwhere trn_ref_no in
(select rn from eivw_pending_items XA)
and auth_stat = 'U'
---------------------------------------------------------------------------------------------------------------------------
-- Branches EOD Stage and verification of batches execution
SELECT * FROM AETB_EOC_BRANCHES WHERE EOC_STATUS<>'C' ORDER BY BRANCH_CODe --FOR UPDATE NOWAIT;
-- Current batches running and their status/Etat des batches en cour par branche en execution
SELECT * FROM AETB_EOC_PROGRAMS WHERE EOC_BATCH_STATUS NOT IN ('C','N') ORDER BY BRANCH_CODE;--for update;
--- Batches pending execution by branches/Etat des batches restant en execution par branche
SELECT branch_code,count(*) FROM AETB_EOC_PROGRAMS WHERE EOC_BATCH_STATUS ='N' group by branch_code ORDER BY BRANCH_CODE;--cndbatch
-- Branches Status & Date
SELECT A.BRANCH_CODE,A.TODAY, DECODE(B.End_Of_Input,'N','Txn Input','T','End of Input','F','End of Fin Input','E','EOD Mark','B','BOD',B.End_Of_Input) Status FROM STTM_DATES A, STTM_BRANCH B WHERE A.BRANCH_CODE = B.BRANCH_CODE ORDER BY TODAY, STATUS, A.BRANCH_CODE;
SELECT * FROM CSTB_PARAM
---- SWITCH ON DEBUG
--1 run this first
UPDATE CSTB_PARAM SET PARAM_VAL='Y' WHERE PARAM_NAME='REAL_DEBUG'
--2 run this second
UPDATE CSTB_DEBUG_USERS SET DEBUG='Y' WHERE USER_ID='&User_ID'
--3 run if number of updated rows is 0 on script 2
INSERT INTO CSTB_DEBUG_USERS (SELECT MODULE_ID,'Y','&User_ID' FROM SMTB_MODULES )
-- Verify if Debug is active for any user
SELECT * FROM cstb_debug_users xa where xa.debug = 'Y'
-- SWITCH OFF DEBUG check this every times before start the EOD ---
UPDATE CSTB_DEBUG_USERS SET DEBUG='N' WHERE USER_ID='&User_ID'
UPDATE CSTB_DEBUG_USERS SET DEBUG='N' WHERE debug='Y'
UPDATE CSTB_PARAM SET PARAM_VAL='N' WHERE PARAM_NAME='REAL_DEBUG'
--- User in system
select * from smtb_current_users order by HOME_BRANCH for update
|
<filename>spring-boot/src/main/java/com/aqzscn/www/global/config/validation/ValidationGroup3.java
package com.aqzscn.www.global.config.validation;
/**
* Created by Godbobo on 2019/5/14.
*/
public interface ValidationGroup3 {
}
|
function OpenVipLink()
{
var obj = document.getElementById("setUserId");
var url = "https://note.youdao.com/charge/setMeal.html?username=" + obj.innerHTML;
var btn = document.getElementById("vipText");
if(btn.value == "试用会员")
{
url = "https://note.youdao.com/charge/setMeal.html?username=" + obj.innerHTML;
}
SendMessageToClient("OpenLink", url);
}
//导入导出
function importynote() {
SendMessageToClient("import","ynote");
}
function importevernote() {
SendMessageToClient("import","evernote");
}
function importothers() {
SendMessageToClient("import","others");
}
function exportynote() {
SendMessageToClient("export","ynote");
}
function exportall() {
SendMessageToClient("export","all");
}
//关于升级
function CheckUpdate()
{
SendMessageToClient("CheckUpdate");
}
function viewLog() {
SendMessageToClient("OpenLink", "https://note.youdao.com/changelog.html?auto=1");
}
function viewLicense() {
SendMessageToClient("OpenLink", "https://note.youdao.com/license.html");
}
function viewLicenseMinors() {
SendMessageToClient("OpenLink", "https://note.youdao.com/juvenile.html");
}
function viewLicenseSecrecy(){
SendMessageToClient("OpenLink", "https://note.youdao.com/license-secrecy.html");
}
//msg from client handle functions
function InitTab(param1)
{
var id = 'tab' + param1 + 'show';
var idLeft = 'tab' + param1;
var objLeft = document.getElementById(idLeft);
document.getElementById(id).style.display = 'block';
objLeft.style.backgroundColor = '#E8F0FF';
objLeft.className = objLeft.className.replace( 'leftline' , 'leftlinesel' );
}
function SetDevices(param1, param2)
{
if(param1 == "NetError")
{
document.getElementById("neterror").style.display = 'block';
document.getElementById("devices").style.display = 'none';
}
else
{
document.getElementById("devicename").innerHTML = param2;
document.getElementById("devices").style.display = 'block';
document.getElementById("neterror").style.display = 'none';
HandleDevices(param1);
}
}
function HandleUserInfo(sig,nickname)
{
if(nickname.length == 0)
{
nickname = '-';
}
document.getElementById("sigature").innerHTML = sig;
document.getElementById("setsigature").value = sig;
document.getElementById("nickname").innerHTML = nickname;
document.getElementById("nicknamebig").innerHTML = nickname;
document.getElementById("setnickname").value = nickname;
}
function SetDistrict(param1)
{
if(param1.length != 0)
{
var districtArray = param1.split(' ');
if (districtArray[0] == "中国") {
districtArray.shift();
}
var obj = document.getElementById("district");
obj.value = districtArray[0];
onSelectChange(obj);
obj = document.getElementById("city");
obj.value = districtArray[1];
if (districtArray[0].length == 0) {
obj.disabled = true;
}
var fullarea = districtArray[0] + ' ' + districtArray[1];
document.getElementById("userArea").innerHTML = fullarea;
}
}
function SetGender(param1)
{
var gender = parseInt(param1);
var objtext = document.getElementById('userGender');
var objectId = "genderUnknown";
if (gender == 0) {
objectId = "genderMale";
objtext.innerHTML = '男';
}
else if (gender == 1) {
objectId = "genderFemale";
objtext.innerHTML = '女';
}
else if (gender == 2) {
objtext.innerHTML = '保密';
}
var obj = document.getElementById(objectId);
$(obj).parent().addClass("checked");
}
function SetVip(param1,param2)
{
var spacetip = document.getElementById("spacetip");
var spacetipVip = document.getElementById("spacetipVip");
var vipIcon = document.getElementById("vipIcon");
var novipIcon = document.getElementById("novipIcon");
if( param1 == "1")
{
document.getElementById("vipText").value = "查看会员";
if(param2 == "获取失败")
{
document.getElementById("expiretime").innerHTML = param2;
}
else if(parseInt(param2) != 0) {
var endDate = new Date(parseInt(param2));
document.getElementById("expiretime").innerHTML = DateToFormatString(endDate);
}
vipIcon.style.display = "inline-block";
novipIcon.style.display = "none";
spacetip.style.display = "none";
spacetipVip.style.display = "block";
}
}
function SetSpace(param1, param2)
{
var obj = document.getElementById("SetSpaceUsed");
var obj2 = document.getElementById("storageused");
var obj3 = document.getElementById("storagetext");
var obj4 = document.getElementById("storageimage");
obj.innerHTML = param1;
obj3.innerHTML = param2;
obj2.style.width = param2;
var leftvalue = obj2.getBoundingClientRect().right;
obj3.style.left = leftvalue - 122;
obj4.style.left = leftvalue - 134;
if(param2 == "100%")
{
obj2.style.borderRadius = "100px 100px 100px 100px";
}
if(param2 == "100%" || param2 == "99%" || param2 == "98%")
{
obj3.style.left = leftvalue - 132;
obj4.style.left = leftvalue - 144;
}
}
function SetProxyAccount(param1, param2)
{
document.getElementById("ProxyName").value = param1;
document.getElementById("ProxyPswd").value = param2;
}
function SetProxy(param1,param2,param3)
{
if(param1 == "1")
{
addClass("UseProxy");
SetProxyOptions(false);
}
else
{
SetProxyOptions(true);
}
document.getElementById("ProxyAddr").value = param2;
document.getElementById("ProxyPort").value = param3;
}
function SetBindStatus(param1,param2,param3)
{
var obj1 = document.getElementById("safetab3show1");
var obj2 = document.getElementById("safetab3show2");
var obj3 = document.getElementById("safetab3show3");
obj1.style.display = "none";
obj2.style.display = "inline-block";
obj3.style.display = "none";
if(param1 == "empty")
{
return;
}
else if(param1 == "notvip")
{
obj1.style.display = "inline-block";
obj2.style.display = "none";
obj3.style.display = "none";
}
else if(param1 == "neterror")
{
obj1.style.display = "none";
obj2.style.display = "none";
obj3.style.display = "inline-block";
}
else
{
document.getElementById("phoneinput").style.display = 'none';
document.getElementById("phoneresult").style.display = 'inline-block';
}
var number = param1.substring(0,3) + "****" + param1.substring(7);
var obj;
var bindnum = document.getElementById("BindNumber");
bindnum.innerHTML = number;
if(param2 == 'true')
{
obj = document.getElementById("loginTip1");
$(obj).parent().addClass("checked");
}
if(param3 == 'true')
{
obj = document.getElementById("loginTip2");
$(obj).parent().addClass("checked");
}
CheckBindOption();
}
function SetKeyDisable(param1)
{
var bDisable = false;;
if(param1 == "true")
{
bDisable = true;
}
document.getElementById("SetTimeLock").disabled = bDisable;
document.getElementById("SetMinLock").disabled = bDisable;
document.getElementById("SetIntevals").disabled = bDisable;
document.getElementById("SetSwitchLock").disabled = bDisable;
}
function SetReadKeyDisable(param1)
{
var bDisable = false;;
if(param1 == "true")
{
bDisable = true;
}
document.getElementById("SetMinReadLock").disabled = bDisable;
document.getElementById("SetTimeReadLock").disabled = bDisable;
document.getElementById("SetReadIntevals").disabled = bDisable;
document.getElementById("SetSwitchReadLock").disabled = bDisable;
} |
#!/bin/bash
if [[ $USER != 'root' ]]; then
echo "Maaf, Anda harus menjalankan ini sebagai root"
exit
fi
# get the VPS IP
#ip=`ifconfig venet0:0 | grep 'inet addr' | awk {'print $2'} | sed s/.*://`
MYIP=`ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0' | head -n1`;
#MYIP=$(ifconfig | grep 'inet addr:' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | cut -d: -f2 | awk '{ print $1}' | head -1)
if [ "$MYIP" = "" ]; then
MYIP=$(wget -qO- ipv4.icanhazip.com)
fi
#MYIP=$(wget -qO- ipv4.icanhazip.com)
echo "" > /root/infouser.txt
echo "" > /root/expireduser.txt
echo "" > /root/activeuser.txt
echo "" > /root/alluser.txt
cat /etc/shadow | cut -d: -f1,8 | sed /:$/d > /tmp/expirelist.txt
totalaccounts=`cat /tmp/expirelist.txt | wc -l`
for((i=1; i<=$totalaccounts; i++ ))
do
tuserval=`head -n $i /tmp/expirelist.txt | tail -n 1`
username=`echo $tuserval | cut -f1 -d:`
userexp=`echo $tuserval | cut -f2 -d:`
userexpireinseconds=$(( $userexp * 86400 ))
tglexp=`date -d @$userexpireinseconds`
tgl=`echo $tglexp |awk -F" " '{print $3}'`
while [ ${#tgl} -lt 2 ]
do
tgl="0"$tgl
done
while [ ${#username} -lt 15 ]
do
username=$username" "
done
bulantahun=`echo $tglexp |awk -F" " '{print $2,$6}'`
echo " User : $username Expire tanggal : $tgl $bulantahun" >> /root/alluser.txt
todaystime=`date +%s`
if [ $userexpireinseconds -ge $todaystime ]; then
echo " User : $username Expire tanggal : $tgl $bulantahun" >> /root/activeuser.txt
timeto7days=$(( $todaystime + 604800 ))
if [ $userexpireinseconds -le $timeto7days ]; then
echo " User : $username Expire tanggal : $tgl $bulantahun" >> /root/infouser.txt
fi
else
echo " User : $username Expire tanggal : $tgl $bulantahun" >> /root/expireduser.txt
passwd -l $username
fi
done
|
<filename>SDK/Plugin/Transaction/Payload/UnregisterCR.h
// Copyright (c) 2012-2018 The Elastos Open Source Project
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef __ELASTOS_SDK_UNREGISTERCR_H__
#define __ELASTOS_SDK_UNREGISTERCR_H__
#include <Plugin/Transaction/Payload/IPayload.h>
namespace Elastos {
namespace ElaWallet {
class UnregisterCR : public IPayload {
public:
UnregisterCR();
~UnregisterCR();
void SetCID(const uint168 &cid);
const uint168 &GetCID() const;
void SetSignature(const bytes_t &signature);
const bytes_t &GetSignature() const;
virtual size_t EstimateSize(uint8_t version) const;
virtual void Serialize(ByteStream &ostream, uint8_t version) const;
virtual bool Deserialize(const ByteStream &istream, uint8_t version);
void SerializeUnsigned(ByteStream &ostream, uint8_t version) const;
bool DeserializeUnsigned(const ByteStream &istream, uint8_t version);
virtual nlohmann::json ToJson(uint8_t version) const;
virtual void FromJson(const nlohmann::json &j, uint8_t version);
virtual IPayload &operator=(const IPayload &payload);
UnregisterCR &operator=(const UnregisterCR &payload);
private:
uint168 _cid;
bytes_t _signature;
};
}
}
#endif //__ELASTOS_SDK_UNREGISTERCR_H__
|
<filename>core/src/mindustry/editor/EditorTool.java
package mindustry.editor;
import arc.func.*;
import arc.math.*;
import arc.math.geom.*;
import arc.struct.*;
import arc.util.*;
import mindustry.content.*;
import mindustry.game.*;
import mindustry.world.*;
import mindustry.world.blocks.*;
public enum EditorTool{
zoom,
pick{
public void touched(MapEditor editor, int x, int y){
if(!Structs.inBounds(x, y, editor.width(), editor.height())) return;
Tile tile = editor.tile(x, y).link();
editor.drawBlock = tile.block() == Blocks.air ? tile.overlay() == Blocks.air ? tile.floor() : tile.overlay() : tile.block();
}
},
line("replace", "orthogonal"){
@Override
public void touchedLine(MapEditor editor, int x1, int y1, int x2, int y2){
//straight
if(mode == 1){
if(Math.abs(x2 - x1) > Math.abs(y2 - y1)){
y2 = y1;
}else{
x2 = x1;
}
}
Bresenham2.line(x1, y1, x2, y2, (x, y) -> {
if(mode == 0){
//replace
editor.drawBlocksReplace(x, y);
}else{
//normal
editor.drawBlocks(x, y);
}
});
}
},
pencil("replace", "square", "drawteams"){
{
edit = true;
draggable = true;
}
@Override
public void touched(MapEditor editor, int x, int y){
if(mode == -1){
//normal mode
editor.drawBlocks(x, y);
}else if(mode == 0){
//replace mode
editor.drawBlocksReplace(x, y);
}else if(mode == 1){
//square mode
editor.drawBlocks(x, y, true, tile -> true);
}else if(mode == 2){
//draw teams
editor.drawCircle(x, y, tile -> tile.link().setTeam(editor.drawTeam));
}
}
},
eraser("eraseores"){
{
edit = true;
draggable = true;
}
@Override
public void touched(MapEditor editor, int x, int y){
editor.drawCircle(x, y, tile -> {
if(mode == -1){
//erase block
tile.remove();
}else if(mode == 0){
//erase ore
tile.clearOverlay();
}
});
}
},
fill("replaceall", "fillteams"){
{
edit = true;
}
IntArray stack = new IntArray();
@Override
public void touched(MapEditor editor, int x, int y){
if(!Structs.inBounds(x, y, editor.width(), editor.height())) return;
Tile tile = editor.tile(x, y);
if(editor.drawBlock.isMultiblock()){
//don't fill multiblocks, thanks
pencil.touched(editor, x, y);
return;
}
//mode 0 or 1, fill everything with the floor/tile or replace it
if(mode == 0 || mode == -1){
//can't fill parts or multiblocks
if(tile.block() instanceof BlockPart || tile.block().isMultiblock()){
return;
}
Boolf<Tile> tester;
Cons<Tile> setter;
if(editor.drawBlock.isOverlay()){
Block dest = tile.overlay();
if(dest == editor.drawBlock) return;
tester = t -> t.overlay() == dest && !t.floor().isLiquid;
setter = t -> t.setOverlay(editor.drawBlock);
}else if(editor.drawBlock.isFloor()){
Block dest = tile.floor();
if(dest == editor.drawBlock) return;
tester = t -> t.floor() == dest;
setter = t -> t.setFloorUnder(editor.drawBlock.asFloor());
}else{
Block dest = tile.block();
if(dest == editor.drawBlock) return;
tester = t -> t.block() == dest;
setter = t -> t.setBlock(editor.drawBlock, editor.drawTeam);
}
//replace only when the mode is 0 using the specified functions
fill(editor, x, y, mode == 0, tester, setter);
}else if(mode == 1){ //mode 1 is team fill
//only fill synthetic blocks, it's meaningless otherwise
if(tile.link().synthetic()){
Team dest = tile.getTeam();
if(dest == editor.drawTeam) return;
fill(editor, x, y, false, t -> t.getTeamID() == (int)dest.id && t.link().synthetic(), t -> t.setTeam(editor.drawTeam));
}
}
}
void fill(MapEditor editor, int x, int y, boolean replace, Boolf<Tile> tester, Cons<Tile> filler){
int width = editor.width(), height = editor.height();
if(replace){
//just do it on everything
for(int cx = 0; cx < width; cx++){
for(int cy = 0; cy < height; cy++){
Tile tile = editor.tile(cx, cy);
if(tester.get(tile)){
filler.get(tile);
}
}
}
}else{
//perform flood fill
int x1;
stack.clear();
stack.add(Pos.get(x, y));
while(stack.size > 0){
int popped = stack.pop();
x = Pos.x(popped);
y = Pos.y(popped);
x1 = x;
while(x1 >= 0 && tester.get(editor.tile(x1, y))) x1--;
x1++;
boolean spanAbove = false, spanBelow = false;
while(x1 < width && tester.get(editor.tile(x1, y))){
filler.get(editor.tile(x1, y));
if(!spanAbove && y > 0 && tester.get(editor.tile(x1, y - 1))){
stack.add(Pos.get(x1, y - 1));
spanAbove = true;
}else if(spanAbove && !tester.get(editor.tile(x1, y - 1))){
spanAbove = false;
}
if(!spanBelow && y < height - 1 && tester.get(editor.tile(x1, y + 1))){
stack.add(Pos.get(x1, y + 1));
spanBelow = true;
}else if(spanBelow && y < height - 1 && !tester.get(editor.tile(x1, y + 1))){
spanBelow = false;
}
x1++;
}
}
}
}
},
spray("replace"){
final double chance = 0.012;
{
edit = true;
draggable = true;
}
@Override
public void touched(MapEditor editor, int x, int y){
//floor spray
if(editor.drawBlock.isFloor()){
editor.drawCircle(x, y, tile -> {
if(Mathf.chance(chance)){
tile.setFloor(editor.drawBlock.asFloor());
}
});
}else if(mode == 0){ //replace-only mode, doesn't affect air
editor.drawBlocks(x, y, tile -> Mathf.chance(chance) && tile.block() != Blocks.air);
}else{
editor.drawBlocks(x, y, tile -> Mathf.chance(chance));
}
}
};
/** All the internal alternate placement modes of this tool. */
public final String[] altModes;
/** The current alternate placement mode. -1 is the standard mode, no changes.*/
public int mode = -1;
/** Whether this tool causes canvas changes when touched.*/
public boolean edit;
/** Whether this tool should be dragged across the canvas when the mouse moves.*/
public boolean draggable;
EditorTool(){
this(new String[]{});
}
EditorTool(String... altModes){
this.altModes = altModes;
}
public void touched(MapEditor editor, int x, int y){}
public void touchedLine(MapEditor editor, int x1, int y1, int x2, int y2){}
}
|
from flask import render_template, request, redirect, url_for
@app.route('/user_profile', methods=['GET'])
def all_messages(msg_id):
isloggedin = validate_helper(request.cookies.get('token'))
if not isloggedin:
return render_template('search.html')
else:
msg_result_size, msg_results = db.get_all_messages(isloggedin, msg_id)
# Process and use msg_result_size and msg_results as needed
return render_template('user_profile.html', messages=msg_results) |
#!/bin/bash
#
# docker-entrypoint for Solr docker
set -e
# Clear some variables that we don't want runtime
unset SOLR_USER SOLR_UID SOLR_GROUP SOLR_GID \
SOLR_CLOSER_URL SOLR_DIST_URL SOLR_ARCHIVE_URL SOLR_DOWNLOAD_URL SOLR_DOWNLOAD_SERVER SOLR_KEYS SOLR_SHA512
if [[ "$VERBOSE" == "yes" ]]; then
set -x
fi
if ! [[ ${SOLR_PORT:-} =~ ^[0-9]+$ ]]; then
SOLR_PORT=8983
export SOLR_PORT
fi
# when invoked with e.g.: docker run solr -help
if [ "${1:0:1}" == '-' ]; then
set -- solr-foreground "$@"
fi
# execute command passed in as arguments.
# The Dockerfile has specified the PATH to include
# /opt/solr/bin (for Solr) and /opt/docker-solr/scripts (for our scripts
# like solr-foreground, solr-create, solr-precreate, solr-demo).
# Note: if you specify "solr", you'll typically want to add -f to run it in
# the foreground.
exec "$@"
|
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+512+512-N-VB-IP/model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+512+512-N-VB-IP/1024+0+512-shuffled-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function shuffle_first_two_thirds_sixth --eval_function penultimate_sixth_eval |
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com/'
# Get the response from the URL
response = requests.get(url)
# Parse the response with BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
# Extract the content
content = soup.find_all('p')
# Print out the content
for i in content:
print(i.text) |
<gh_stars>0
import { HTMLNodeElement } from 'types';
export function addOnFunctionEvents(htmlNode: HTMLNodeElement) {
htmlNode.onpanelupdate = () => {};
htmlNode.onpanelwillunmount = () => {};
}
|
const todos = ["Buy milk"];
const listTodos = () => {
console.log(todos);
};
const addTodo = (todo) => {
todos.push(todo);
};
const handleInput = (input) => {
if (input === "list") {
listTodos();
} else if (input === "new") {
let newTodo = prompt("Enter new todo");
addTodo(newTodo);
}
};
let input = prompt("What would you like to do?");
handleInput(input); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.