text stringlengths 1 1.05M |
|---|
//
// NSUserNotificationCenter+KSNotifications.h
// Github Status
//
// Created by <NAME> on 7/18/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
@interface NSUserNotificationCenter (KSNotifications)
- (void)ks_deliverNotificationWithText:(NSString *)text;
@end
|
<gh_stars>0
import numpy as np
import pandas as pd
import math
def report_back(km, cur_dis, cur_beat, tot_beat):
df=pd.read_csv('history_1.csv')
df.describe()
df.dropna()
#print df.columns
df=df.drop(['Beat number'],axis=1)
avg_speed=[]
for i in range(len(df)):
avg_speed.append(df['Distance (km)'][i]/df['Time Taken (minutes)'][i])
df['Average Speed']=avg_speed
#print df
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LinearRegression as LR
X,Y=df[['Distance (km)']],df[['Time Taken (minutes)']]
X_t,X_test,Y_t,Y_test=train_test_split(X,Y,test_size=0.3,random_state=42)
regressor=LR().fit(X,Y)
#plt.plot(X,Y)
#plt.scatter(X,Y,color='orange')
print "Expected Time of Completion : ",regressor.predict(km)[0][0],"minutes"
print cur_dis/float(km) * 100,"% distance already covered \n",cur_beat/float(tot_beat) * 100,"% Beat portions covered"
print "Estimated Time to complete remaining beat points :",regressor.predict(km-cur_dis)[0][0],"minutes"
report_back(14,10,4,6) |
import React from 'react';
import { storiesOf } from '@storybook/react';
import { ParticlesContainer } from './ParticlesContainer';
const svgParams = {
fps_limit: 28,
particles: {
number: {
value: 200,
density: {
enable: false,
},
},
line_linked: {
color: '#3CA9D1',
enable: true,
distance: 30,
opacity: 0.4,
},
move: {
speed: 1,
},
opacity: {
anim: {
enable: true,
opacity_min: 0.05,
speed: 2,
sync: false,
},
value: 0.4,
},
},
polygon: {
enable: true,
scale: 0.5,
type: 'inline',
move: {
radius: 10,
},
url: '/svg/small-deer.2a0425af.svg',
inline: {
arrangement: 'equidistant',
},
draw: {
enable: true,
stroke: {
color: 'rgba(255, 255, 255, .2)',
},
},
},
retina_detect: false,
interactivity: {
events: {
onhover: {
enable: true,
mode: 'bubble',
},
},
modes: {
bubble: {
size: 6,
distance: 40,
},
},
},
};
const imgParams = {
particles: {
number: {
value: 10,
density: {
enable: true,
value_area: 100,
},
},
line_linked: {
enable: false,
},
move: {
speed: 1,
out_mode: 'out',
},
shape: {
type: ['images', 'circles'],
images: [
{
src: './cys/png/001-lock.png',
height: 100,
width: 100,
},
{
src: './cys/png/003-password.png',
height: 100,
width: 100,
},
],
},
color: {
value: '#CCC',
},
size: {
value: 30,
random: false,
anim: {
enable: true,
speed: 4,
size_min: 10,
sync: false,
},
},
},
retina_detect: false,
};
storiesOf('Particles Container', module)
.add('basic', () => <ParticlesContainer>Basic</ParticlesContainer>)
.add('svg', () => <ParticlesContainer params={svgParams}>SVG</ParticlesContainer>)
.add('image', () => <ParticlesContainer params={imgParams}>SVG</ParticlesContainer>);
|
/*! Example v1.0.0 | (c) 2014 Example, Inc. | example.com/license */
|
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import FactoryMaker from '../../core/FactoryMaker';
import Constants from '../../streaming/constants/Constants';
function SegmentBaseGetter(config) {
config = config || {};
const timelineConverter = config.timelineConverter;
let instance;
function checkConfig() {
if (!timelineConverter || !timelineConverter.hasOwnProperty('calcPeriodRelativeTimeFromMpdRelativeTime')) {
throw new Error(Constants.MISSING_CONFIG_ERROR);
}
}
function getMediaFinishedInformation(representation) {
const mediaFinishedInformation = { numberOfSegments: 0, mediaTimeOfLastSignaledSegment: NaN }
if (!representation || !representation.segments) {
return mediaFinishedInformation
}
mediaFinishedInformation.numberOfSegments = representation.segments.length;
return mediaFinishedInformation;
}
function getSegmentByIndex(representation, index) {
checkConfig();
if (!representation) {
return null;
}
const len = representation.segments ? representation.segments.length : -1;
let seg;
if (index < len) {
seg = representation.segments[index];
if (seg && seg.index === index) {
return seg;
}
}
for (let i = 0; i < len; i++) {
seg = representation.segments[i];
if (seg && seg.index === index) {
return seg;
}
}
return null;
}
function getSegmentByTime(representation, requestedTime) {
checkConfig();
const index = getIndexByTime(representation, requestedTime);
return getSegmentByIndex(representation, index);
}
function getIndexByTime(representation, time) {
if (!representation) {
return -1;
}
const segments = representation.segments;
const ln = segments ? segments.length : null;
let idx = -1;
let epsilon,
seg,
ft,
fd,
i;
if (segments && ln > 0) {
for (i = 0; i < ln; i++) {
seg = segments[i];
ft = seg.presentationStartTime;
fd = seg.duration;
epsilon = fd / 2;
if ((time + epsilon) >= ft &&
(time - epsilon) < (ft + fd)) {
idx = seg.index;
break;
}
}
}
return idx;
}
instance = {
getSegmentByIndex,
getSegmentByTime,
getMediaFinishedInformation
};
return instance;
}
SegmentBaseGetter.__dashjs_factory_name = 'SegmentBaseGetter';
const factory = FactoryMaker.getClassFactory(SegmentBaseGetter);
export default factory;
|
Criando arquivo no VScode
Utilizando o Git e Github |
int randomNumber = (rand() % (b - a + 1)) + a; //randomNumber is between 10 and |
#!/bin/sh
#
# This Cmd4 example demonstrates a little more advanced way of using ping to test if an
# accessory is on the network by passing in the IP address to be used with the Cmd4 option
# of state_cmd_suffix.
#
# Your Cmd4 .homebridge/.config.json file would have a state_cmd like:
# state_cmd: ".homebridge/Cmd4Scripts/Examples/ping.sh"
# state_cmd_suffix: "192.168.2.1"
#
# Testing from the shell prompt:
# ./advanced_ping.sh Get My_TV On 192.168.2.1
# or
# ./advanced_ping.sh Set My_TV On 1 192.168.2.1
# Exit immediately if a command exits with a non-zero status
set -e
# Check if the first parameter to this script was "Get" for getting an accessory's
# specific attribute.
if [ "$1" = "Get" ]; then
# Cmd4 will pass the IP in the config.json defined by state_cmd_suffix as the fourth
# parameter to a Get command.
ip="${4}"
# Normally we would exit immediately if a command fails with a non-zero status.
# In this case ping can fail and we would rely on the failing exit status to
# tell Cmd4 that the accessory is not on the network. That would be the prefered
# thing to do. However for this example we are going to output '0' (false) so
# that you can see the '0' on the console telling us that the accessory is not
# on the network.
set +e
# $2 would be the name of the accessory
# $3 would be the accessory's charactersistic 'On'
# On OSX the string is returned differently than on linux.
ping -c 2 -W 1 "${ip}" | sed -E 's/2 packets received/2 received/g' | grep -i '2 received' >> /dev/null
rc=$?
# Exit immediately if a command exits with a non-zero status
set -e
# Check if we got the message '2 packets recieved' meaning the accessory is
# on the network by seeing if the return code of the above command passed or
# failed.
if [ "$rc" = "0" ]; then
# The message was recieved so the target is up, sending a '1' (true), like
# a binary number is, back to Cmd4.
echo "1"
# Exit this script positivitely.
exit 0
else
# The message was not recieved so the target must be down, sending a '0' (false), like
# a binary number is, back to Cmd4.
echo "0"
# Exit this script positivitely, even though ping failed.
exit 0
fi
fi
# Check if the first parameter to this script was "Set" for setting an accessory's
# specific attribute.
if [ "$1" = "Set" ]; then
# $2 would be the name of the accessory.
# $3 would be the accessory's charactersistic 'On'.
# $4 would be '1' for 'On' and '0' for 'Off', like a binary number is.
# $4 would be 'true' for 'On' and 'false' for 'Off' with
# outputConstants=true in your .homebridge/.config.json file.
# Cmd4 will pass the IP in the config.json defined by state_cmd_suffix as the fifth
# parameter to a Set command.
ip="${5}"
# This ping script does not do anything for set so just exit successfully.
exit 0
fi
# The proper arguments to this script were not passed to it so end with a failure exit status.
exit 66
|
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
*
* 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.
*
***************************************************************************/
#define BUNDLE(TYPE, ...) \
OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_BUNDLE, OATPP_MACRO_API_CONTROLLER_BUNDLE_INFO, TYPE, (__VA_ARGS__))
// BUNDLE MACRO // ------------------------------------------------------
#define OATPP_MACRO_API_CONTROLLER_BUNDLE_1(TYPE, NAME) \
TYPE NAME = __request->getBundleData<TYPE>(#NAME);
#define OATPP_MACRO_API_CONTROLLER_BUNDLE_2(TYPE, NAME, QUALIFIER) \
TYPE NAME = __request->getBundleData<TYPE>(QUALIFIER);
#define OATPP_MACRO_API_CONTROLLER_BUNDLE(TYPE, PARAM_LIST) \
OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_BUNDLE_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST)
#define OATPP_MACRO_API_CONTROLLER_BUNDLE_INFO(TYPE, PARAM_LIST)
|
Office.initialize = function () {
}
//Clears all charges for the customer.
function clearValues(event) {
var item = Office.cast.item.toItemRead(Office.context.mailbox.item);
var organizer = Office.cast.item.toAppointmentRead(item).organizer;
localStorage.removeItem(organizer.displayName);
item.notificationMessages.replaceAsync("status", {
type: "informationalMessage",
icon: "icon1_16x16",
message: "Finished clearing charges for customer.",
persistent: false
});
event.completed();
}
|
import pandas as pd
import numpy as np
import cv2
KEYPOINT = {
0: 'nose',
1: 'left_eye',
2: 'right_eye',
3: 'left_ear',
4: 'right_ear',
5: 'left_shoulder',
6: 'right_shoulder',
7: 'left_elbow',
8: 'right_elbow',
9: 'left_wrist',
10: 'right_wrist',
11: 'left_hip',
12: 'right_hip',
13: 'left_knee',
14: 'right_knee',
15: 'left_ankle',
16: 'right_ankle'
}
SKELETON = [
[0,6],[6,8],[8,10],[6,12],[12,14],[14,16]
]
COLORS = [[255, 0, 0], [0, 255, 255], [0,255,255], [127, 127, 127], [0, 0, 255], [0,0,255]]
if __name__ == "__main__":
df = pd.read_excel("C:/Users/neo/Downloads/正手模型1.xlsx", )
print(df.head())
for j, r in df.iterrows():
img = np.zeros((720,1280,3), np.uint8)
r = r.to_dict()
for i in range(len(SKELETON)):
kpt_a, kpt_b = KEYPOINT[SKELETON[i][0]], KEYPOINT[SKELETON[i][1]]
x_a, y_a = r[kpt_a + "_x"] + 330, r[kpt_a + "_y"] + 410
x_b, y_b = r[kpt_b + "_x"] + 330, r[kpt_b + "_y"] + 410
cv2.circle(img, (int(x_a), int(y_a)), 6, COLORS[i], -1)
cv2.circle(img, (int(x_b), int(y_b)), 6, COLORS[i], -1)
cv2.line(img, (int(x_a), int(y_a)), (int(x_b), int(y_b)), COLORS[i], 2)
cv2.imwrite("../output/img_{}.jpg".format(j+1), img)
print("finish")
|
# Finding the lowest common multiple (LCM)
# of two given numbers
def find_lcm(x, y):
# Choose the greater number
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
# Input
x = 15
y = 20
# Print result
print("The LCM of", x, "and", y, "is", find_lcm(x, y)) |
#!/usr/bin/env bash
#
# Script to install host system binaries along with required libraries.
#
# Copyright (C) 2012-2017 Jo-Philipp Wich <jo@mein.io>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
DIR="$1"; shift
_cp() {
cp ${VERBOSE:+-v} -L "$1" "$2" || {
echo "cp($1 $2) failed" >&2
exit 1
}
}
_mv() {
mv ${VERBOSE:+-v} "$1" "$2" || {
echo "mv($1 $2) failed" >&2
exit 1
}
}
_md() {
mkdir ${VERBOSE:+-v} -p "$1" || {
echo "mkdir($1) failed" >&2
exit 2
}
}
_ln() {
ln ${VERBOSE:+-v} -sf "$1" "$2" || {
echo "ln($1 $2) failed" >&2
exit 3
}
}
_relpath() {
local base="$(readlink -f "$1")"
local dest="$(readlink -f "$2")"
local up
[ -d "$base" ] || base="${base%/*}"
[ -d "$dest" ] || dest="${dest%/*}"
while true; do
case "$base"
in "$dest"/*)
echo "$up/${base#$dest/}"
break
;;
*)
dest="${dest%/*}"
up="${up:+$up/}.."
;;
esac
done
}
_runas_so() {
cat <<-EOT | ${CC:-gcc} -x c -fPIC -shared -o "$1" -
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int mangle_arg0(int argc, char **argv, char **env) {
char *arg0 = getenv("RUNAS_ARG0");
if (arg0) {
argv[0] = arg0;
unsetenv("RUNAS_ARG0");
}
return 0;
}
#ifdef __APPLE__
__attribute__((section("__DATA,__mod_init_func")))
#else
__attribute__((section(".init_array")))
#endif
static void *mangle_arg0_constructor = &mangle_arg0;
EOT
[ -x "$1" ] || {
echo "compiling preload library failed" >&2
exit 5
}
}
_patch_ldso() {
_cp "$1" "$1.patched"
sed -i -e 's,/\(usr\|lib\|etc\)/,/###/,g' "$1.patched"
if "$1.patched" 2>&1 | grep -q -- --library-path; then
_mv "$1.patched" "$1"
else
echo "binary patched ${1##*/} not executable, using original" >&2
rm -f "$1.patched"
fi
}
_patch_glibc() {
_cp "$1" "$1.patched"
sed -i -e 's,/usr/\(\(lib\|share\)/locale\),/###/\1,g' "$1.patched"
if "$1.patched" 2>&1 | grep -q -- GNU; then
_mv "$1.patched" "$1"
else
echo "binary patched ${1##*/} not executable, using original" >&2
rm -f "$1.patched"
fi
}
should_be_patched() {
local bin="$1"
[ -x "$bin" ] || return 1
case "$bin" in
*.so|*.so.[0-9]*)
return 1
;;
*)
file "$bin" | grep -sqE "ELF.*(executable|interpreter)" && return 0
;;
esac
return 1
}
for LDD in ${PATH//://ldd }/ldd; do
"$LDD" --version >/dev/null 2>/dev/null && break
LDD=""
done
[ -n "$LDD" -a -x "$LDD" ] || LDD=
for BIN in "$@"; do
[ -n "$BIN" -a -n "$DIR" ] || {
echo "Usage: $0 <destdir> <executable> ..." >&2
exit 1
}
[ ! -d "$DIR/lib" ] && {
_md "$DIR/lib"
_md "$DIR/usr"
_ln "../lib" "$DIR/usr/lib"
}
[ ! -x "$DIR/lib/runas.so" ] && {
_runas_so "$DIR/lib/runas.so"
}
LDSO=""
[ -n "$LDD" ] && should_be_patched "$BIN" && {
for token in $("$LDD" "$BIN" 2>/dev/null); do
case "$token" in */*.so*)
dest="$DIR/lib/${token##*/}"
ddir="${dest%/*}"
case "$token" in
*/ld-*.so*) LDSO="${token##*/}" ;;
esac
[ -f "$token" -a ! -f "$dest" ] && {
_md "$ddir"
_cp "$token" "$dest"
case "$token" in
*/ld-*.so*) _patch_ldso "$dest" ;;
*/libc.so.6) _patch_glibc "$dest" ;;
esac
}
;; esac
done
}
# is a dynamically linked executable
if [ -n "$LDSO" ]; then
echo "Bundling ${BIN##*/}"
RUNDIR="$(readlink -f "$BIN")"; RUNDIR="${RUNDIR%/*}"
RUN="${LDSO#ld-}"; RUN="run-${RUN%%.so*}.sh"
REL="$(_relpath "$DIR/lib" "$BIN")"
_mv "$BIN" "$RUNDIR/.${BIN##*/}.bin"
cat <<-EOF > "$BIN"
#!/usr/bin/env bash
dir="\$(dirname "\$0")"
export RUNAS_ARG0="\$0"
export LD_PRELOAD="\${LD_PRELOAD:+\$LD_PRELOAD:}\$dir/${REL:+$REL/}runas.so"
exec "\$dir/${REL:+$REL/}$LDSO" --library-path "\$dir/${REL:+$REL/}" "\$dir/.${BIN##*/}.bin" "\$@"
EOF
chmod ${VERBOSE:+-v} 0755 "$BIN"
fi
done
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var profileCode = {
a: {
type: Number,
required: [true, 'Profile Code Quadrant A is missing'],
validate: [
function(a) {
return (a > 0 && a < 3);
},
'Profile Code Quadrant A should be greater than 0 and less than 3'
]
},
b: {
type: Number,
required: [true, 'Profile Code Quadrant B is missing'],
validate: [
function(b) {
return (b > 0 && b < 3);
},
'Profile Code Quadrant B should be greater than 0 and less than 3'
]
},
c: {
type: Number,
required: [true, 'Profile Code Quadrant C is missing'],
validate: [
function(c) {
return (c > 0 && c < 3);
},
'Profile Code Quadrant C should be greater than 0 and less than 3'
]
},
d: {
type: Number,
required: [true, 'Profile Code Quadrant D is missing'],
validate: [
function(d) {
return (d > 0 && d < 3);
},
'Profile Code Quadrant D should be greater than 0 and less than 3'
]
}
};
var communication = {
prefer: {
title: {
type: String,
required: [true, 'Prefered Communication Title is missing']
},
description: {
type: String,
required: [true, 'Prefered Communication Description is missing']
}
},
overlook: {
title: {
type: String,
required: [true, 'Overlooked Communication Title is missing']
},
description: {
type: String,
required: [true, 'Overlooked Communication Description is missing']
}
}
};
var strategy = {
prefer: {
title: {
type: String,
required: [true, 'Prefered Strategy Title is missing']
},
description: {
type: String,
required: [true, 'Prefered Strategy Description is missing']
}
},
overlook: {
title: {
type: String,
required: [true, 'Overlooked Strategy Title is missing']
},
description: {
type: String,
required: [true, 'Overlooked Strategy Description is missing']
}
}
};
var decision = {
prefer: {
title: {
type: String,
required: [true, 'Prefered Decision Title is missing']
},
description: {
type: String,
required: [true, 'Prefered Decision Description is missing']
}
},
overlook: {
title: {
type: String,
required: [true, 'Overlooked Decision Title is missing']
},
description: {
type: String,
required: [true, 'Overlooked Decision Description is missing']
}
}
};
var HerrmannModel = new Schema({
profileCode: [profileCode],
databasePercentage: {
type: String,
required: [true, 'Database Percentage is missing']
},
description: {
type: String,
required: [true, 'Description is missing']
},
communication: [communication],
strategy: [strategy],
decision: [decision]
});
module.exports = mongoose.model('Herrmann', HerrmannModel);
|
#!/bin/bash
db_host=""
db_port=""
auth_user=""
auth_pswd=""
db_name=""
project_name=""
bckp_folder_name="mongodump-${project_name}-$(date | sed 's/ /-/g')"
zip_file_name="${bckp_folder_name}.zip"
mongodump --host $db_host --port $db_port \
--username $auth_user --password $auth_pswd \
-d $db_name \
--out $bckp_folder_name
zip -r $zip_file_name $bckp_folder_name
rm -rf $bckp_folder_name
# Delete backups older than 30 days
find *.zip -mtime +30 -exec rm -rf {} \;
echo "Done!"
exit 0
|
#!/bin/bash
# ***** BEGIN LICENSE BLOCK *****
#
# Copyright (C) 2017-2019 Olof Hagsand
# Copyright (C) 2020-2021 Olof Hagsand and Rubicon Communications, LLC(Netgate)
#
# This file is part of CLIXON
#
# 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.
#
# Alternatively, the contents of this file may be used under the terms of
# the GNU General Public License Version 3 or later (the "GPL"),
# in which case the provisions of the GPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of the GPL, and not to allow others to
# use your version of this file under the terms of Apache License version 2,
# indicate your decision by deleting the provisions above and replace them with
# the notice and other provisions required by the GPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the Apache License version 2 or the GPL.
#
# ***** END LICENSE BLOCK *****
# Usage: ./startup.sh
# Debug: DBG=1 ./startup.sh
# See also cleanup.sh
>&2 echo "Running script: $0"
# Start clixon-example backend
sudo docker run --name clixon --rm -td clixon/clixon || err "Error starting clixon"
>&2 echo "clixon started"
|
<filename>src/main/java/cn/pasteme/common/utils/converter/DoToDtoConverter.java
package cn.pasteme.common.utils.converter;
/**
* @author Moyu
* @version 1.0.0
*/
public class DoToDtoConverter extends BeansConverter {
private DoToDtoConverter() {}
public static <T, E> E convert(T source, E target, String... ignore) {
return BeansConverter.convert(source, target, ignore);
}
}
|
#!/bin/bash
mkdir -p ../../gen/dev
cp ../npm/gulpfile.js ../../gen/dev
cd ../../gen/dev
cp ../../src/npm/package.json .
rm -rf src
node_modules/.bin/gulp build_dev
|
// Get the user data from the database for the given username
app.get('/api/user', (req, res) => {
const username = req.query.username;
db.query(`SELECT * FROM users WHERE username = '${username}';`)
.then((data) => {
res.send(data.rows[0]);
})
.catch((err) => {
console.log(err.message);
});
}); |
<reponame>chylex/Hardcore-Ender-Expansion
package chylex.hee.render.entity;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class RenderMobEnderman extends AbstractRenderMobEnderman{}
|
# 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.
#
# processes --config option from command line
#
this="$0"
while [ -h "$this" ]; do
ls=`ls -ld "$this"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '.*/.*' > /dev/null; then
this="$link"
else
this=`dirname "$this"`/"$link"
fi
done
# convert relative path to absolute path
bin=`dirname "$this"`
script=`basename "$this"`
bin=`cd "$bin"; pwd`
this="$bin/$script"
# the root of the Hive installation
if [[ -z $HIVE_HOME ]] ; then
export HIVE_HOME=`dirname "$bin"`
fi
#check to see if the conf dir is given as an optional argument
while [ $# -gt 0 ]; do # Until you run out of parameters . . .
case "$1" in
--config)
shift
confdir=$1
shift
HIVE_CONF_DIR=$confdir
;;
--auxpath)
shift
HIVE_AUX_JARS_PATH=$1
shift
;;
*)
break;
;;
esac
done
# Allow alternate conf dir location.
HIVE_CONF_DIR="${HIVE_CONF_DIR:-$HIVE_HOME/conf}"
export HIVE_CONF_DIR=$HIVE_CONF_DIR
export HIVE_AUX_JARS_PATH=$HIVE_AUX_JARS_PATH
# Default to use 256MB
export HADOOP_HEAPSIZE=${HADOOP_HEAPSIZE:-256}
|
<reponame>Sanjaysj10/angular-meta-tags
export const sectionsMetadata = {
homePage: {
meta: {
title: 'Angular Dynamic Meta Links',
description: 'Angular Homepage Description'
}
},
articles: {
meta: {
title: 'Angular Dynamic Meta Links - Articles',
description: 'Articles Homepage Description'
}
}
} |
# Pull Request ID
export BC_PR_ID="${BC_PR_ID:-${CI_PULL_REQUEST##*/}}";
REPO=$CI_PULL_REQUEST;
REPO=${REPO##https://github.com/};
REPO=${REPO%%/pull/$BC_PR_ID};
# Repo Slug
export BC_REPO_SLUG=$REPO;
# Install dependencies
apk update && apk add jq;
REPOS_VALUES=($(curl -H "Authorization: token $GITHUB_TOKEN" -sSL https://api.github.com/repos/$BC_REPO_SLUG/pulls/$BC_PR_ID | jq -r -c ".head.repo.full_name, .head.repo.owner.login, .base.ref, .head.ref"));
# Pull request base branch (usually master)
export BC_PR_BASE_BRANCH=${REPOS_VALUES[2]};
# Pull request branch (branch to be merged into the base branch)
export BC_PR_BRANCH=${REPOS_VALUES[3]};
|
<gh_stars>100-1000
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
enum NodeType {
Element = 1,
Text = 3,
Comment = 8,
Document = 9,
};
typedef uint32_t NodeType;
typedef uint32_t Ref_Value;
typedef uint32_t Ref_Vec_Value;
typedef uint32_t Ref_String;
typedef uint32_t Ref_App;
typedef Ref_App Option_Ref_App;
typedef uint32_t Ref_Window;
typedef uint32_t WindowId;
typedef Ref_Window Option_Ref_Window;
enum Event_Tag {
CursorPos,
MouseDown,
MouseUp,
Scroll,
KeyUp,
KeyDown,
KeyPress,
Resize,
FramebufferSize,
Close,
};
typedef uint32_t Event_Tag;
typedef struct CursorPos_Body {
float _0;
float _1;
} CursorPos_Body;
typedef struct Scroll_Body {
float _0;
float _1;
} Scroll_Body;
typedef struct Resize_Body {
float _0;
float _1;
} Resize_Body;
typedef struct FramebufferSize_Body {
float _0;
float _1;
} FramebufferSize_Body;
typedef struct Event {
Event_Tag tag;
union {
CursorPos_Body cursor_pos;
Scroll_Body scroll;
struct {
uint32_t key_up;
};
struct {
uint32_t key_down;
};
struct {
uint32_t key_press;
};
Resize_Body resize;
FramebufferSize_Body framebuffer_size;
};
} Event;
typedef uint32_t Ref_WebView;
typedef uint32_t Ref_DocumentRef;
typedef uint32_t Ref_ElementRef;
typedef uint32_t Ref_CharacterDataRef;
typedef uint32_t NodeId;
typedef uint32_t Ref_NodeRef;
typedef Ref_NodeRef Option_Ref_NodeRef;
typedef Ref_ElementRef Option_Ref_ElementRef;
typedef Ref_String Option_Ref_String;
typedef uint32_t Ref_CssStyleDeclaration;
typedef uint32_t Ref_Renderer;
void gft_Ref_drop(Ref_Value obj);
unsigned int gft_Vec_len(Ref_Vec_Value vec);
Ref_Value gft_Vec_get(Ref_Vec_Value vec, unsigned int index);
unsigned int gft_String_bytes_len(Ref_String string);
void gft_String_copy(Ref_String string, uint8_t *dest_buf);
Ref_App gft_App_init(void);
Option_Ref_App gft_App_current(void);
void gft_App_tick(Ref_App app);
void gft_App_wake_up(Ref_App app);
Ref_Window gft_Window_new(const char *title, uint32_t title_len, int width, int height);
WindowId gft_Window_id(Ref_Window win);
Option_Ref_Window gft_Window_find_by_id(WindowId id);
bool gft_Window_next_event(Ref_Window win, struct Event *event_dest);
Ref_String gft_Window_title(Ref_Window win);
void gft_Window_set_title(Ref_Window win, const char *title, uint32_t title_len);
int gft_Window_width(Ref_Window win);
int gft_Window_height(Ref_Window win);
void gft_Window_resize(Ref_Window win, int width, int height);
bool gft_Window_should_close(Ref_Window win);
void gft_Window_show(Ref_Window win);
void gft_Window_hide(Ref_Window win);
void gft_Window_focus(Ref_Window win);
void gft_Window_minimize(Ref_Window win);
void gft_Window_maximize(Ref_Window win);
void gft_Window_restore(Ref_Window win);
Ref_WebView gft_WebView_new(void);
void gft_WebView_attach(Ref_WebView webview, Ref_Window win);
void gft_WebView_load_url(Ref_WebView webview, const char *url, uint32_t url_len);
void gft_WebView_eval(Ref_WebView webview, const char *script, uint32_t script_len);
Ref_DocumentRef gft_Document_new(void);
Ref_ElementRef gft_Document_create_element(Ref_DocumentRef doc,
const char *local_name,
uint32_t local_name_len);
Ref_CharacterDataRef gft_Document_create_text_node(Ref_DocumentRef doc,
const char *data,
uint32_t data_len);
Ref_CharacterDataRef gft_Document_create_comment(Ref_DocumentRef doc,
const char *data,
uint32_t data_len);
NodeId gft_Node_id(Ref_NodeRef node);
NodeType gft_Node_node_type(Ref_NodeRef node);
Option_Ref_NodeRef gft_Node_parent_node(Ref_NodeRef node);
Option_Ref_NodeRef gft_Node_first_child(Ref_NodeRef node);
Option_Ref_NodeRef gft_Node_last_child(Ref_NodeRef node);
Option_Ref_NodeRef gft_Node_previous_sibling(Ref_NodeRef node);
Option_Ref_NodeRef gft_Node_next_sibling(Ref_NodeRef node);
void gft_Node_append_child(Ref_NodeRef parent, Ref_NodeRef child);
void gft_Node_insert_before(Ref_NodeRef parent, Ref_NodeRef child, Ref_NodeRef before);
void gft_Node_remove_child(Ref_NodeRef parent, Ref_NodeRef child);
Option_Ref_ElementRef gft_Node_query_selector(Ref_NodeRef node,
const char *selector,
uint32_t selector_len);
Ref_Vec_Value gft_Node_query_selector_all(Ref_NodeRef node,
const char *selector,
uint32_t selector_len);
Ref_String gft_CharacterData_data(Ref_CharacterDataRef node);
void gft_CharacterData_set_data(Ref_CharacterDataRef node, const char *data, uint32_t data_len);
Ref_String gft_Element_local_name(Ref_ElementRef el);
Ref_Vec_Value gft_Element_attribute_names(Ref_ElementRef el);
Option_Ref_String gft_Element_attribute(Ref_ElementRef el, const char *att, uint32_t att_len);
void gft_Element_set_attribute(Ref_ElementRef el,
const char *att,
uint32_t att_len,
const char *val,
uint32_t val_len);
void gft_Element_remove_attribute(Ref_ElementRef el, const char *att, uint32_t att_len);
bool gft_Element_matches(Ref_ElementRef el, const char *selector, uint32_t selector_len);
Ref_CssStyleDeclaration gft_Element_style(Ref_ElementRef el);
unsigned int gft_CssStyleDeclaration_length(Ref_CssStyleDeclaration style);
Option_Ref_String gft_CssStyleDeclaration_property_value(Ref_CssStyleDeclaration style,
const char *prop,
uint32_t prop_len);
void gft_CssStyleDeclaration_set_property(Ref_CssStyleDeclaration style,
const char *prop,
uint32_t prop_len,
const char *val,
uint32_t val_len);
void gft_CssStyleDeclaration_remove_property(Ref_CssStyleDeclaration style,
const char *prop,
uint32_t prop_len);
Ref_String gft_CssStyleDeclaration_css_text(Ref_CssStyleDeclaration style);
void gft_CssStyleDeclaration_set_css_text(Ref_CssStyleDeclaration style,
const char *css_text,
uint32_t css_text_len);
Ref_Renderer gft_Renderer_new(Ref_DocumentRef doc, Ref_Window win);
void gft_Renderer_render(Ref_Renderer renderer);
void gft_Renderer_resize(Ref_Renderer renderer, float width, float height);
|
<reponame>zhangfeng0415/Zakker
package com.zte.zakker.common.util;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
/**
* Description: <软键盘的显示与隐藏><br>
* Author: mxdl<br>
* Date: 2018/6/11<br>
* Version: V1.0.0<br>
* Update: <br>
* <ul>
* <li>1.显示软键盘</li>
* <li>2.隐藏软键盘</li>
* </ul>
*/
public class SoftInputUtil {
/**
* 显示软键盘
*
* @param context
*/
public static void showSoftInput(Context context) {
InputMethodManager imm =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); // 显示软键盘
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
/**
* 显示软键盘
*
* @param context
*/
public static void showSoftInput(Context context, View view) {
InputMethodManager imm =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); // 显示软键盘
imm.showSoftInput(view, 0);
}
/**
* 隐藏软键盘
*
* @param context
* @param view
*/
public static void hideSoftInput(Context context, View view) {
InputMethodManager immHide =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); // 隐藏软键盘
immHide.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
} |
/**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.course.style;
import static org.assertj.core.api.Assertions.assertThat;
import static org.olat.test.JunitTestHelper.random;
import org.assertj.core.api.SoftAssertions;
import org.junit.Test;
import org.olat.core.commons.persistence.DB;
import org.olat.test.OlatTestCase;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* Initial date: 25 Jun 2021<br>
* @author uhensler, <EMAIL>, http://www.frentix.com
*
*/
public class CourseStyleServiceTest extends OlatTestCase {
@Autowired
private DB dbInstance;
@Autowired
private CourseStyleService sut;
@Test
public void shouldReturnColorCategoryIfExistingIdentifier() {
ColorCategory colorCategory = sut.createColorCategory(random());
ColorCategory reloaded = sut.getColorCategory(colorCategory.getIdentifier(), ColorCategory.IDENTIFIER_NO_COLOR);
assertThat(reloaded).isEqualTo(colorCategory);
}
@Test
public void shouldReturnFallbackColorCategoryIfIdentifierNotExists() {
ColorCategory fallbackCategory = sut.createColorCategory(ColorCategory.IDENTIFIER_NO_COLOR);
ColorCategory reloaded = sut.getColorCategory(random(), ColorCategory.IDENTIFIER_NO_COLOR);
assertThat(reloaded).isEqualTo(fallbackCategory);
}
@Test
public void shouldMoveUp() {
ColorCategory colorCategory1 = sut.createColorCategory(random());
ColorCategory colorCategory2 = sut.createColorCategory(random());
dbInstance.commitAndCloseSession();
sut.doMove(colorCategory2, true);
dbInstance.commitAndCloseSession();
SoftAssertions softly = new SoftAssertions();
softly.assertThat(sut.getColorCategory(colorCategory1).getSortOrder()).isEqualTo(colorCategory2.getSortOrder());
softly.assertThat(sut.getColorCategory(colorCategory2).getSortOrder()).isEqualTo(colorCategory1.getSortOrder());
softly.assertAll();
}
@Test
public void shouldMoveDown() {
ColorCategory colorCategory1 = sut.createColorCategory(random());
ColorCategory colorCategory2 = sut.createColorCategory(random());
dbInstance.commitAndCloseSession();
sut.doMove(colorCategory1, false);
dbInstance.commitAndCloseSession();
SoftAssertions softly = new SoftAssertions();
softly.assertThat(sut.getColorCategory(colorCategory1).getSortOrder()).isEqualTo(colorCategory2.getSortOrder());
softly.assertThat(sut.getColorCategory(colorCategory2).getSortOrder()).isEqualTo(colorCategory1.getSortOrder());
softly.assertAll();
}
@Test
public void shouldNotMoveUpTopmost() {
ColorCategorySearchParams searchParams = ColorCategorySearchParams.builder().addColorTypes().build();
ColorCategory topmost = sut.getColorCategories(searchParams).stream()
.sorted()
.findFirst().get();
sut.doMove(topmost, true);
dbInstance.commitAndCloseSession();
assertThat(sut.getColorCategory(topmost).getSortOrder()).isEqualTo(topmost.getSortOrder());
}
@Test
public void shouldNotMoveDownLowermost() {
ColorCategory lowermost = sut.createColorCategory(random());
dbInstance.commitAndCloseSession();
sut.doMove(lowermost, false);
dbInstance.commitAndCloseSession();
assertThat(sut.getColorCategory(lowermost).getSortOrder()).isEqualTo(lowermost.getSortOrder());
}
}
|
$.validator.addMethod("validEmail",
function(value, element) {
return this.optional( element ) || /[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]+/.test( value );
},
"Please enter a valid email address"
); |
def partition(head, x):
beforeStart = None
beforeEnd = None
afterStart = None
afterEnd = None
while head is not None:
next = head.next
head.next = None
if head.data < x:
if beforeStart is None:
beforeStart = head
beforeEnd = beforeStart
else:
beforeEnd.next = head
beforeEnd = head
else:
if afterStart is None:
afterStart = head
afterEnd = afterStart
else:
afterEnd.next = head
afterEnd = head
head = next
if beforeStart is None:
return afterStart
beforeEnd.next = afterStart
return beforeStart |
#!/bin/bash
# 2021 Collegiate eCTF
# Launch a test echo deployment
# Ben Janis
#
# (c) 2021 The MITRE Corporation
#
# This source file is part of an example system for MITRE's 2021 Embedded System CTF (eCTF).
# This code is being provided only for educational purposes for the 2021 MITRE eCTF competition,
# and may not meet MITRE standards for quality. Use this code at your own risk!
set -e
set -m
if [ ! -d ".git" ]; then
echo "ERROR: This script must be run from the root of the repo!"
exit 1
fi
export DEPLOYMENT=echo
export SOCK_ROOT=$PWD/socks
export SSS_SOCK=sss.sock
export FAA_SOCK=faa.sock
export MITM_SOCK=mitm.sock
export START_ID=10
export END_ID=12
export SC_PROBE_SOCK=sc_probe.sock
export SC_RECVR_SOCK=sc_recvr.sock
# create deployment
make create_deployment
make add_sed SED=echo_server SCEWL_ID=10 NAME=echo_server
make add_sed SED=echo_client SCEWL_ID=11 NAME=echo_client CUSTOM='TGT_ID=10'
# launch deployment
make deploy
# launch transceiver in background
python3 tools/faa.py $SOCK_ROOT/$FAA_SOCK &
# launch seds detatched
make launch_sed_d NAME=echo_server SCEWL_ID=10
sleep 1
make launch_sed_d NAME=echo_client SCEWL_ID=11
# bring transceiver back into foreground
fg
echo "Killing docker containers..."
docker kill $(docker ps -q) 2>/dev/null
|
### Define here local variables #####
#####################################
# chmod +x run_experiments.sh
# ./run_experiments.sh
#
# Besure to already build the source files in the directories:
# /kelinci_analysis/bin, /kelinci_analysis/bin-instr, /spf_analysis/bin
#
# and create the folder:
# /kelinci_analysis/fuzzer-out/spf/queue
#
# time bound for each run (in hours):
time_bound=18000 #18000 = 5 hours
# number of iterations
number_of_runs=5 #5
# folder with sources
src=/vol/home-vol2/se/nollerya/fuzzing/memoise/issta-experiments/03-regex
# folder for runtime
target=/vol/home-vol2/se/nollerya/fuzzing/experiments/03-regex-10htmllink-badger
# kelinci=1, kelinci-spf=2
execution_mode=2
# server parameter
server_param="Regex resources-byte/popular-regexes/10htmllink-byte @@"
#####################################
echo "Running experiments for:"
echo "execution_mode=$execution_mode"
echo "time_bound=$time_bound"
echo "number_of_runs=$number_of_runs"
echo "src=$src"
echo "target=$target"
echo "server_param=$server_param"
echo ""
for i in `seq 1 $number_of_runs`
do
current_target="$target-$i"
echo "Initializing experiment environment for run=$i"
mkdir "$current_target"
cp -r "$src/kelinci_analysis" "$current_target/"
if [ $execution_mode -eq 2 ]
then
cp -r "$src/spf_analysis" "$current_target/"
mkdir "$current_target/tmp"
cp "/vol/home-vol2/se/nollerya/fuzzing/memoise/KelinciSPFRunner.jar" "$current_target"
cp "$src/config-server-berlin-10link" "$current_target"
fi
echo "Starting server.."
cd "$current_target/kelinci_analysis"
screen -S server -d -m java -cp ./bin-instr/ edu.cmu.sv.kelinci.Kelinci $server_param
echo "Starting AFL.."
screen -S afl -d -m bash -c 'AFL_SKIP_CPUFREQ=1 AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES=1 /vol/home-vol2/se/nollerya/fuzzing/afl-2.51b/afl-fuzz -i ./in_dir -o ./fuzzer-out -c jumps -S afl -t 999999999 /vol/home-vol2/se/nollerya/fuzzing/kelinciwca/fuzzerside/interface @@'
cd "$current_target"
if [ $execution_mode -eq 2 ]
then
echo "Starting SPF.."
export PATH=$PATH:/vol/home-vol2/se/nollerya/fuzzing/z3/build
export LD_LIBRARY_PATH=/vol/home-vol2/se/nollerya/fuzzing/z3/build
screen -S spf -d -m java -Xmx10240m -jar KelinciSPFRunner.jar config-server-berlin-10link
fi
echo "Waiting for $time_bound seconds.."
sleep $time_bound
if [ $execution_mode -eq 2 ]
then
echo "Stopping SPF.."
screen -r spf -X kill
fi
echo "Stopping AFL.."
screen -r afl -X kill
echo "Stopping server.."
screen -r server -X kill
echo "Finished run=$i"
echo ""
done
echo "Done."
|
<filename>liquidsledgehammerMaven/liquid-sledgehammer-command-line/src/main/java/com/coltsoftware/liquidsledgehammer/CSVOutput.java<gh_stars>0
package com.coltsoftware.liquidsledgehammer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import com.coltsoftware.liquidsledgehammer.collections.AliasPathResolver;
import com.coltsoftware.liquidsledgehammer.collections.FinancialTreeNode;
import com.coltsoftware.liquidsledgehammer.model.FinancialTransaction;
import com.coltsoftware.liquidsledgehammer.model.Money;
import com.coltsoftware.liquidsledgehammer.model.SubTransaction;
public class CSVOutput {
private final FinancialTreeNode root;
private final ArrayList<String> data = new ArrayList<String>();
private final AliasPathResolver aliasPathResolver;
public CSVOutput(FinancialTreeNode root,
AliasPathResolver aliasPathResolver, String path, String fileName) {
this.root = root;
this.aliasPathResolver = aliasPathResolver;
File file = new File(new File(path), fileName);
writeHeader();
writeNode(root);
try {
save(file);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void writeHeader() {
StringBuilder sb = new StringBuilder();
sb.append("Date");
sb.append(",");
sb.append("Account");
sb.append(",");
sb.append("Description");
sb.append(",");
sb.append("Value");
sb.append(",");
sb.append("Adjusted Value");
sb.append(",");
sb.append("Balance");
sb.append(",");
sb.append("Group");
sb.append(",");
data.add(sb.toString());
}
private void save(File file) throws FileNotFoundException, IOException {
FileOutputStream fos = new FileOutputStream(file);
PrintStream printStream = new PrintStream(fos, true, "UTF-8");
try {
for (String s : data) {
printStream.append(s);
printStream.append(System.getProperty("line.separator"));
}
} finally {
printStream.close();
fos.close();
}
}
private void writeNode(FinancialTreeNode parent) {
ArrayList<SubTransaction> allTransations = new ArrayList<SubTransaction>();
addSubTransactions(allTransations, root);
Collections.sort(allTransations, new Comparator<SubTransaction>() {
@Override
public int compare(SubTransaction o1, SubTransaction o2) {
return o1.getTransaction().getDate()
.compareTo(o2.getTransaction().getDate());
}
});
Money balance = Money.Zero;
for (SubTransaction subTransaction : allTransations) {
balance = balance.add(subTransaction.getValue());
writeNode(subTransaction, balance);
}
}
private void addSubTransactions(ArrayList<SubTransaction> allTransations,
FinancialTreeNode parent) {
for (FinancialTreeNode child : parent)
addSubTransactions(allTransations, child);
for (SubTransaction subTransaction : parent.getSubTransactions())
allTransations.add(subTransaction);
}
private void writeNode(SubTransaction subTransaction, Money balance) {
FinancialTransaction transaction = subTransaction.getTransaction();
StringBuilder sb = new StringBuilder();
sb.append(transaction.getDate());
sb.append(",");
sb.append(csvEscape(transaction.getSource().getName()));
sb.append(",");
sb.append(csvEscape(transaction.getDescription()));
sb.append(",");
sb.append(csvEncode(transaction.getValue()));
sb.append(",");
sb.append(csvEncode(subTransaction.getValue()));
sb.append(",");
sb.append(csvEncode(balance));
sb.append(",");
sb.append(csvEscape(aliasPathResolver.resolve(subTransaction.getGroup())));
sb.append(",");
data.add(sb.toString());
}
private static String csvEncode(Money value) {
return value.toStringNoSymbol();
}
private static String csvEscape(String csvData) {
return "\"" + csvData.replace("\"", "\"\"") + "\"";
}
}
|
#!/bin/bash
set -e
exec 1>>/var/log/mongo_backup.log 2>&1
echo "$(date -u) start backup"
mongodump --out /raw_files --host $MONGO_HOST:$MONGO_PORT
tar -zcvf /mongo_backup/"$(date '+%Y-%m-%d-%H-%M-%S').tar.gz" /raw_files/
aws s3 sync /mongo_backup/ $S3_DESTINATION
rm -rf /raw_files/* /mongo_backup/*
echo "$(date -u) finished backup"
|
function manageDbConnection() {
let isConnected = false;
return {
openDb: async () => {
if (!isConnected) {
// Simulate opening the database connection
await new Promise((resolve) => {
setTimeout(() => {
isConnected = true;
console.log('Database connection opened');
resolve();
}, 1000);
});
} else {
console.log('Database connection already open');
}
},
closeDb: async () => {
if (isConnected) {
// Simulate closing the database connection
await new Promise((resolve) => {
setTimeout(() => {
isConnected = false;
console.log('Database connection closed');
resolve();
}, 1000);
});
} else {
console.log('Database connection already closed');
}
},
};
} |
package app.cleancode.host;
import java.util.Random;
public class DoorSet {
final boolean[] hasCar;
public DoorSet(Random rand) {
hasCar = new boolean[3];
hasCar[rand.nextInt(hasCar.length)] = true;
}
}
|
const http = require('http');
const server = http.createServer((req, res) => {
// Log the request method and the request URL.
console.log(`${req.method} request for ${req.url}`);
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<h1>Welcome!</h1>
<p>You've reached the home page.</p>
`);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Error - File Not Found');
}
});
server.listen(3000);
console.log('Server listening on port 3000'); |
#!/bin/bash
#
# Copyright 2016 Red Hat, Inc. and/or its affiliates
# and other contributors as indicated by the @author tags.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
set -xe
MVN_VERSION="$1"
MVN_INSTALL_DIR="$2"
if [ ! -f "${MVN_INSTALL_DIR}/lib/maven-artifact-${MVN_VERSION}.jar" ]; then
# remove the older version that can eventually be there
rm -Rf "${MVN_INSTALL_DIR}"
mkdir -p "${MVN_INSTALL_DIR}"
# Find the closest Apache mirror
APACHE_MIRROR="$(curl -sL https://www.apache.org/dyn/closer.cgi?asjson=1 | python -c 'import sys, json; print json.load(sys.stdin)["preferred"]')"
curl -o "${HOME}/apache-maven-$MVN_VERSION-bin.tar.gz" "$APACHE_MIRROR/maven/maven-3/$MVN_VERSION/binaries/apache-maven-$MVN_VERSION-bin.tar.gz"
cd "${MVN_INSTALL_DIR}"
tar -xzf "${HOME}/apache-maven-$MVN_VERSION-bin.tar.gz" --strip 1
chmod +x "${MVN_INSTALL_DIR}/bin/mvn"
else
echo "Using cached Maven ${MVN_VERSION}"
fi
${MVN_INSTALL_DIR}/bin/mvn -version
|
use std::thread;
use std::time::Duration;
struct Engine {
state: String,
}
impl Engine {
fn new() -> Engine {
Engine { state: String::from("off") }
}
fn start(&mut self) {
self.state = String::from("starting");
}
fn update_state(&mut self) {
thread::sleep(Duration::from_secs(2)); // Simulate engine start process
self.state = String::from("running");
}
fn stop(&mut self) {
self.state = String::from("off");
}
fn get_state(&self) -> &str {
&self.state
}
}
fn main() {
let mut car_engine = Engine::new();
println!("Engine state: {}", car_engine.get_state());
car_engine.start();
println!("Engine state: {}", car_engine.get_state());
car_engine.update_state();
println!("Engine state: {}", car_engine.get_state());
car_engine.stop();
println!("Engine state: {}", car_engine.get_state());
} |
#!/usr/bin/env sh
URL=$1
for i in `seq -w 10`
do
STATUS=`curl -s ${URL} -o /dev/null -w '%{http_code}'`
if [ $STATUS = '200' ]
then
echo "[ok] status:${STATUS} ${URL}"
exit 0
fi
echo "[${i}] status:${STATUS} ${URL}"
sleep 1
done
exit 1
|
<gh_stars>1-10
package com.tjhello.lib.billing.base.handler;
import android.app.Activity;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.tjhello.lib.billing.base.anno.BillingName;
import com.tjhello.lib.billing.base.listener.BillingEasyListener;
import com.tjhello.lib.billing.base.utils.BillingEasyLog;
import java.util.List;
/**
* BillingEasy
*一款全新设计的内购聚合,同时支持华为内购与谷歌内购。
*=========================================
* 作者:TJHello
* 日期:2021-07-17
* qq群:425219113
* 仓库地址:https://gitee.com/TJHello/BillingEasy
* ========================================
* 使用该库请遵循Apache License2.0协议,莫要寒了广大开源者的心
*/
public class EmptyHandler extends BillingHandler {
public EmptyHandler(BillingEasyListener mBillingEasyListener) {
super(mBillingEasyListener);
BillingEasyLog.e("没有检测到任何内购库");
}
@NonNull
@Override
public String getProductType(String type) {
return "";
}
@Override
public void onInit(@NonNull Context context) {
}
@Override
public boolean connection(@NonNull BillingEasyListener listener) {
return false;
}
@Override
public void queryProduct(@NonNull List<String> productCodeList, @NonNull String type, @Nullable BillingEasyListener listener) {
}
@Override
public void purchase(@NonNull Activity activity, @NonNull String productCode, @NonNull String type) {
}
@Override
public void consume(@NonNull String purchaseToken, @NonNull BillingEasyListener listener) {
}
@Override
public void acknowledge(@NonNull String purchaseToken, @NonNull BillingEasyListener listener) {
}
@Override
public void queryOrderAsync(@NonNull List<String> typeList, @NonNull BillingEasyListener listener) {
}
@Override
public void queryOrderLocal(@NonNull List<String> typeList, @NonNull BillingEasyListener listener) {
}
@Override
public void queryOrderHistory(@NonNull List<String> typeList, @NonNull BillingEasyListener listener) {
}
@Override
@BillingName
public String getBillingName() {
return BillingName.EMPTY;
}
}
|
#!/bin/bash
set -e
BRANCH=$(git symbolic-ref HEAD | awk -F/ '{print $3}')
OSX_BRANCH=${OSX_BRANCH:-${BRANCH}-osx}
if test -n "$(git status --porcelain)"; then
echo "$(basename $0): Working copy not clean. Exiting."
exit 1
fi
if [[ -n "$(git branch | egrep "^ *$OSX_BRANCH")" ]]; then
git checkout $OSX_BRANCH
if git merge $BRANCH --no-edit; then
git checkout $BRANCH
exit 0
fi
echo "WARNING: Can't merge, falling back to overwriting branch"
git checkout $BRANCH
git branch -D $OSX_BRANCH
fi
git checkout -b $OSX_BRANCH
sed -i '' -e 's/^language: c/language: objective-c/' .travis.yml
git add .travis.yml
git commit -m "change language to objective-c to test OS X"
git checkout $BRANCH
|
package eval
import (
"strings"
)
type Scanner struct {
Reader *strings.Reader
Input string
}
func NewScanner(text string) *Scanner {
reader := strings.NewReader(text)
return &Scanner{Reader: reader, Input: text}
}
func (scanner *Scanner) Mark() int {
return scanner.Reader.Len()
}
func (scanner *Scanner) Reset(mark int) {
r := scanner.Reader
offset := r.Len() - mark
_, err := r.Seek(int64(offset), 1) // relative move
chk(err)
}
func (scanner *Scanner) ReadRune() (ch rune, err error) {
ch, _, err = scanner.Reader.ReadRune()
return ch, err
}
func (scanner *Scanner) UnreadRune() {
err := scanner.Reader.UnreadRune()
chk(err)
}
func (scanner *Scanner) Slice(mark int) (s string) {
begin := len(scanner.Input) - mark
end := scanner.Pos()
return scanner.Input[begin:end]
}
func (scanner *Scanner) Pos() int {
return len(scanner.Input) - scanner.Reader.Len()
}
// Panic if unexpected error
func chk(err error) {
if err != nil {
panic(err)
}
}
|
def caesarCipherEncryptor(string, key):
newLetters = []
newKey = key % 26
for letter in string:
newLetters.append(getEncryptedLetter(letter, newKey))
return "".join(newLetters)
def getEncryptedLetter(letter, key):
newLetterCode = ord(letter) + key
return chr(newLetterCode) if newLetterCode <= 122 else chr(96 + newLetterCode % 122)
string = "hello"
key = 2
encryptedString = caesarCipherEncryptor(string, key)
print(encryptedString) //Output: jgnnq |
import React from 'react';
import Modal from './Modal.js';
import {
Navbar,
Nav,
} from 'react-bootstrap'
export default function _Navbar(){
return(
<Navbar collapseOnSelect expand="lg" bg="info" >
<Navbar.Brand href="#home">SGER</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto">
<Modal _method="Cadastrar"></Modal>
<Modal _method="Login"></Modal>
</Nav>
</Navbar.Collapse>
</Navbar>
)} |
<gh_stars>10-100
package io.opensphere.wms.event;
import io.opensphere.core.common.connection.ServerConfiguration;
import io.opensphere.core.util.PausingTimeBudget;
import io.opensphere.server.customization.ServerCustomization;
import io.opensphere.server.services.ServerConnectionParams;
import io.opensphere.server.source.AuthenticationHelper;
import io.opensphere.server.source.OGCServerSource;
/**
* The Default implementation of the WMSConnectionParams interface.
*/
public class DefaultWmsConnectionParams implements ServerConnectionParams
{
/** The parameters needed to connect to the server. */
private final ServerConfiguration myServerConfig;
/** Special rules for how to configure/format requests to the server. */
private final ServerCustomization myServerCustomization;
/** The ID that uniquely identifies this server. */
private final String myServerId;
/** The Server title. */
private final String myServerTitle;
/** My WMS GetMap override URL. */
private final String myWmsGetMapOverride;
/** My WMS URL. */
private final String myWmsUrl;
/**
* Instantiates a new default WMS connection params.
*
* @param other the other
*/
public DefaultWmsConnectionParams(ServerConnectionParams other)
{
myWmsUrl = other.getWmsUrl();
myWmsGetMapOverride = other.getWmsGetMapOverride();
myServerId = other.getServerId(OGCServerSource.WMS_SERVICE);
myServerTitle = other.getServerTitle();
myServerConfig = other.getServerConfiguration();
myServerCustomization = other.getServerCustomization();
}
@Override
public void failedAuthentication()
{
AuthenticationHelper.failedAuthentication(myServerConfig);
}
@Override
public ServerConfiguration getServerConfiguration()
{
return myServerConfig;
}
@Override
public ServerCustomization getServerCustomization()
{
return myServerCustomization;
}
@Override
public String getServerId(String service)
{
return myServerId;
}
@Override
public String getServerTitle()
{
return myServerTitle;
}
@Override
public PausingTimeBudget getTimeBudget()
{
return null;
}
@Override
public String getWfsUrl()
{
// Don't care about WFS connection info
return null;
}
@Override
public String getWmsGetMapOverride()
{
return myWmsGetMapOverride;
}
@Override
public String getWmsUrl()
{
return myWmsUrl;
}
@Override
public String getWpsUrl()
{
// Don't care about WPS connection info
return null;
}
@Override
public void setTimeBudget(PausingTimeBudget timeBudget)
{
}
}
|
# frozen_string_literal: true
module DatDirec
# Classes which test a set of databases to determine the differences
# between them.
#
# There'll be a protocol description here soon
#
# If I knew more about physics this would be some kind of reference to the
# works of Dirac
module Differs
end
end
Dir[File.dirname(__FILE__) + "/differs/*.rb"].sort.each { |f| require f }
|
const is = require("@sindresorhus/is");
const child1 = require("./parent/child1.js");
module.exports = {}; |
<filename>06. Filters and User Authentication/Exercise/Resident Evil Part III/src/main/java/org/softuni/residentevil/domain/converters/CreatorConverter.java
package org.softuni.residentevil.domain.converters;
import org.softuni.residentevil.domain.enums.Creator;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class CreatorConverter implements AttributeConverter<Creator, String> {
@Override
public String convertToDatabaseColumn(Creator creator) {
return creator == null ? null : creator.getLabel();
}
@Override
public Creator convertToEntityAttribute(String label) {
return Creator.fromLabel(label);
}
}
|
#!/bin/sh
pod spec lint SlideMenuControllerSwift.podspec
|
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { stubUserManagementDetailServiceProvider } from '../services/user-management-detail.service.stub';
import { UserManagementDetailGuard } from './user-management-detail.guard';
describe('UserManagementDetailGuard', () => {
let guard: UserManagementDetailGuard;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
providers: [stubUserManagementDetailServiceProvider],
});
guard = TestBed.inject(UserManagementDetailGuard);
});
it('should be created', () => {
expect(guard).toBeTruthy();
});
});
|
<reponame>nikse/react-mobiledoc-editor<filename>src/components/SectionButton.js
import PropTypes from 'prop-types';
import React from 'react';
import titleCase from '../utils/titleCase';
import { ReactMobileDocContext } from './Context';
const SectionButton = ({
tag = '',
type = 'button',
children = titleCase(tag),
className,
activeClassName = 'active',
...props
}) => {
return (
<ReactMobileDocContext.Consumer>
{({ editor, activeSectionTags = [] }) => {
const onClick = () => editor.toggleSection(tag);
className = [
className,
activeSectionTags.indexOf(tag.toLowerCase()) > -1 && activeClassName,
]
.filter(Boolean)
.join(' ');
props = { type, ...props, onClick, className };
return <button {...props}>{children}</button>;
}}
</ReactMobileDocContext.Consumer>
);
};
SectionButton.propTypes = {
tag: PropTypes.string.isRequired,
children: PropTypes.node,
};
export default SectionButton;
|
def product_of_list(num_list):
product = 1
for num in num_list:
product *= num
return product |
<reponame>jasonroelofs/simple_aws<filename>samples/s3.rb<gh_stars>1-10
$: << File.expand_path("../../lib", __FILE__)
require 'simple_aws/s3'
##
# Expects your Amazon keys to be in the environment, something like
#
# export AWS_KEY="KEY"
# export AWS_SECRET="SECRET"
#
# Usage:
# ruby sample/s3.rb [bucket name] [file to use]
#
# This script will upload the file, show that the file is up, then remove the file
##
def bad_usage
puts ""
puts "Usage:"
puts " ruby sample/s3.rb [bucket name] [file to use]"
exit 1
end
s3 = SimpleAWS::S3.new ENV["AWS_KEY"], ENV["AWS_SECRET"]
s3.debug!
bucket_name = ARGV[0]
file_name = ARGV[1]
puts "All buckets in this account:", ""
s3.get("/").buckets.bucket.each do |bucket|
puts bucket.name
end
puts "", "First 10 files in #{bucket_name}:", ""
bad_usage unless bucket_name
s3.get("/", :bucket => bucket_name, :params => {"max-keys" => 10}).tap do |response|
# Amazon doesn't include Contents if there are no files
# Amazon also includes just one entry if there's only one file to be found,
# where as if there's > 1 then SimpleAWS will be given a proper array.
# Gotta love XML!
if response["Contents"]
[response.contents].flatten.each do |entry|
puts entry.key
end
end
end
puts "", "Uploading #{file_name} to #{bucket_name}:", ""
bad_usage unless file_name
uploaded_file_name = File.basename file_name
p s3.put(uploaded_file_name, :bucket => bucket_name, :file => File.open(file_name))
puts "", "Checking that the file now exists...", ""
p s3.head(uploaded_file_name, :bucket => bucket_name)
puts "", "Getting file again", ""
p s3.get(uploaded_file_name, :bucket => bucket_name,
:params => {
"response-content-disposition" => "attachment",
"response-content-type" => "text/ruby",
"response-expires" => "never" })
puts "", "Signed, expiring URL for this resource: ", ""
puts s3.url_for(uploaded_file_name, :bucket => bucket_name,
:expires => Time.now.to_i + 120,
:params => { "response-content-disposition" => "attachment" })
puts "", "Deleting the file from S3", ""
p s3.delete(uploaded_file_name, :bucket => bucket_name)
puts "", "Checking that file is no longer in S3...", ""
begin
p s3.head(uploaded_file_name, :bucket => bucket_name)
rescue => ex
puts "Not found: #{ex.message}"
end
|
/// <reference path="../../node_modules/@citizenfx/client/natives_universal.d.ts"/>
export const config = {
RADIUS: 350.0,
SPAWN_LOCATION: {x: -1336.1760, y: -3044.0562, z: 13.9444}
}; |
import {
Chromosome,
FitnessFn,
FitnessScorePromise,
Genotype,
} from "../types.ts";
import { assertEquals } from "./deps.ts";
import { evaluate } from "./evaluate.ts";
import { getChromosomeWithDefaults } from "./chromosome.ts";
Deno.test("evaluate", async () => {
const population = [
getChromosomeWithDefaults({ genes: [0, 1, 1, 1] }),
getChromosomeWithDefaults({ genes: [1, 0, 0, 0] }),
getChromosomeWithDefaults({ genes: [1, 1, 1, 1] }),
];
const sumGenes = (genes: Genotype<number>) =>
genes.reduce((total, n) => n + total, 0);
const computeFitness: FitnessFn<number> = (
genotype: Chromosome<number>,
): FitnessScorePromise =>
new Promise((resolve) => resolve(sumGenes(genotype.genes)));
const solution = await evaluate(population, computeFitness);
assertEquals(solution, [
{ genes: [1, 1, 1, 1], size: 4, fitness: 4, age: 1 },
{ genes: [0, 1, 1, 1], size: 4, fitness: 3, age: 1 },
{ genes: [1, 0, 0, 0], size: 4, fitness: 1, age: 1 },
]);
const solutionAsc = await evaluate(population, computeFitness, {
fitnessSortDirection: "ASC",
});
assertEquals(
solutionAsc,
[
{ genes: [1, 0, 0, 0], size: 4, fitness: 1, age: 1 },
{ genes: [0, 1, 1, 1], size: 4, fitness: 3, age: 1 },
{ genes: [1, 1, 1, 1], size: 4, fitness: 4, age: 1 },
],
);
const solutionAgeTracking = await evaluate(solutionAsc, computeFitness);
assertEquals(solutionAgeTracking, [
{ genes: [1, 1, 1, 1], size: 4, fitness: 4, age: 2 },
{ genes: [0, 1, 1, 1], size: 4, fitness: 3, age: 2 },
{ genes: [1, 0, 0, 0], size: 4, fitness: 1, age: 2 },
]);
});
|
function longestCommonPrefix(strs) {
if (!strs.length) return '';
let prefix = strs[0];
for (let i = 0; i < strs.length; i++) {
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.substring(0, prefix.length - 1);
}
}
return prefix;
}
let strs = ['flower', 'flow', 'flight'];
console.log(longestCommonPrefix(strs)); // Output: 'fl' |
#!/bin/bash
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
script_dir=`dirname $0`
LIB=$script_dir/../lib
CLASSPATH=$script_dir/../target/classes:"$LIB"/helix-core-0.6.4-SNAPSHOT.jar:"$LIB"/rabbitmq-client.jar:"$LIB"/commons-cli-1.1.jar:"$LIB"/commons-io-1.2.jar:"$LIB"/commons-math-2.1.jar:"$LIB"/jackson-core-asl-1.8.5.jar:"$LIB"/jackson-mapper-asl-1.8.5.jar:"$LIB"/log4j-1.2.15.jar:"$LIB"/org.restlet-1.1.10.jar:"$LIB"/zkclient-0.1.jar:"$LIB"/zookeeper-3.3.4.jar
# echo $CLASSPATH
java -cp "$CLASSPATH" org.apache.helix.filestore.StartClusterManager $@
|
#! /bin/bash
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
source ~/cpo200/config
sed -i \
-e s/'<guestbook-project-id>'/$DEVSHELL_PROJECT_ID/g \
-e s/'<your-default-zone>'/$CPO200_ZONE/ \
-e s/'<guestbook-sql-connection-name>'/$CPO200_SQL_CONNECTION_NAME/ \
-e s/'<guestbook-sql-password>'/$CPO200_SQL_PW/ \
-e s/'<guestbook-external-ip-address>'/$CPO200_GB_DM_IP/ \
-e s/'<startup-scripts-bucket>'/$CPO200_SCRIPTS_BUCKET/ \
guestbook.yaml |
<reponame>tenebrousedge/ruby-packer
require File.expand_path('../spec_helper', __FILE__)
load_extension("float")
describe "CApiFloatSpecs" do
before :each do
@f = CApiFloatSpecs.new
end
describe "rb_float_new" do
it "creates a new float" do
((@f.new_zero - 0).abs < 0.000001).should == true
((@f.new_point_five - 0.555).abs < 0.000001).should == true
end
end
describe "RFLOAT_VALUE" do
it "returns the C double value of the Float" do
@f.RFLOAT_VALUE(2.3).should == 2.3
end
end
describe "rb_Float" do
it "creates a new Float from a String" do
f = @f.rb_Float("101.99")
f.should be_kind_of(Float)
f.should eql(101.99)
end
end
end
|
import re
def validate_phone_number(phone_num):
phone_num_pattern = r"^\+[1-9][0-9]{10,12}$"
if re.search(phone_num_pattern, phone_num):
return True
return False
phone_num = '+1 (123) 456-78-90'
print(validate_phone_number(phone_num)) |
#!/bin/sh
# CYBERWATCH SAS - 2017
#
# Security fix for USN-2890-2
#
# Security announcement date: 2016-02-01 00:00:00 UTC
# Script generation date: 2017-01-01 21:05:09 UTC
#
# Operating System: Ubuntu 14.04 LTS
# Architecture: i686
#
# Vulnerable packages fix on version:
# - linux-image-4.2.0-27-lowlatency:4.2.0-27.32~14.04.1
# - linux-image-4.2.0-27-generic-lpae:4.2.0-27.32~14.04.1
# - linux-image-4.2.0-27-powerpc-e500mc:4.2.0-27.32~14.04.1
# - linux-image-4.2.0-27-powerpc64-emb:4.2.0-27.32~14.04.1
# - linux-image-4.2.0-27-powerpc-smp:4.2.0-27.32~14.04.1
# - linux-image-4.2.0-27-powerpc64-smp:4.2.0-27.32~14.04.1
# - linux-image-4.2.0-27-generic:4.2.0-27.32~14.04.1
#
# Last versions recommanded by security team:
# - linux-image-4.2.0-27-lowlatency:4.2.0-27.32~14.04.1
# - linux-image-4.2.0-27-generic-lpae:4.2.0-27.32~14.04.1
# - linux-image-4.2.0-27-powerpc-e500mc:4.2.0-27.32~14.04.1
# - linux-image-4.2.0-27-powerpc64-emb:4.2.0-27.32~14.04.1
# - linux-image-4.2.0-27-powerpc-smp:4.2.0-27.32~14.04.1
# - linux-image-4.2.0-27-powerpc64-smp:4.2.0-27.32~14.04.1
# - linux-image-4.2.0-27-generic:4.2.0-27.32~14.04.1
#
# CVE List:
# - CVE-2013-7446
# - CVE-2015-7513
# - CVE-2015-7550
# - CVE-2015-7990
# - CVE-2015-8374
# - CVE-2015-8543
# - CVE-2015-8569
# - CVE-2015-8575
# - CVE-2015-8787
#
# More details:
# - https://www.cyberwatch.fr/vulnerabilites
#
# Licence: Released under The MIT License (MIT), See LICENSE FILE
sudo apt-get install --only-upgrade linux-image-4.2.0-27-lowlatency=4.2.0-27.32~14.04.1 -y
sudo apt-get install --only-upgrade linux-image-4.2.0-27-generic-lpae=4.2.0-27.32~14.04.1 -y
sudo apt-get install --only-upgrade linux-image-4.2.0-27-powerpc-e500mc=4.2.0-27.32~14.04.1 -y
sudo apt-get install --only-upgrade linux-image-4.2.0-27-powerpc64-emb=4.2.0-27.32~14.04.1 -y
sudo apt-get install --only-upgrade linux-image-4.2.0-27-powerpc-smp=4.2.0-27.32~14.04.1 -y
sudo apt-get install --only-upgrade linux-image-4.2.0-27-powerpc64-smp=4.2.0-27.32~14.04.1 -y
sudo apt-get install --only-upgrade linux-image-4.2.0-27-generic=4.2.0-27.32~14.04.1 -y
|
#! /bin/bash
# build the StandAlone app and all it's dependencies
make -C StandAlone
# so we can find the shared library
LD_LIBRARY_PATH=`pwd`/glslang/MachineIndependent/lib:${LD_LIBRARY_PATH}
export LD_LIBRARY_PATH
# run using test data
cd StandAlone
./StandAlone -i sample.vert sample.frag
|
#!/bin/bash
#
# LICENSE UPL 1.0
#
# Copyright (c) 1982-2018 Oracle and/or its affiliates. All rights reserved.
#
# Since: July, 2018
# Author: gerald.venzl@oracle.com
# Description: Installs Oracle database software
#
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
#
echo 'INSTALLER: Started up'
# get up to date
yum upgrade -y
echo 'INSTALLER: System updated'
# fix locale warning
yum reinstall -y glibc-common
echo LANG=en_US.utf-8 >> /etc/environment
echo LC_ALL=en_US.utf-8 >> /etc/environment
echo 'INSTALLER: Locale set'
# set system time zone
sudo timedatectl set-timezone $SYSTEM_TIMEZONE
echo "INSTALLER: System time zone set to $SYSTEM_TIMEZONE"
# Install Oracle Database prereq and openssl packages
yum install -y oracle-database-preinstall-18c openssl
echo 'INSTALLER: Oracle preinstall and openssl complete'
# create directories
mkdir -p $ORACLE_HOME && \
mkdir -p /u01/app && \
ln -s $ORACLE_BASE /u01/app/oracle
echo 'INSTALLER: Oracle directories created'
# set environment variables
echo "export ORACLE_BASE=$ORACLE_BASE" >> /home/oracle/.bashrc && \
echo "export ORACLE_HOME=$ORACLE_HOME" >> /home/oracle/.bashrc && \
echo "export ORACLE_SID=$ORACLE_SID" >> /home/oracle/.bashrc && \
echo "export PATH=\$PATH:\$ORACLE_HOME/bin" >> /home/oracle/.bashrc
echo 'INSTALLER: Environment variables set'
# Install Oracle
unzip /vagrant/LINUX.X64_180000_db_home.zip -d $ORACLE_HOME/
cp /vagrant/ora-response/db_install.rsp.tmpl /vagrant/ora-response/db_install.rsp
sed -i -e "s|###ORACLE_BASE###|$ORACLE_BASE|g" /vagrant/ora-response/db_install.rsp && \
sed -i -e "s|###ORACLE_HOME###|$ORACLE_HOME|g" /vagrant/ora-response/db_install.rsp && \
sed -i -e "s|###ORACLE_EDITION###|$ORACLE_EDITION|g" /vagrant/ora-response/db_install.rsp && \
chown oracle:oinstall -R $ORACLE_BASE
su -l oracle -c "yes | $ORACLE_HOME/runInstaller -silent -ignorePrereqFailure -waitforcompletion -responseFile /vagrant/ora-response/db_install.rsp"
$ORACLE_BASE/oraInventory/orainstRoot.sh
$ORACLE_HOME/root.sh
rm /vagrant/ora-response/db_install.rsp
echo 'INSTALLER: Oracle software installed'
# create sqlnet.ora, listener.ora and tnsnames.ora
su -l oracle -c "mkdir -p $ORACLE_HOME/network/admin"
su -l oracle -c "echo 'NAME.DIRECTORY_PATH= (TNSNAMES, EZCONNECT, HOSTNAME)' > $ORACLE_HOME/network/admin/sqlnet.ora"
# Listener.ora
su -l oracle -c "echo 'LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
(ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))
)
)
DEDICATED_THROUGH_BROKER_LISTENER=ON
DIAG_ADR_ENABLED = off
' > $ORACLE_HOME/network/admin/listener.ora"
su -l oracle -c "echo '$ORACLE_SID=localhost:1521/$ORACLE_SID' > $ORACLE_HOME/network/admin/tnsnames.ora"
su -l oracle -c "echo '$ORACLE_PDB=
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = $ORACLE_PDB)
)
)' >> $ORACLE_HOME/network/admin/tnsnames.ora"
# Start LISTENER
su -l oracle -c "lsnrctl start"
echo 'INSTALLER: Listener created'
# Create database
# Auto generate ORACLE PWD if not passed on
export ORACLE_PWD=${ORACLE_PWD:-"`openssl rand -base64 8`1"}
cp /vagrant/ora-response/dbca.rsp.tmpl /vagrant/ora-response/dbca.rsp
sed -i -e "s|###ORACLE_SID###|$ORACLE_SID|g" /vagrant/ora-response/dbca.rsp && \
sed -i -e "s|###ORACLE_PDB###|$ORACLE_PDB|g" /vagrant/ora-response/dbca.rsp && \
sed -i -e "s|###ORACLE_CHARACTERSET###|$ORACLE_CHARACTERSET|g" /vagrant/ora-response/dbca.rsp && \
sed -i -e "s|###ORACLE_PWD###|$ORACLE_PWD|g" /vagrant/ora-response/dbca.rsp
su -l oracle -c "dbca -silent -createDatabase -responseFile /vagrant/ora-response/dbca.rsp"
su -l oracle -c "sqlplus / as sysdba <<EOF
ALTER PLUGGABLE DATABASE $ORACLE_PDB SAVE STATE;
exit;
EOF"
rm /vagrant/ora-response/dbca.rsp
echo 'INSTALLER: Database created'
sed '$s/N/Y/' /etc/oratab | sudo tee /etc/oratab > /dev/null
echo 'INSTALLER: Oratab configured'
# configure systemd to start oracle instance on startup
sudo cp /vagrant/scripts/oracle-rdbms.service /etc/systemd/system/
sudo sed -i -e "s|###ORACLE_HOME###|$ORACLE_HOME|g" /etc/systemd/system/oracle-rdbms.service
sudo systemctl daemon-reload
sudo systemctl enable oracle-rdbms
sudo systemctl start oracle-rdbms
echo "INSTALLER: Created and enabled oracle-rdbms systemd's service"
sudo cp /vagrant/scripts/setPassword.sh /home/oracle/ && \
sudo chmod a+rx /home/oracle/setPassword.sh
echo "INSTALLER: setPassword.sh file setup";
echo "ORACLE PASSWORD FOR SYS, SYSTEM AND PDBADMIN: $ORACLE_PWD";
echo "INSTALLER: Installation complete, database ready to use!";
|
import React, { useState} from 'react';
import { StyleSheet, View, FlatList } from 'react-native';
import { SignIn, FriendsList } from './components';
import { Message } from './types';
export default function App() {
const [isSignedIn, setIsSignedIn] = useState(false);
const [friends, setFriends] = useState<string[]>([]);
const [messages, setMessages] = useState<Message[]>([]);
// Render the app with appropriate components
return (
<View style={styles.container}>
{isSignedIn ? (
<>
<FriendsList
friends={friends}
onFriendSelected={handleFriendSelected}
/>
<FlatList
data={messages}
renderItem={({ item }) => (
<Message message={item.message} from={item.from} to={item.to} />
)}
keyExtractor={(item) => item.id}
/>
</>
) : (
<SignIn onSignIn={handleSignIn} />
)}
</View>
);
}
// Component styles
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
}); |
<reponame>pjmolina/event-backend
angular.module('myApp').controller('SelectSponsorController', ['$http', '$scope', '$location', '$translate', '$q', '$timeout', 'NavigationService', 'EntityUtilService', 'SponsorService', function($http, $scope, $location, $translate, $q, $timeout, NavigationService, EntityUtilService, SponsorService) {
$scope.dataList = [];
$scope.selectionContext = {
allSelected: false,
noneSelected: true
};
$scope.searchContext = {
sort: {},
pageSize: 12,
currentPage: 1,
searchText: '',
totalItems: 0,
isSearching: false,
criteria: null
};
$scope.sortBy = function(field) {
EntityUtilService.sortBy($scope.searchContext, field);
$scope.refresh();
};
$scope.select = function(retData) {
NavigationService.setReturnData({parent: $scope.parent, entity: retData});
$location.path(NavigationService.getReturnUrl());
};
$scope.loadCurrentPage = function () {
$scope.dataReceived = false;
$scope.searchContext.isSearching = true;
SponsorService.getList({
'page' : $scope.searchContext.currentPage,
'pageSize' : $scope.searchContext.pageSize,
'searchText' : $scope.searchContext.searchText,
'sort' : $scope.searchContext.sort,
'criteria' : $scope.searchContext.criteria
})
.then(onLoadData)
.catch(onError)
.finally(onLoadDataFinally);
};
function onLoadData(httpResponse) {
$scope.dataList = httpResponse.data;
}
function onError(err) {
$scope.error = err;
}
function onLoadDataFinally() {
$scope.searchContext.isSearching = false;
$scope.dataReceived = true;
$scope.$digest();
}
$scope.updateRecordCount = function () {
$scope.searchContext.totalItems = null;
SponsorService.getCount({
'searchText' : $scope.searchContext.searchText,
'criteria' : $scope.searchContext.criteria
})
.then(onUpdateCount, onError);
};
function onUpdateCount(httpResponse) {
$scope.searchContext.totalItems = Number(httpResponse.data);
}
$scope.refresh = function () {
if(NavigationService.getState().criteria) {
$scope.searchContext.criteria = NavigationService.getState().criteria;
}
$scope.updateRecordCount();
$scope.searchContext.currentPage = 1;
$scope.loadCurrentPage();
};
function init() {
var state = NavigationService.getState();
if (state) {
$scope.parent = state.parent;
if(state.criteria) {
$scope.searchContext.criteria = state.criteria;
}
}
$scope.refresh();
}
init();
}]);
|
<reponame>maurov/xraysloth
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Script for installing packages on Microsoft Windows using wheels
from [GOHLKE WINDOWS REPOSITORY](https://www.lfd.uci.edu/~gohlke/pythonlibs/)
- Steps to build this environment with Conda from the 'base':
(base)$ conda create -n py37w python=3.7
(base)$ conda activate py37w
"""
try:
from gohlkegrabber import GohlkeGrabber
except ImportError:
print("gohlkegrabber not installed -> 'pip install gohlkegrabber'")
pass
import subprocess
import tempfile
import shutil
PACKAGES = ('numpy', 'cffi', 'pyopencl', 'pyopengl', 'h5py')
def install_packages(packages, pkgs_dir=None, remove_pkgs_dir=False):
"""main script"""
_py = '3.7'
_platform = 'win_amd64'
if pkgs_dir is None:
pkgs_dir = tempfile.mkdtemp(prefix='py37w')
print(f"Temporary packages directory is: {pkgs_dir}")
remove_pkgs_dir = True
gg = GohlkeGrabber()
for pkg in packages:
print(f"retreiving {pkg}...")
try:
pkwhl = gg.retrieve(pkgs_dir, pkg, python=_py, platform=_platform)
except KeyError:
print(f"{pkg} not found")
continue
subprocess.call(f"pip install {pkwhl[0]}")
if remove_pkgs_dir:
shutil.rmtree(pkgs_dir)
print("temporary directory removed")
if __name__ == "__main__":
print("To install Windows packages from Gohlke, manually run 'install_packages()' function")
# install_packages(PACKAGES)
pass
|
import * as actionType from "./action-types";
const initialState = {};
const rootReducer = (state = initialState, action) => {
let newState = Object.assign({}, state);
switch (action.type) {
case actionType.SET_LIBRARY:
{
newState.library = action.payload;
newState.libraryVersion++;
}
return newState;
case actionType.SET_DATASOURCE:
{
newState.datasourceId = action.payload.datasourceId;
newState.pageDatasourceId = action.payload.pageDatasourceId;
newState.pageDatasourceName = action.payload.pageDatasourceName;
newState.pageDatasourceParams = action.payload.pageDatasourceParams;
}
return newState;
default:
return state;
}
};
export default rootReducer;
|
#!/usr/bin/env bash
#
# For Xamarin, change some constants located in some class of the app.
# In this sample, suppose we have an AppConstant.cs class in shared folder with follow content:
#
# namespace Core
# {
# public class AppConstant
# {
# public const string ApiUrl = "https://CMS_MyApp-Eur01.com/api";
# }
# }
#
# Suppose in our project exists two branches: master and develop.
# We can release app for production API in master branch and app for test API in develop branch.
# We just need configure this behaviour with environment variable in each branch :)
#
# The same thing can be perform with any class of the app.
#
# AN IMPORTANT THING: FOR THIS SAMPLE YOU NEED DECLARE API_URL ENVIRONMENT VARIABLE IN APP CENTER BUILD CONFIGURATION.
if [ ! -n "$API_URL" ]
then
echo "You need define the API_URL variable in App Center"
exit
fi
APP_CONSTANT_FILE=$APPCENTER_SOURCE_DIRECTORY/Core/AppConstant.cs
if [ -e "$APP_CONSTANT_FILE" ]
then
echo "Updating ApiUrl to $API_URL in AppConstant.cs"
sed -i '' 's#ApiUrl = "[-A-Za-z0-9:_./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE
echo "File content:"
cat $APP_CONSTANT_FILE
fi
|
VERSION = (0, 10)
__version__ = '.'.join(map(str, VERSION))
__author__ = 'Ministry of Justice Digital & Technology'
|
#!/bin/bash
#===============================================
# Description: DIY script part 2
# File name: diy-part2.sh
# Lisence: MIT
# Author: P3TERX
# Blog: https://p3terx.com
#===============================================
# 修改默认IP
sed -i 's/192.168.1.1/192.168.0.110/g' package/base-files/files/bin/config_generate
# Autocore
sed -i 's/TARGET_rockchip/TARGET_rockchip\|\|TARGET_armvirt/g' package/lean/autocore/Makefile
# Cpufreq
sed -i 's/LUCI_DEPENDS.*/LUCI_DEPENDS:=\@\(arm\|\|aarch64\)/g' feeds/luci/applications/luci-app-cpufreq/Makefile
sed -i 's/services/system/g' feeds/luci/applications/luci-app-cpufreq/luasrc/controller/cpufreq.lua
# 移除重复软件包
rm -rf feeds/packages/admin/netdata
rm -rf feeds/luci/themes/luci-theme-argon
rm -rf feeds/luci/themes/luci-theme-netgear
rm -rf feeds/luci/applications/luci-app-netdata
rm -rf feeds/luci/applications/luci-app-wrtbwmon
rm -rf feeds/luci/applications/luci-app-dockerman
# 添加额外软件包
git clone https://github.com/jerrykuku/luci-app-jd-dailybonus.git package/luci-app-jd-dailybonus
git clone https://github.com/jerrykuku/lua-maxminddb.git package/lua-maxminddb
git clone https://github.com/jerrykuku/luci-app-vssr.git package/luci-app-vssr
git clone https://github.com/kongfl888/luci-app-adguardhome.git package/luci-app-adguardhome
git clone https://github.com/esirplayground/luci-app-poweroff package/luci-app-poweroff
svn co https://github.com/lisaac/luci-app-dockerman/trunk/applications/luci-app-dockerman package/luci-app-dockerman
svn co https://github.com/sirpdboy/sirpdboy-package/trunk/luci-app-smartdns package/luci-app-smartdns
# 科学上网插件依赖
svn co https://github.com/vernesong/OpenClash/trunk/luci-app-openclash package/luci-app-openclash
# 编译 po2lmo (如果有po2lmo可跳过)
pushd package/luci-app-openclash/tools/po2lmo
make && sudo make install
popd
svn co https://github.com/xiaorouji/openwrt-passwall/trunk/brook package/brook
svn co https://github.com/xiaorouji/openwrt-passwall/trunk/chinadns-ng package/chinadns-ng
svn co https://github.com/xiaorouji/openwrt-passwall/trunk/tcping package/tcping
svn co https://github.com/xiaorouji/openwrt-passwall/trunk/trojan-go package/trojan-go
svn co https://github.com/xiaorouji/openwrt-passwall/trunk/trojan-plus package/trojan-plus
svn co https://github.com/xiaorouji/openwrt-passwall/branches/luci/luci-app-passwall package/luci-app-passwall
svn co https://github.com/xiaorouji/openwrt-passwall/trunk/xray-core package/xray-core
svn co https://github.com/xiaorouji/openwrt-passwall/trunk/xray-plugin package/xray-plugin
svn co https://github.com/xiaorouji/openwrt-passwall/trunk/ssocks package/ssocks
svn co https://github.com/xiaorouji/openwrt-passwall/trunk/hysteria package/hysteria
svn co https://github.com/xiaorouji/openwrt-passwall/trunk/v2ray-plugin package/v2ray-plugin
svn co https://github.com/xiaorouji/openwrt-passwall/trunk/v2ray-core package/v2ray-core
svn co https://github.com/fw876/helloworld/trunk/naiveproxy package/naiveproxy
svn co https://github.com/fw876/helloworld/trunk/shadowsocks-rust package/shadowsocks-rust
svn co https://github.com/fw876/helloworld/trunk/shadowsocksr-libev package/shadowsocksr-libev
svn co https://github.com/fw876/helloworld/trunk/luci-app-ssr-plus package/luci-app-ssr-plus
svn co https://github.com/fw876/helloworld/trunk/simple-obfs package/simple-obfs
svn co https://github.com/fw876/helloworld/trunk/trojan package/trojan
# Themes
svn co https://github.com/kenzok8/openwrt-packages/trunk/luci-theme-edge package/luci-theme-edge
svn co https://github.com/rosywrt/luci-theme-rosy/trunk/luci-theme-rosy package/luci-theme-rosy
svn co https://github.com/haiibo/packages/trunk/luci-theme-darkmatter package/luci-theme-darkmatter
svn co https://github.com/haiibo/packages/trunk/luci-theme-atmaterial package/luci-theme-atmaterial
svn co https://github.com/haiibo/packages/trunk/luci-theme-opentomcat package/luci-theme-opentomcat
svn co https://github.com/haiibo/packages/trunk/luci-theme-netgear package/luci-theme-netgear
git clone https://github.com/xiaoqingfengATGH/luci-theme-infinityfreedom package/luci-theme-infinityfreedom
git clone -b 18.06 https://github.com/jerrykuku/luci-theme-argon.git package/luci-theme-argon
git clone https://github.com/jerrykuku/luci-app-argon-config package/luci-app-argon-config
git clone https://github.com/sirpdboy/luci-theme-opentopd package/luci-theme-opentopd
git clone https://github.com/thinktip/luci-theme-neobird package/luci-theme-neobird
# 晶晨宝盒
svn co https://github.com/ophub/luci-app-amlogic/trunk/luci-app-amlogic package/luci-app-amlogic
sed -i "s|https.*/OpenWrt|https://github.com/haiibo/OpenWrt|g" package/luci-app-amlogic/root/etc/config/amlogic
sed -i "s|opt/kernel|https://github.com/ophub/kernel/tree/main/pub/stable|g" package/luci-app-amlogic/root/etc/config/amlogic
sed -i "s|ARMv8|ARMv8_MINI|g" package/luci-app-amlogic/root/etc/config/amlogic
# 实时监控
svn co https://github.com/sirpdboy/sirpdboy-package/trunk/luci-app-netdata package/luci-app-netdata
svn co https://github.com/sirpdboy/sirpdboy-package/trunk/netdata package/netdata
# 流量监控
svn co https://github.com/sirpdboy/sirpdboy-package/trunk/luci-app-wrtbwmon package/luci-app-wrtbwmon
svn co https://github.com/sirpdboy/sirpdboy-package/trunk/wrtbwmon package/wrtbwmon
# 修改makefile
find package/*/ -maxdepth 2 -path "*/Makefile" | xargs -i sed -i 's/include\ \.\.\/\.\.\/luci\.mk/include \$(TOPDIR)\/feeds\/luci\/luci\.mk/g' {}
find package/*/ -maxdepth 2 -path "*/Makefile" | xargs -i sed -i 's/include\ \.\.\/\.\.\/lang\/golang\/golang\-package\.mk/include \$(TOPDIR)\/feeds\/packages\/lang\/golang\/golang\-package\.mk/g' {}
find package/*/ -maxdepth 2 -path "*/Makefile" | xargs -i sed -i 's/PKG_SOURCE_URL:=\@GHREPO/PKG_SOURCE_URL:=https:\/\/github\.com/g' {}
find package/*/ -maxdepth 2 -path "*/Makefile" | xargs -i sed -i 's/PKG_SOURCE_URL:=\@GHCODELOAD/PKG_SOURCE_URL:=https:\/\/codeload\.github\.com/g' {}
# 调整Dockerman到服务菜单
sed -i 's/"admin"/"admin","services"/g' package/luci-app-dockerman/luasrc/controller/*.lua
sed -i 's/"admin/"admin\/services/g' package/luci-app-dockerman/luasrc/model/*.lua
sed -i 's/"admin/"admin\/services/g' package/luci-app-dockerman/luasrc/model/cbi/dockerman/*.lua
sed -i 's/"admin/"admin\/services/g' package/luci-app-dockerman/luasrc/view/dockerman/*.htm
sed -i 's/"admin/"admin\/services/g' package/luci-app-dockerman/luasrc/view/dockerman/cbi/*.htm
# 修改插件名字
sed -i 's/"Argon 主题设置"/"Argon 设置"/g' `grep "Argon 主题设置" -rl ./`
sed -i 's/"Docker"/"Docker 容器"/g' `grep "Docker" -rl ./`
sed -i 's/"带宽监控"/"监控"/g' `grep "带宽监控" -rl ./`
sed -i 's/"UPnP"/"UPnP 设置"/g' `grep "UPnP" -rl ./`
./scripts/feeds update -a
./scripts/feeds install -a
|
<gh_stars>10-100
import React from "react";
import { View,TouchableOpacity} from "react-native";
import { Cell } from "./cell";
import {sum} from "../../utils/validators"
import styles from "./styles";
export const Row = props =>{
const { data,widthArr,height,backgroundColor,rowNumber,toggleEditModal } = props;
let width = widthArr ? sum(widthArr) : 0;
return data.length ? (
<TouchableOpacity
style={[styles.row, height && { height }, width && { width }, backgroundColor && {backgroundColor}]}
onPress ={()=> typeof toggleEditModal ==='function' && toggleEditModal(data,rowNumber)}
key={rowNumber.toString()}
>
{data.map((item, i) => {
const wth = widthArr && widthArr[i];
return (
<View key={`${item['rowKey']+""+item['colKey']}`}>
<Cell
type={item['type']}
value={item['value']}
width={wth}
height={height}
color= {'black'}
keyIndex ={`${item['rowKey']+""+item['colKey']}`}
/>
</View>
);
})}
</TouchableOpacity>
) : null;
}
export const Rows = props =>{
const { data, theme,toggleEditModal, widthArr ,height} = props;
return data ? (
<View style={{paddingTop :1}}>
{data.map((item, i) => {
return (
<View key ={i.toString()}>
<Row
data={item['data']}
theme={theme}
widthArr={widthArr}
height ={height}
backgroundColor={ i%2 == 0 ?'#E1FBFF':'white'}
toggleEditModal = {toggleEditModal}
rowNumber = {i+1}
/>
</View>
);
})}
</View>
) : null;
}
|
<reponame>t-abraham/slack-docker
package formatter
import (
"fmt"
"github.com/docker/docker/api/types"
"github.com/int128/slack"
)
// Version returns a message for the Docker version.
func Version(v types.Version) *slack.Message {
return &slack.Message{
Username: username,
IconEmoji: iconEmoji,
Text: fmt.Sprintf("Docker version %s (%s)", v.Version, v.KernelVersion),
}
}
|
<filename>components/DeckView.js
import React, {useContext} from 'react'
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native'
import { LinearGradient } from 'expo-linear-gradient';
import { AppContext } from '../provider/AppProvider'
export default function DeckView( {deck} ) {
const state = useContext(AppContext)
const viewDeck = () => {
state.setViewSelectedDeck(deck)
state.setShowDeck(true)
}
return (
<LinearGradient
style={styles.cardContainer}
colors={['#696969', '#383838']}
>
<Text style={styles.titleText}>{deck.deck_name}</Text>
<Text style={styles.text}>{deck.cards.length} cards</Text>
<View style={styles.buttonContainer}>
<TouchableOpacity onPress={viewDeck}>
<LinearGradient
colors={['#08d4c4', '#008075']}
style={styles.viewButton}
>
<Text style={styles.textView}>View Deck</Text>
</LinearGradient>
</TouchableOpacity>
</View>
</LinearGradient>
)
}
const styles = StyleSheet.create({
cardContainer: {
width: 200,
height: 215,
alignItems: 'center',
justifyContent: 'center',
marginVertical: 5,
marginHorizontal: 10,
borderRadius: 10,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 10,
},
card: {
padding: 10,
},
titleText: {
color: 'white',
fontSize: 28
},
text: {
color: 'white',
fontSize: 22
},
buttonContainer: {
paddingTop: 15,
// flexDirection: 'row',
// justifyContent: 'space-between',
},
viewButton: {
width: 150,
height: 40,
// paddingTop: 14,
// paddingBottom: 14,
// alignItems: 'center',
color: 'white',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 50,
flexDirection: 'row'
},
textView: {
color: 'white',
fontSize: 20,
fontWeight: 'bold'
}
});
|
<gh_stars>0
//Always runs in the background
var from = "K";
var to = "M";
var reloadable = false;
var transliterate = false;
function clickHandler(info, tab)
{
to = info.menuItemId;
chrome.tabs.getSelected(null, function(tab)
{
if(tab.url.substring(0, 7) == "chrome:") // if the page is a chrome settings page or if from and to values are the same
{
reloadable = false;
}
else
{
transliterate = true;
reloadable = true;
chrome.tabs.reload();
}
});
}
chrome.runtime.onInstalled.addListener(function()
{
chrome.contextMenus.create(
{
"title" : "Transliterate to Malayalam",
"contexts": ["page"],
"id": "M"
});
});
chrome.contextMenus.onClicked.addListener(clickHandler);
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse)
{
if(message == "tamMajority")
{
from = "T";
sendResponse("Tamil Majority");
chrome.contextMenus.update("M", {"enabled":false});
chrome.contextMenus.update("M", {"title": "To Malayalam Not Supported(Try Reloading)"});
}
else if(message == "devMajority")
{
from = "D";
sendResponse("Devanagari Majority");
chrome.contextMenus.update("M", {"enabled":true});
chrome.contextMenus.update("M", {"title": "Transliterate To Malayalam"});
}
else if(message == "punMajority")
{
from = "P";
sendResponse("Punjabi Majority");
chrome.contextMenus.update("M", {"enabled":false});
chrome.contextMenus.update("M", {"title": "To Malayalam Not Supported(Try Reloading)"});
}
else if(message == "oriMajority")
{
from = "O";
sendResponse("Oriya Majority");
chrome.contextMenus.update("M", {"enabled":false});
chrome.contextMenus.update("M", {"title": "To Malayalam Not Supported(Try Reloading)"});
}
else if(message == "benMajority")
{
from = "B";
sendResponse("Bengali Majority");
chrome.contextMenus.update("M", {"enabled":false});
chrome.contextMenus.update("M", {"title": "To Malayalam Not Supported(Try Reloading)"});
}
else if(message == "gujMajority")
{
from = "G";
sendResponse("Gujarati Majority");
chrome.contextMenus.update("M", {"enabled":false});
chrome.contextMenus.update("M", {"title": "To Malayalam Not Supported(Try Reloading)"});
}
else if(message == "malMajority")
{
from = "M";
sendResponse("Malayalam Majority");
chrome.contextMenus.update("M", {"enabled":false});
chrome.contextMenus.update("M", {"title": "To Malayalam Not Supported(Try Reloading)"});
}
else if(message == "kanMajority")
{
from = "K";
sendResponse("Kannada Majority");
chrome.contextMenus.update("M", {"enabled":false});
chrome.contextMenus.update("M", {"title": "To Malayalam Not Supported(Try Reloading)"});
}
else if(message == "telMajority")
{
from = "TEL";
sendResponse("Telugu Majority");
chrome.contextMenus.update("M", {"enabled":false});
chrome.contextMenus.update("M", {"title": "To Malayalam Not Supported(Try Reloading)"});
}
else if(message == "transliterate")
{
if(transliterate == true)
sendResponse("ok_" + from + "_" + to); // If transliteratinong has been requested, grant permission to transliterate
else
sendResponse("notOk");
}
else if(message == 'reset') // Once transliteration is done, reset message is received
{
transliterate = false;
sendResponse("backgroundReset");
}
}); |
#!/usr/bin/env node
// std
const path = require('path');
// libs
const rollup = require('rollup');
const json = require('rollup-plugin-json');
const resolve = require('rollup-plugin-node-resolve');
const uglify = require('rollup-plugin-uglify');
// project
const pkg = require('./package.json');
const PKG_NAME = pkg.name.replace('.js', '');
const banner = `/** \
${pkg.name} v${pkg.version} | @copyright ${new Date().getFullYear()} \
${pkg.author.name} <${pkg.author.url}> | @license ${pkg.license} */`
// Configuration data
const config = {
input: `src/${PKG_NAME}`,
external: ['jquery'],
plugins: [resolve(), json()],
output: {
format: 'umd',
file: `dist/${PKG_NAME}.js`,
name: PKG_NAME,
banner: banner,
globals: {
jquery: '$'
},
outro: `exports._build = "${new Date().toISOString()}";`
}
};
const plugins_min = config.plugins.concat([uglify({
mangle: true,
output: {beautify: false, preamble: banner}
})]);
const config_min = Object.assign({}, config, {
plugins: plugins_min,
output: Object.assign({}, config.output, {
file: `dist/${PKG_NAME}.min.js`,
sourcemap: true
})
});
// Handle watch events.
var isWatch = false;
var built = 0;
const stderr = console.error.bind(console); // eslint-disable-line no-console
const onevent = (e) => {
const filename = path.basename(`${e.output}`);
const duration = (e.duration / 1000).toFixed(1);
switch (e.code) {
case 'START':
stderr(`starting (${new Date().toISOString()})...`);
break;
case 'BUNDLE_START':
stderr(`bundling ${filename}...`);
break;
case 'BUNDLE_END':
stderr(`bundled ${filename} in [${duration}s].`);
break;
case 'END':
built += 1;
if (isWatch) {
stderr(`watching...${0 === built % 2 ? '\n' : ''}`);
} else if (2 === built) {
process.exit(0); // eslint-disable-line no-process-exit
}// end if: checked if we're ready to exit
break;
case 'ERROR': stderr(`error: ${e.error}`); break;
case 'FATAL': stderr(`fatal: ${e.error}`); break;
default: stderr(`unknown event: ${JSON.stringify(e)}`);
}// end switch: processed the event
};
// Process args.
if ('-w' === process.argv[2]) { isWatch = true; }
rollup.watch(config).on('event', onevent);
rollup.watch(config_min).on('event', onevent);
|
#!/usr/bin/env bash
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==============================================================================
set -e
set -x
N_JOBS=$(grep -c ^processor /proc/cpuinfo)
echo ""
echo "Bazel will use ${N_JOBS} concurrent job(s)."
echo ""
# Run configure.
export TF_NEED_GCP=0
export TF_NEED_HDFS=0
export TF_NEED_CUDA=0
# Only running cc tests, python version does not matter.
export PYTHON_BIN_PATH=`which python`
yes "" | $PYTHON_BIN_PATH configure.py
# Run bazel test command. Double test timeouts to avoid flakes.
bazel test --test_tag_filters=-no_oss,-gpu,-benchmark-test --test_lang_filters=cc,java -k \
--jobs=${N_JOBS} --test_timeout 300,450,1200,3600 \
--test_output=errors -- \
//tensorflow/... -//tensorflow/compiler/... -//tensorflow/contrib/...
|
<reponame>gerardob/generator-restgoose
'use strict';
// Module dependencies.
const mongoose = require('mongoose');
const User = mongoose.models.User;
const Constants = require('../library').Constants;
const Util = require('../library').Util;
const debug = require('debug')('Tools:Seed');
const API = {};
API.Run = async () => {
Util.PrintTitle('Running Seed ...');
return API.CreateTestCustomer().then(() => {
return 'Created test customers ';
});
};
API.CreateTestCustomer = async () => {
debug('Creating Owner User');
const fakeUsers = ['Customer 1', 'Customer 2', 'Customer 3'];
for await (const fakeUser of fakeUsers) {
const user = new User({
email: `${fakeUser.toLowerCase().replace(' ', '')}@<EMAIL>`,
password: ' ',
profile: {
firstName: fakeUser,
lastName: 'Test'
},
role: Constants.UserRole.Customer
});
await user.save();
}
};
module.exports = API;
|
<gh_stars>0
/**
* Copyright 2020 The Magma Authors.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* 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.
*
* @flow
* @format
*/
import type {Entries} from './Tokenizer';
import React from 'react';
import Token from './Token';
import {makeStyles} from '@material-ui/styles';
const useStyles = makeStyles(() => ({
token: {
margin: '2px',
},
}));
type Props<TEntry> = $ReadOnly<{|
tokens: Entries<TEntry>,
onTokensChange: (Entries<TEntry>) => void,
disabled?: boolean,
|}>;
const TokensList = <TEntry>(props: Props<TEntry>) => {
const {tokens, onTokensChange, disabled = false} = props;
const classes = useStyles();
return (
<>
{tokens.map(token => (
<Token
key={token.key}
className={classes.token}
disabled={disabled}
label={token.label}
onRemove={() =>
onTokensChange(tokens.slice().filter(t => t.key !== token.key))
}
/>
))}
</>
);
};
export default TokensList;
|
package ndsmickelson
import (
"fmt"
"net/http"
)
func init() {
http.HandleFunc("/", home)
http.HandleFunc("/data", data)
}
func home(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, HomeTemplate)
}
func data(w http.ResponseWriter, r *http.Request) {
peeps := GetTestPeople()
js, err := peeps.ToJSON()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprint(w, string(js))
}
|
import { Express } from 'express';
const styleSource = 'https://fonts.googleapis.com';
const fontSource = 'https://fonts.gstatic.com';
const amplitude = 'https://amplitude.nav.no';
const sentry = 'https://sentry.gc.nav.no';
const cspString = `default-src 'self' data: ${amplitude} ${sentry}; style-src 'self' ${styleSource} data: 'unsafe-inline'; font-src 'self' ${fontSource} data:`;
const setup = (app: Express) => {
app.disable('x-powered-by');
app.use((_req, res, next) => {
res.header('X-Frame-Options', 'DENY');
res.header('X-Xss-Protection', '1; mode=block');
res.header('X-Content-Type-Options', 'nosniff');
res.header('Referrer-Policy', 'no-referrer');
if (process.env.NODE_ENV !== 'development') {
res.header('Content-Security-Policy', cspString);
res.header('X-WebKit-CSP', cspString);
res.header('X-Content-Security-Policy', cspString);
}
res.header('Feature-Policy', "geolocation 'none'; microphone 'none'; camera 'none'");
res.header('Access-Control-Allow-Methods', 'PUT, PATCH, GET, POST, DELETE');
next();
});
};
export default { setup };
|
package lib
import "encoding/base32"
func Base32String(p []byte) string {
return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(p)
}
|
#!/bin/bash
set -e
DEPLOY_DIR="__deploy"
COMMON_DIR="../docker-common"
COGSTACK_DIR="./cogstack"
DB_DIR="./db_dump"
DOCKER_DIR="./docker"
COMMON_OUT_DIR="$DEPLOY_DIR/common"
COGSTACK_OUT_DIR="$DEPLOY_DIR/cogstack"
DB_OUT_DIR="$DEPLOY_DIR/db_dump"
DB_DUMP_FILE="$DB_DIR/db_samples.sql.gz"
# main entry point
#
echo "Generating deployment scripts"
if [ -e $DEPLOY_DIR ]; then rm -rf $DEPLOY_DIR; fi
mkdir $DEPLOY_DIR
# copy the relevant common data
#
if [ ! -e $DB_DUMP_FILE ]; then echo "Missing DB dump file: $DB_DUMP_FILE" && exit 1; fi
echo "Copying the DB dump"
mkdir $DB_OUT_DIR
cp $DB_DUMP_FILE $DB_OUT_DIR/
# used services
#
services=(pgjobrepo
pgsamples
elasticsearch
kibana
fluentd
nginx)
echo "Copying the configuration files for the common docker images and setting up services"
mkdir $COMMON_OUT_DIR
for sv in ${services[@]}; do
echo "-- Setting up: ${sv}"
cp -r $COMMON_DIR/${sv} $COMMON_OUT_DIR/
done
# setup nginx
#
if [ ! -e $COMMON_OUT_DIR/nginx/auth/.htpasswd ]; then
echo "-- Generating user:password --> 'test:test' for nginx proxy"
mkdir $COMMON_OUT_DIR/nginx/auth
htpasswd -b -c $COMMON_OUT_DIR/nginx/auth/.htpasswd 'test' 'test'
fi
cp $DOCKER_DIR/docker-compose.override.yml $DEPLOY_DIR/
cp $COMMON_DIR/docker-compose.yml $DEPLOY_DIR/
# setup cogstack
#
echo "Generating properties files for CogStack"
mkdir $COGSTACK_OUT_DIR
cp $COGSTACK_DIR/*.properties $COGSTACK_OUT_DIR/
echo "Done."
|
class Dog {
constructor(name, breed, age) {
this.name = name;
this.breed = breed;
this.age = age;
}
bark() {
console.log('Woof!');
}
getAge() {
return this.age;
}
}
// Instantiate an object of the class:
let myDog = new Dog('Spot', 'Labrador', 4);
console.log(myDog);
// Output: Dog {name: 'Spot', breed: 'Labrador', age: 4} |
from collections import Counter
import string
def analyze_text_file(file_path):
with open(file_path, 'r') as file:
content = file.read()
alphanumeric_content = ''.join(filter(lambda x: x.isalnum(), content))
character_frequency = Counter(alphanumeric_content.lower())
sorted_frequency = sorted(character_frequency.items(), key=lambda x: x[1], reverse=True)
for char, freq in sorted_frequency:
print(f"{char}: {freq}")
# Example usage
analyze_text_file('sample.txt') |
// function to generate markdown for README
function generateMarkdown(data) {
const title = data.title.trim();
const description = data.description.trim();
const install = data.install.trim();
const usage = data.usage.trim();
const contribute = data.contribute.trim();
const test = data.test.trim();
const github = data.github.trim();
const email = data.email.trim();
const license = data.license.trim();
const year = data.year.trim();
const name = data.name.trim();
let descriptionText = "";
let installText = "";
let usageText = "";
let contributeText = "";
let testText = "";
let licenseText = "";
let badge = "";
let tableOfContents = "## Table of Contents\n\n";
switch (license) {
//thanks to <NAME> on GitHub for collecting the badges (https://gist.github.com/lukas-h/2a5d00690736b4c3a7ba)
case "MIT License":
badge = `[](https://opensource.org/licenses/MIT)`;
licenseText = `Copyright ${year} ${name}\n
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:\n
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n
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.\n`;
break;
case "Apache 2.0":
badge = `[](https://opensource.org/licenses/Apache-2.0)`;
licenseText = `Copyright ${year} ${name}\n
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 a\n
http://www.apache.org/licenses/LICENSE-2.0\n
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.\n`;
break;
case "BSD 3-Clause License":
badge = `[](https://opensource.org/licenses/BSD-3-Clause)`;
licenseText = `Copyright ${year} ${name}\n
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n
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.\n
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n
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.\n`;
break;
}
let result = `# ${title} ${badge}\n\n`;
if (description !== "") {
descriptionText += `${description}\n\n`;
}
if (install !== "") {
installText += `## Installation\n\n${install}\n\n`;
tableOfContents += `* [Installation](#installation)\n\n`;
}
if (usage !== "") {
usageText += `## Usage\n\n${usage}\n\n`;
tableOfContents += `* [Usage](#usage)\n\n`;
}
if (contribute !== "") {
contributeText += `## Contributing\n\n${contribute}\n\n`;
tableOfContents += `* [Contributing](#contributing)\n\n`;
}
if (test !== "") {
testText += `## Tests\n\n${test}\n\n`;
tableOfContents += `* [Tests](#tests)\n\n`;
}
tableOfContents += `* [License](#license)\n\n`;
tableOfContents += `* [Questions](#questions)\n\n`;
result +=
descriptionText +
tableOfContents +
installText +
usageText +
contributeText +
testText;
result += `## License\n\n${licenseText}\n`;
result += `## Questions\n\nReach out to me through email or on GitHub!\n\n### Github\n\nhttps://github.com/${github}\n\n### Email\n\n${email}\n`;
return result;
}
module.exports = generateMarkdown;
|
package org.jooby.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.concurrent.atomic.AtomicReference;
import org.jooby.test.ServerFeature;
import org.junit.Test;
public class ShouldCreateANewSessionFeature extends ServerFeature {
private static final AtomicReference<String> sessionId = new AtomicReference<>();
{
get("/shouldCreateANewSession", req -> {
sessionId.set(req.session().id());
return sessionId.get();
});
}
@Test
public void shouldCreateANewSession() throws Exception {
request()
.get("/shouldCreateANewSession")
.expect(sid -> assertEquals(sid, sessionId.get()))
.header("Set-Cookie", setCookie -> assertNotNull(setCookie));
}
}
|
const { createFilePath } = require("gatsby-source-filesystem")
const generateBlogPage = require('./page-generators/blog-list');
const generatePostPage = require('./page-generators/post');
exports.createPages = async function (createPageParams) {
await generateBlogPage(createPageParams);
await generatePostPage(createPageParams);
}
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions;
if (node.internal.type === 'MarkdownRemark') {
const value = createFilePath({ node, getNode });
createNodeField({
name: 'slug',
node,
value
});
}
} |
<gh_stars>0
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
// Solution
public static void insertionSort2(int n, List<Integer> array) {
for (int i = 1; i < array.size(); i++) {
int j = i;
int value = array.get(i);
while (j >= 1 && array.get(j - 1) > value) {
array.set(j, array.get(j - 1));
j--;
}
array.set(j, value);
printArr(array);
}
}
public static void printArr(List<Integer> arr) {
for (Integer num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
Result.insertionSort2(n, arr);
bufferedReader.close();
}
}
|
<filename>cmd/diplomat/internal/config_navigator.go
package internal
import (
"fmt"
"github.com/tony84727/diplomat/pkg/data"
"reflect"
"strconv"
"strings"
)
type ConfigNavigator struct {
previous reflect.Value
current reflect.Value
currentType reflect.Type
valid bool
}
func NewConfigNavigator(config data.Configuration) *ConfigNavigator {
navigator := &ConfigNavigator{valid:true}
navigator.setCurrent(reflect.ValueOf(config))
return navigator
}
func structFieldHint(structValue reflect.Value) string {
keys := make([]string, structValue.NumField())
for i := 0; i < structValue.NumField() ; i++ {
v := structValue.FieldByIndex([]int{i})
keys[i] = v.Type().Name()
}
return fmt.Sprintf("%v", keys)
}
func (c *ConfigNavigator) setCurrent(value reflect.Value) {
c.previous = c.current
c.current = value
if !c.current.IsValid() {
c.valid = false
return
}
c.currentType = value.Type()
}
func (c *ConfigNavigator) Get(paths ...string) (interface{}, error) {
i := 0
for i < len(paths) {
segment := paths[i]
switch c.currentType.Kind() {
case reflect.Ptr, reflect.Interface:
c.setCurrent(c.current.Elem())
continue
case reflect.Slice:
index,err := strconv.Atoi(segment)
if err != nil {
return nil,fmt.Errorf(`%s is a slice. "%s" is not a valid integer`, strings.Join(paths[:i],"."), segment)
}
c.setCurrent(c.current.Index(index))
i++
case reflect.Struct:
searcher := FieldSearcher{c.current}
value, ok := searcher.Search(segment)
if !ok {
return nil, fmt.Errorf("%s doesn't exist, possible values %s", segment, structFieldHint(c.current))
}
c.setCurrent(value)
i++
case reflect.Map:
c.setCurrent(c.current.MapIndex(reflect.ValueOf(segment)))
i++
}
if !c.valid {
return nil, fmt.Errorf("%s doesn't exist. current: %v", segment, c.previous.Interface())
}
}
return c.current.Interface(),nil
}
|
<filename>components/FilterCard.js<gh_stars>0
import { React } from "react";
import Filter from "./Filter";
export default function FilterCard(props) {
const titleTransformer = {
job_type: "Job type",
department: "Department",
work_schedule: "Work Schedule",
experience: "Experience",
};
const { title, filters } = props;
const filterElements = filters.map((filter) => {
const { key, doc_count } = filter;
return (
<Filter title={title} key={key} filterId={key} doc_count={doc_count} />
);
});
return (
<div className="max-w-sm bg-white border-1 border-gray-300 p-4 rounded-sm tracking-wide mb-3 w-full md:max-h-80 md:overflow-auto">
<header className="mb-4 flex items-center justify-between">
<h3 className="text-md leading-6 font-medium text-black uppercase truncate">
{titleTransformer[title]}
</h3>
</header>
{filterElements}
</div>
);
}
|
#!/bin/bash
#
# This is one of the scripts that gets passed to binary_search_state.py.
# It's supposed to generate the binary to be tested, from the mix of
# good & bad object files.
#
source full_bisect_test/common.sh
WD=`pwd`
cd full_bisect_test
echo "BUILDING IMAGE"
gcc -o bin-trees work/*.o
|
<gh_stars>10-100
package io.opensphere.mantle.data.geom.factory;
import io.opensphere.core.Toolbox;
import io.opensphere.core.geometry.AbstractRenderableGeometry;
import io.opensphere.core.geometry.Geometry;
import io.opensphere.mantle.data.DataTypeInfo;
import io.opensphere.mantle.data.element.VisualizationState;
import io.opensphere.mantle.data.geom.MapGeometrySupport;
/**
* Interface that defines a converter that will transform a
* {@link MapGeometrySupport} implementer into a {@link Geometry}.
*/
public interface MapGeometrySupportToGeometryConverter
{
/**
* Converts the provided {@link MapGeometrySupport} to a {@link Geometry}.
*
* @param geomSupport the geometry support to convert
* @param id the id - the id of the element in the registry
* @param dti the {@link DataTypeInfo}
* @param vs - the {@link VisualizationState}
* @param renderPropertyPool the render property pool
* @return the geometry resultant geometry.
* @throws IllegalArgumentException if the geomSupport is not the same as
* the class ( or extension of the class) returned by
* getConvertedClassType.
*/
AbstractRenderableGeometry createGeometry(MapGeometrySupport geomSupport, long id, DataTypeInfo dti, VisualizationState vs,
RenderPropertyPool renderPropertyPool) throws IllegalArgumentException;
/**
* Gets the class for which this converter will make conversions from
* something that implements MapGeometrySupport to a Geometry.
*
* @return the converted class type
*/
Class<?> getConvertedClassType();
/**
* Gets the Toolbox.
*
* @return the toolbox
*/
Toolbox getToolbox();
}
|
#!/bin/sh
pwd
|
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/views/Home.vue'
import Competition from '@/views/Competition.vue'
import PageNotFound from '@/views/PageNotFound.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/competition/:compName/:compSection',
name: 'competition',
component: Competition,
props: true
},
{
path: '/admin',
name: 'admin',
component: () => import(/* webpackChunkName: "admin" */ '@/views/admin/Home.vue')
},
{
path: '*',
name: '404',
component: PageNotFound
}
]
})
|
"use strict";
const fs = require(`fs`);
exports.clearTemporaryFile = function(request, reply) {
if (request.response.isBoom) {
return reply.continue();
}
// Once a successful request completes, we delete any
// temporary files we created
request.response.once(`finish`, function() {
if (!request.app.tmpFile) {
return;
}
fs.unlink(request.app.tmpFile, function(err) {
if (err) {
request.log.error(`Failed to destroy temporary file with ${err}`);
}
});
});
reply.continue();
};
exports.logRequest = function(request, reply) {
const response = request.response;
// We don't want to clutter the terminal, so only
// show request details if this was an error
if (!response.isBoom) {
reply.continue();
return;
}
const data = response.data;
const error = data && data.error;
// Prefer the error object stack over the
// boom object stack
const stack = error && error.stack || response.stack;
let logLevel = `error`;
if (!data || data.debug) {
// Errors we process will contain a "data" property
// containing the error object (or string) and the
// level of the error. If it doesn't exist, then the `boom`
// object was created by the framework and represents an
// error we don't care about under normal circumstances
logLevel = `debug`;
}
request.log[logLevel]({
request,
response,
error,
stack
});
reply.continue();
};
|
import { StoreCalc } from './storeCalc';
import {ActionCalc, ActionsCalculator} from './actions';
let store: StoreCalc = new StoreCalc();
let action: ActionCalc = {
type: ActionsCalculator.ADD_ONE
}
console.log ('### Initial state: ', store.getState());
store.dispatch(action);
console.log('### State ADD_ONE: ', store.getState());
store.dispatch(action);
console.log('### State ADD_ONE (second): ', store.getState());
action.type = ActionsCalculator.SUBSTRACT_ONE;
store.dispatch(action);
console.log('### State SUBSTRACT_ONE: ', store.getState()); |
#!/usr/bin/env bash
# enable/disable shell options
TRUE_REG='^([tT][rR][uU][eE]|[yY]|[yY][eE][sS]|1)$'
# start message prefix
START_GROUP=${START_GROUP:-START}
# end message prefix
END_GROUP=${END_GROUP:-END}
# console color points
if command -v tput &>/dev/null && tty -s; then
COLOR_RED=$(tput setaf 1)
COLOR_GREEN=$(tput setaf 2)
COLOR_YELLOW=$(tput setaf 3)
COLOR_BOLD=$(tput bold)
COLOR_END=$(tput sgr0)
else
COLOR_RED=$(echo -e "\e[31m")
COLOR_GREEN=$(echo -e "\e[32m")
COLOR_YELLOW=$(echo -e "\e[33m")
COLOR_BOLD=$(echo -e "\e[01m")
COLOR_END=$(echo -e "\e[00m")
fi
# enable/disable debug output
DEBUG_SCRIPT=${DEBUG_SCRIPT:-false}
if [[ $DEBUG_SCRIPT =~ $TRUE_REG ]]; then
set -o xtrace
fi
# enable/disable strict mode
STRICT_SCRIPT=${STRICT_SCRIPT:-false}
if [[ $STRICT_SCRIPT =~ $TRUE_REG ]]; then
set -o errexit
set -o nounset
set -o pipefail
fi
# enable/disable docker BuildKit option
export DOCKER_BUILDKIT=${DOCKER_BUILDKIT:-1}
# enable/disable docker cli build option
export COMPOSE_DOCKER_CLI_BUILD=${COMPOSE_DOCKER_CLI_BUILD:-1}
# architecture type
UNAME_ARCH=${UNAME_ARCH:-$(uname -m | sed s/x86_64/amd64/ | sed s/aarch64/arm64/ | sed s/aarch64_be/arm64/)}
# DOCKER_COMPOSE_CMD stores docker-compose command
DOCKER_COMPOSE_CMD=$(command -v docker-compose || command -v docker compose)
_newline() {
printf "\n"
}
_success() {
printf "${COLOR_GREEN} ✔ [ %s ]${COLOR_END}" "$@" >&2
_newline
}
_error() {
printf "${COLOR_RED} ✖ [ %s ]${COLOR_END}" "$@" >&2
_newline
}
_info() {
printf "${COLOR_YELLOW} %s ${COLOR_END}" "$@" >&2
_newline
}
_message() {
_newline
printf "${COLOR_BOLD}${COLOR_YELLOW}========== %s ==========${COLOR_END}" "$@" >&2
_newline
_newline
}
_log() {
(($# > 0)) && echo "$@" >&2
}
_exit() {
(($# > 1)) && _error "${@:2}"
exit "$1"
}
_log_success() {
(($# > 0)) && _success "$@"
}
_log_error() {
(($# > 0)) && _error "$@"
}
_log_info() {
(($# > 0)) && _info "$@"
}
_log_message() {
(($# > 0)) && _message "$@"
}
_log_start_group() {
_log_message "${START_GROUP}"
}
_log_end_group() {
_log_message "${END_GROUP}"
}
_docker_compose() {
$DOCKER_COMPOSE_CMD "$@"
}
_run() {
_log_start_group
_log_success "Running script $(basename "$0")"
_docker_compose "$@"
_log_success "Done!"
_log_end_group
}
|
<gh_stars>0
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AppdataService {
apiUrl = 'https://jsonplaceholder.typicode.com';
constructor(private http: HttpClient) { }
fetchAllPosts() {
return this.http.get(`${this.apiUrl}/posts`);
}
fetchAllPostsById(id: number) {
return this.http.get(`${this.apiUrl}/posts/${id}`);
}
fetchAllPostsByUserId(userid: number) {
return this.http.get(`${this.apiUrl}/posts?userId=${userid}`);
}
}
|
import { combineReducers } from 'redux';
import authReducer from './authReducer';
import employeeFormReducer from './employeeFormReducer';
import employeesReducer from './employeesReducer';
export default combineReducers({
auth: authReducer,
employeeForm: employeeFormReducer,
employees: employeesReducer
}); |
// define the set of characters
const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
// generate a random string of 10 characters
function generateRandomString(length) {
let result = '';
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
const randomString = generateRandomString(10);
console.log(randomString); // ex: 4b0a9HY4e7 |
#!/bin/sh
echo "Enter your CaaS API username:"
read MCP_USERNAME
echo "Enter your CaaS API password:"
read -s MCP_PASSWORD
echo "Enter the URL of the fittings file you want to deploy:"
read FITTINGS_URL
echo "Enter the password for deploying new servers:"
read SHARED_SECRET
docker run -e "MCP_USERNAME=$MCP_USERNAME" -e "MCP_PASSWORD=$MCP_PASSWORD" -e "SHARED_SECRET=$SHARED_SECRET" -e "FITTINGS=$FITTINGS_URL" dimensiondataresearch/plumbery
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.