text stringlengths 1 1.05M |
|---|
/*! \file CLUtils.hpp
* \brief Declarations of objects,
* functions and classes for the CLUtils library.
* \details CLUtils offers utilities that help
setup and manage an OpenCL environment.
* \author <NAME>
* \version 0.2.2
* \date 2014-2015
* \copyright The MIT License (MIT)
* \par
* Copyright (c) 2014 <NAME>
* \par
* 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:
* \par
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \par
* 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.
*/
#ifndef CLUTILS_HPP
#define CLUTILS_HPP
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <numeric>
#include <unordered_map>
#include <chrono>
#include <cassert>
#include <cmath>
#define __CL_ENABLE_EXCEPTIONS
#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl.hpp>
#else
#include <CL/cl.hpp>
#endif
/*! \brief It brings together functionality common to all OpenCL projects.
*
* It offers structures that aim to ease the process of setting up and
* maintaining an OpenCL environment.
*/
namespace clutils
{
/*! \brief Returns the name of an error code. */
const char* getOpenCLErrorCodeString (int errorCode);
/*! \brief Checks the availability of the "GL Sharing" capability. */
bool checkCLGLInterop (cl::Device &device);
/*! \brief Reads in the contents from the requested files. */
void readSource (const std::vector<std::string> &kernel_filenames,
std::vector<std::string> &sourceCodes);
/*! \brief Splits a string on the requested delimiter. */
void split (const std::string &str, char delim,
std::vector<std::string> &names);
/*! \brief Creates a pair of a char array (source code) and its size. */
std::pair<const char *, size_t>
make_kernel_pair (const std::string &kernel_filename);
/*! \brief Sets up an OpenCL environment.
* \details Prepares the essential OpenCL objects for the execution of
* kernels. This class aims to allow rapid prototyping by hiding
* away all the boilerplate code necessary for establishing
* an OpenCL environment.
*/
class CLEnv
{
public:
CLEnv (const std::vector<std::string> &kernel_filenames = std::vector<std::string> (),
const char *build_options = nullptr);
CLEnv (const std::string &kernel_filename,
const char *build_options = nullptr);
virtual ~CLEnv () {};
/*! \brief Gets back one of the existing contexts. */
cl::Context& getContext (unsigned int pIdx = 0);
/*! \brief Gets back one of the existing command queues
* in the specified context. */
cl::CommandQueue& getQueue (unsigned int ctxIdx = 0, unsigned int qIdx = 0);
/*! \brief Gets back one of the existing programs. */
cl::Program& getProgram (unsigned int pgIdx = 0);
/*! \brief Gets back one of the existing kernels in some program. */
cl::Kernel& getKernel (const char *kernelName, unsigned int pgIdx = 0);
/*! \brief Creates a context for all devices in the requested platform. */
cl::Context& addContext (unsigned int pIdx, const bool gl_shared = false);
/*! \brief Creates a queue for the specified device in the specified context. */
cl::CommandQueue& addQueue (unsigned int ctxIdx, unsigned int dIdx, cl_command_queue_properties props = 0);
/*! \brief Creates a queue for the GL-shared device in the specified context. */
cl::CommandQueue& addQueueGL (unsigned int ctxIdx, cl_command_queue_properties props = 0);
/*! \brief Creates a program for the specified context. */
cl::Kernel& addProgram (unsigned int ctxIdx,
const std::vector<std::string> &kernel_filenames,
const char *kernel_name = nullptr,
const char *build_options = nullptr);
cl::Kernel& addProgram (unsigned int ctxIdx,
const std::string &kernel_filename,
const char *kernel_name = nullptr,
const char *build_options = nullptr);
// Objects associated with an OpenCL environment.
// For each of a number of objects, there is a vector that
// can hold all instances of that object.
std::vector<cl::Platform> platforms; /*!< List of platforms. */
/*! \brief List of devices per platform.
* \details Holds a vector of devices per platform. */
std::vector< std::vector<cl::Device> > devices;
private:
std::vector<cl::Context> contexts; /*!< List of contexts. */
/*! \brief List of queues per context.
* \details Holds a vector of queues per context. */
std::vector< std::vector<cl::CommandQueue> > queues;
std::vector<cl::Program> programs; /*!< List of programs. */
/*! \brief List of kernels per program.
* \details Holds a vector of kernels per program. */
std::vector< std::vector<cl::Kernel> > kernels;
protected:
/*! \brief Initializes the OpenGL memory buffers.
* \details If CL-GL interop is desirable, CLEnv has to be derived and
* `initGLMemObjects` be implemented. `initGLMemObjects` will
* have to create all necessary OpenGL memory buffers.
* \note Setting up CL-GL interop requires the following procedure:
* (i) Initialize OpenGL context, (ii) Initilize OpenCL context,
* (iii) Create OpenGL buffers, (iv) Create OpenCL buffers.
* \note Do not call `initGLMemObjects` directly. `initGLMemObjects`
* will be called by `addContext` when it is asked for a
* GL-shared CL context to be created.
*/
virtual void initGLMemObjects () {};
private:
/*! \brief Maps kernel names to kernel indices.
* There is one unordered_map for every program.
*
* For every program in programs, there is an element in kernelIdx.
* For every kernel in program i, there is a mapping from the kernel
* name to the kernel index in kernels[i].
*/
std::vector< std::unordered_map<std::string, unsigned int> > kernelIdx;
};
/*! \brief Facilitates the conveyance of `CLEnv` arguments.
* \details `CLEnv` creates an OpenCL environment. A `CLEnv` object
* potentially contains many platforms, contexts, queues, etc,
* that are to be used by different (independent) subsystems.
* Those subsystems will have to know where to look inside CLEnv
* for their associated CL objects. `CLEnvInfo` organizes this
* process of information transfer between OpenCL systems.
*
* \tparam nQueues the number of command queue indices to be held by `CLEnvInfo`.
*/
template<unsigned int nQueues = 1>
class CLEnvInfo
{
public:
/*! \brief Initializes a `CLEnvInfo` object.
* \details All provided indices are supposed to follow the order the
* associated objects were created in the associated `CLEnv` instance.
*
* \param[in] _pIdx platform index.
* \param[in] _dIdx device index.
* \param[in] _ctxIdx context index.
* \param[in] _qIdx vector with command queue indices.
* \param[in] _pgIdx program index.
*/
CLEnvInfo (unsigned int _pIdx = 0, unsigned int _dIdx = 0, unsigned int _ctxIdx = 0,
const std::vector<unsigned int> _qIdx = { 0 }, unsigned int _pgIdx = 0) :
pIdx (_pIdx), dIdx (_dIdx), ctxIdx (_ctxIdx), pgIdx (_pgIdx)
{
try
{
if (_qIdx.size () != nQueues)
throw "The provided vector of command queue indices has the wrong size";
qIdx = _qIdx;
}
catch (const char *error)
{
std::cerr << "Error[CLEnvInfo]: " << error << std::endl;
exit (EXIT_FAILURE);
}
}
/*! \brief Creates a new `CLEnvInfo` object with the specified command queue.
* \details Maintains the same OpenCL configuration, but chooses only one
* of the available command queues to include.
*
* \param[in] idx an index for the `qIdx` vector.
*/
CLEnvInfo<1> getCLEnvInfo (unsigned int idx)
{
try
{
return CLEnvInfo<1> (pIdx, dIdx, ctxIdx, { qIdx.at (idx) }, pgIdx);
}
catch (const std::out_of_range &error)
{
std::cerr << "Out of Range error: " << error.what ()
<< " (" << __FILE__ << ":" << __LINE__ << ")" << std::endl;
exit (EXIT_FAILURE);
}
}
unsigned int pIdx; /*!< Platform index. */
unsigned int dIdx; /*!< Device index. */
unsigned int ctxIdx; /*!< Context index. */
std::vector<unsigned int> qIdx; /*!< Vector of queue indices. */
unsigned int pgIdx; /*!< Program index. */
};
/*! \brief A class that collects and manipulates timing information
* about a test.
* \details It stores the execution times of a test in a vector,
* and then offers summarizing results.
*
* \tparam nSize the number of test repetitions.
* \tparam rep the type of the values the class stores and returns.
*/
template <uint nSize, typename rep = double>
class ProfilingInfo
{
public:
/*! \param[in] pLabel a label characterizing the test.
* \param[in] pUnit a name for the time unit to be printed
* when displaying the results.
*/
ProfilingInfo (std::string pLabel = std::string (), std::string pUnit = std::string ("ms"))
: label (pLabel), tExec (nSize), tWidth (4 + log10 (nSize)), tUnit (pUnit)
{
}
/*! \param[in] idx subscript index. */
rep& operator[] (const int idx)
{
assert (idx >= 0 && idx < nSize);
return tExec[idx];
}
/*! \brief Returns the sum of the \#nSize executon times.
*
* \param[in] initVal an initial value from which to start counting.
* \return The sum of the vector elements.
*/
rep total (rep initVal = 0.0)
{
return std::accumulate (tExec.begin (), tExec.end (), initVal);
}
/*! \brief Returns the mean time of the \#nSize executon times.
*
* \return The mean of the vector elements.
*/
rep mean ()
{
return total() / (rep) tExec.size ();
}
/*! \brief Returns the min time of the \#nSize executon times.
*
* \return The min of the vector elements.
*/
rep min ()
{
return *std::min_element (tExec.begin (), tExec.end ());
}
/*! \brief Returns the max time of the \#nSize executon times.
*
* \return The max of the vector elements.
*/
rep max ()
{
return *std::max_element (tExec.begin (), tExec.end ());
}
/*! \brief Returns the relative performance speedup wrt `refProf`.
*
* \param[in] refProf a reference test.
* \return The factor of execution time decrease.
*/
rep speedup (ProfilingInfo &refProf)
{
return refProf.mean () / mean ();
}
/*! \brief Displays summarizing results on the test.
*
* \param[in] title a title for the table of results.
* \param[in] bLine a flag for whether or not to print a newline
* at the end of the table.
*/
void print (const char *title = nullptr, bool bLine = true)
{
std::ios::fmtflags f (std::cout.flags ());
std::cout << std::fixed << std::setprecision (3);
if (title)
std::cout << std::endl << title << std::endl << std::endl;
else
std::cout << std::endl;
std::cout << " " << label << std::endl;
std::cout << " " << std::string (label.size (), '-') << std::endl;
std::cout << " Mean : " << std::setw (tWidth) << mean () << " " << tUnit << std::endl;
std::cout << " Min : " << std::setw (tWidth) << min () << " " << tUnit << std::endl;
std::cout << " Max : " << std::setw (tWidth) << max () << " " << tUnit << std::endl;
std::cout << " Total : " << std::setw (tWidth) << total () << " " << tUnit << std::endl;
if (bLine) std::cout << std::endl;
std::cout.flags (f);
}
/*! \brief Displays summarizing results on two tests.
* \details Compares the two tests by calculating the speedup
* on the mean execution times.
* \note I didn't bother handling the units. It's your responsibility
* to enforce the same unit of time on the two objects.
*
* \param[in] refProf a reference test.
* \param[in] title a title for the table of results.
*/
void print (ProfilingInfo &refProf, const char *title = nullptr)
{
if (title)
std::cout << std::endl << title << std::endl;
refProf.print (nullptr, false);
print (nullptr, false);
std::cout << std::endl << " Benchmark" << std::endl << " ---------" << std::endl;
std::cout << " Speedup: " << std::setw (tWidth) << speedup (refProf) << std::endl << std::endl;
}
private:
std::string label; /*!< A label characterizing the test. */
std::vector<rep> tExec; /*!< Execution times. */
uint8_t tWidth; /*!< Width of the results when printing. */
std::string tUnit; /*!< Time unit to display when printing the results. */
};
/*! \brief A class for measuring execution times.
* \details CPUTimer is an interface for `std::chrono::duration`.
*
* \tparam rep the type of the value returned by `duration`.
* \tparam period the unit of time for the value returned by `duration`.
* It is declared as an `std::ratio<std::intmax_t num, std::intmax_t den>`.
*/
template <typename rep = int64_t, typename period = std::milli>
class CPUTimer
{
public:
/*! \brief Constructs a timer.
* \details The timer doesn't start automatically.
*
* \param[in] initVal a value to initialize the timer with.
*/
CPUTimer (int initVal = 0) : tDuration (initVal)
{
}
/*! \brief Starts the timer.
*
* \param[in] tReset a flag for resetting the timer before the timer starts.
* If `false`, the timer starts counting from
* the point it reached the last time it stopped.
*/
void start (bool tReset = true)
{
if (tReset)
reset ();
tReference = std::chrono::high_resolution_clock::now ();
}
/*! \brief Stops the timer.
*
* \return The time measured up to this point in `period` units.
*/
rep stop ()
{
tDuration += std::chrono::duration_cast< std::chrono::duration<rep, period> >
(std::chrono::high_resolution_clock::now () - tReference);
return duration ();
}
/*! \brief Returns the time measured by the timer.
* \details This time is measured up to the point the timer last time stopped.
*
* \return The time in `period` units.
*/
rep duration ()
{
return tDuration.count ();
}
/*! \brief Resets the timer. */
void reset ()
{
tDuration = std::chrono::duration<rep, period>::zero ();
}
private:
/*! A reference point for when the timer started. */
std::chrono::time_point<std::chrono::high_resolution_clock> tReference;
/*! The time measured by the timer. */
std::chrono::duration<rep, period> tDuration;
};
/*! \brief A class for profiling CL devices.
*
* \tparam period the unit of time for the value returned by `duration`.
* It is declared as an `std::ratio<std::intmax_t num, std::intmax_t den>`.
*/
template <typename period = std::milli>
class GPUTimer
{
public:
/*! \param[in] device the targeted for profiling CL device.
*/
GPUTimer (cl::Device &device)
{
period tPeriod;
size_t tRes = device.getInfo<CL_DEVICE_PROFILING_TIMER_RESOLUTION> (); // x nanoseconds
// Converts nanoseconds to seconds and then to the requested scale
tUnit = (double) tPeriod.den / (double) tPeriod.num / 1000000000.0 * tRes;
}
/*! \brief Returns a new unpopulated event.
* \details The last populated event gets dismissed.
*
* \return An event for the profiling process.
*/
cl::Event& event ()
{
return pEvent;
}
/*! \brief This is an interface for `cl::Event::wait`.
*/
void wait ()
{
pEvent.wait ();
}
/*! \brief Returns the time measured by the timer.
* \note It's important that it's called after a call to `wait`.
*
* \return The time in `period` units.
*/
double duration ()
{
cl_ulong start = pEvent.getProfilingInfo<CL_PROFILING_COMMAND_START> ();
cl_ulong end = pEvent.getProfilingInfo<CL_PROFILING_COMMAND_END> ();
return (end - start) * tUnit;
}
private:
cl::Event pEvent; /*!< The profiling event. */
double tUnit; /*!< A factor to set the scale for the measured time. */
};
}
#endif // CLUTILS_HPP
|
function calculateArea(width, height) {
return width * height;
} |
"""
Zaimplementuj sortowanie babelkowe.
"""
# Zlozonosc czasowa O(n^2)
def sortuj_v1(tablica):
n = len(tablica)
for i in range(n - 1):
for j in range(n - i - 1):
if tablica[j] > tablica[j + 1]:
tablica[j], tablica[j + 1] = tablica[j + 1], tablica[j]
# Testy Poprawnosci
def test_1():
tablica = [4, 2, 5, 3, 1]
wynik = [1, 2, 3, 4, 5]
sortuj_v1(tablica)
assert tablica == wynik
def test_2():
tablica = [6, 5, 1, 2, 3, 1, 4, 3, 5, 2, 3]
wynik = [1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 6]
sortuj_v1(tablica)
assert tablica == wynik
def main():
test_1()
test_2()
if __name__ == "__main__":
main()
|
#!/usr/bin/env bash
# This function checks whether we have a given program on the system.
_have()
{
# Completions for system administrator commands are installed as well in
# case completion is attempted via `sudo command ...'.
PATH=$PATH:/usr/sbin:/sbin:/usr/local/sbin type $1 &> /dev/null
}
_have cerberus &&
_cerberus_complete()
{
# Internal field separator
local IFS=$'\t\n'
# current and previously typed words
local cur prev
cur=${COMP_WORDS[COMP_CWORD]}
prev=${COMP_WORDS[COMP_CWORD-1]}
# completion array
COMPREPLY=( )
# cerberus <command>
if [[ ${COMP_CWORD} -eq 1 ]]; then
COMPREPLY=( $(compgen -W "$(printf "file \nsecret \nsdb ")" -- ${cur}) )
# cerberus <command> <command>
elif [[ $COMP_CWORD -eq 2 ]]; then
case "$prev" in
"file")
COMPREPLY=( $(compgen -W "$(printf "read \ndownload \nedit \ndelete \nupload \nlist ")" -- ${cur}) )
;;
"secret")
COMPREPLY=( $(compgen -W "$(printf "read \nwrite \nedit \ndelete \nlist ")" -- ${cur}) )
;;
"sdb")
COMPREPLY=( $(compgen -W "$(printf "create \ndelete \nupdate ")" -- ${cur}) )
;;
*)
# no autocomplete
;;
esac
# cerberus <command> <command> <path to sdb/file/secret>
elif [[ ${COMP_CWORD} -eq 3 ]]; then
# grab secondary command
local command=${COMP_WORDS[COMP_CWORD-2]}
# Internal field separator
IFS=$'\t\n\ '
# switch on secondary command
case "$command" in
"file"|"secret")
# count number of slashes
NUMSLASH=$(echo ${cur} | grep -o / | wc -l | xargs echo)
# empty completion
completion=""
# switch on number of slashes
case "${NUMSLASH}" in
"0")
# list categories
completion=$(cerberus category list -q)
;;
"1")
# list SDBs
completion=$(cerberus sdb list -a -q -c "${cur}")
;;
*)
# change IFS to newline only
IFS=$'\n'
# isolate path to sdb from what has been typed
sdbpath="$(echo ${cur} | sed -e 's/\(.*\)\/.*/\1/')""/"
# remove escaped spaces
sdbpath="$(echo ${sdbpath} | sed -e 's/\\//g')"
# list secrets or files
list="$(cerberus ${command} list "${sdbpath}" -a -q)"
# if list not empty
if [[ ${#list} -gt 0 ]]; then
# use printf to separate fields using IFS
completion="$(printf ${list})"
fi
;;
esac
# construct COMPREPLY with completion
COMPREPLY=( $(compgen -W "${completion}" -- ${cur}) )
;;
"sdb")
# count number of slashes
NUMSLASH=$(echo ${cur} | grep -o / | wc -l | xargs echo)
# empty completion
completion=""
# no completion for create command
if [[ ${prev} != "create" ]]; then
# switch on number of slashes
case "${NUMSLASH}" in
"0")
# list categories
completion=$(cerberus category list -q)
;;
"1")
# list SDBs
completion=$(cerberus sdb list -a -q -c "${cur}")
;;
*)
# no autocomplete
;;
esac
fi
# construct COMPREPLY with completion
COMPREPLY=( $(compgen -W "${completion}" -- ${cur}) )
;;
*)
# no autocomplete
;;
esac
local escaped_single_quote="'\''"
local i=0
# correctly escape all autocompletion entries
for entry in ${COMPREPLY[*]}
do
if [[ "${cur:0:1}" == "'" ]]
then
# started with single quote, escaping only other single quotes
# [']bla'bla"bla\bla bla --> [']bla'\''bla"bla\bla bla
COMPREPLY[$i]="${entry//\'/${escaped_single_quote}}"
elif [[ "${cur:0:1}" == "\"" ]]
then
# started with double quote, escaping all double quotes and all backslashes
# ["]bla'bla"bla\bla bla --> ["]bla'bla\"bla\\bla bla
entry="${entry//\\/\\\\}"
COMPREPLY[$i]="${entry//\"/\\\"}"
else
# no quotes in front, escaping _everything_
# [ ]bla'bla"bla\bla bla --> [ ]bla\'bla\"bla\\bla\ bla
entry="${entry//\\/\\\\}"
entry="${entry//\'/\'}"
entry="${entry//\"/\\\"}"
COMPREPLY[$i]="${entry// /\\ }"
fi
(( i++ ))
done
# append spaces to all non-empty autocompletion entries that end with a slash
for (( i=0; i<${#COMPREPLY[@]}; i++ ));
do
if [[ "${COMPREPLY[$i]}" != */ ]] && [[ "${COMPREPLY[$1]}" != "" ]]; then
COMPREPLY[$i]+=" "
fi
done
fi
return 0
} &&
complete -o nospace -o default -F _cerberus_complete cerberus
|
#!/bin/bash
r=`basename $0`
if [ $r == 'weeklyreminders.sh' ];
then
t=14;
w=Weekly;
elif [ $r == 'dailyreminders.sh' ];
then
t=3;
w=Daily;
else
t=5
w=Test;
fi
cd .rem
for d in * ;
do
if [ "$( ls -A $d/$w 2>/dev/null )" ];
then
echo "Sending a $w reminder to $d"
ft=/tmp/$d-t-$$.txt
f=/tmp/$d-$$.txt
echo "Reminders for next $t days:" >> $f
cat /dev/null > $d/ical2rem
for c in $d/*.ics
do
calname=`basename $c .ics | tr a-z A-Z`
cat $c 2>/dev/null | sed -e "s/^SUMMARY:/SUMMARY: {${calname}} /" \
| sed -e 's/DT\([A-Z]*\);TZID=UTC:\([0-9T]*\)/DT\1:\2Z/' >> $ft
done
cat $ft | ~/bin/ical2rem.pl --label "Online Calendar" --heading "PRIORITY 9999" --lead-time $t >> $d/ical2rem
if [ -e $d/reminders ];then r="${d}/reminders"; else r="${d}/ical2rem";fi
/usr/bin/remind -q -iplain=1 $r >> $f
echo "
All calendars can be accessed by logging into https://calendar.google.com/ as $d@jalcorn.net
" >> $f
cat $f | mail -s "$w Reminders for $d" $d@jalcorn.net;
cat $f
rm $f
rm $ft
fi;
done
|
# bash completion for salticid
_salticid_complete() {
local cur goals
COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
goals="$(salticid --show all-tasks)"
cur=`echo $cur | sed 's/\\\\//g'`
COMPREPLY=($(compgen -W "${goals}" "${cur}" | sed 's/\\\\//g') )
}
complete -F _salticid_complete -o filenames salticid
|
def max_difference(arr):
max_diff = 0
for i in range(0, len(arr)):
for j in range(i+1, len(arr)):
diff = arr[j]-arr[i]
if(diff > max_diff):
max_diff = diff
return max_diff
array = [2, 9, 4, 1, 5]
print("Maximum difference =", max_difference(array)) |
def generate_password():
'''This function generates a random password of 10 alphanumeric characters that also contains at least 1 special character'''
# Initialize an empty string
password = ''
# Populate the string with alphanumeric characters
for i in range(9):
password += random.choice(string.ascii_letters + string.digits)
# Add at least one special character
password += random.choice(string.punctuation)
# Return the generated password
return password |
for num in range(1, 20):
if num % 5 == 0:
print(num) |
# shell script version of the utest test framework
tests_ok=0
tests_failed=0
utest_running() {
echo -n "$1: "
}
utest_ok() {
tests_ok=`echo $tests_ok + 1 | bc`
echo OK
}
utest_fail() {
tests_failed=`echo $tests_failed + 1 | bc`
echo FAILED
}
utest_run() {
for t in $*; do
utest_running $t
if $t; then
utest_ok
else
utest_fail
fi
done
}
utest_report() {
echo "`echo $tests_failed + $tests_ok | bc` tests run; $tests_ok successes and $tests_failed failures."
if [ "$tests_failed" -eq 0 ]; then
return 0
else
return 1
fi
}
utest_chk() {
if [ "$#" -eq 2 -a "$1" = "$2" ]; then
utest_ok
else
utest_fail
fi
}
utest_chknoerr() {
if [ "$?" = 0 ]; then
utest_ok
else
utest_fail
fi
}
|
#!/usr/bin/env bash
################################################################################
### Release a new version of tekton-watcher.
###
### This script joins all manifest files into a single one and creates a
### corresponding Github release.
################################################################################
set -euo pipefail
cur_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" > /dev/null && pwd )"
version=$1
join_manifests() {
local readonly file=/tmp/tekton-watcher-${version}.yaml
local readonly year=$(date +'%Y')
cat > $file<<EOF
# Copyright ${year} Nubank
#
# 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.
EOF
for manifest in $(ls -d $cur_dir/../app/*); do
cat $manifest >> $file
echo '---' >> $file
done
mkdir -p ${cur_dir}/../target
mv $file ${cur_dir}/../target/
}
create_release() {
hub release create "v${version}" \
--message "tekton-watcher $version" \
--attach ${cur_dir}/../target/tekton-watcher-${version}.yaml
}
dirty=$(git status --porcelain)
if [ ! -z "$dirty" ]; then
>&2 echo "Error: your working tree is dirty. Aborting release."
exit 1
fi
echo "Releasing tekton-watcher version ${version}"
join_manifests
create_release
|
import type {Collection, JSCodeshift, TSPropertySignature, TSTypeAnnotation, TSTypeReference} from 'jscodeshift';
function makeTypeName(str: string) {
const a = /^(.*)(Query|Mutation|Subscription)$/.exec(str);
if (!a) throw new Error('Query or Mutation is named wrong');
return `${a[1]}Type`;
}
function dig(typeAnno: TSTypeAnnotation['typeAnnotation']): TSTypeAnnotation['typeAnnotation'] {
if (typeAnno.type === 'TSTypeReference') {
if (typeAnno.typeName.type === 'Identifier' || typeAnno.typeName.type === 'TSQualifiedName') {
const tp = typeAnno.typeParameters;
if (tp && tp.type === 'TSTypeParameterInstantiation' && tp.params.length > 0) {
return dig(tp.params[0]);
}
}
}
return typeAnno;
}
export function addCustomGraphqlType(root: Collection, j: JSCodeshift) {
// Find the return type name
// Looks for something like 'useQuery<GetSomethingQuery, ...>'
const u = root.find(j.CallExpression).filter(v => {
if (v.node.callee.type === 'MemberExpression') {
if (v.node.callee.property.type === 'Identifier') {
return v.node.callee.property.name === 'useQuery' || v.node.callee.property.name === 'useMutation' || v.node.callee.property.name === 'useSubscription';
}
}
return false;
});
if (u.length !== 1) throw new Error('One mutation, query, or subscription should exist in this file.');
// Get the first generic parameters. ie. 'GetSomethingQuery'
// @ts-ignore 'typeParameters' exists, but jscodeshift doesn't think so.
const returnTypeName = u.nodes()[0].typeParameters.params[0].typeName.name;
// Find the reference type (very dependant on how codegen creates types!)
const t = root.find(j.ExportNamedDeclaration, {declaration: {type: 'TSTypeAliasDeclaration', id: {name: returnTypeName}}});
if (t.length !== 1) throw new Error(`There must be a type alias declaration of: ${returnTypeName}`);
// @ts-ignore
const querySpecifier: TSPropertySignature = t.nodes()[0].declaration.typeAnnotation.members[0];
if (querySpecifier.key.type !== 'Identifier') throw new Error(`Query specifier must have a name`);
const querySpecifierName = querySpecifier.key.name; // Should be something like 'getSomething'
const r = dig(querySpecifier.typeAnnotation?.typeAnnotation as TSTypeAnnotation);
// console.log('-------');
// console.log(j(r).toSource());
// console.log('-------');
t.insertAfter(`export type ${makeTypeName(returnTypeName)} = ${j(r).toSource()};`);
}
|
# Custom Script for Linux
#!/bin/bash
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
set -ex
Lamp_on_azure_configs_json_path=${1}
. ./helper_functions.sh
get_setup_params_from_configs_json $Lamp_on_azure_configs_json_path || exit 99
echo $glusterNode >> /tmp/vars.txt
echo $glusterVolume >> /tmp/vars.txt
echo $siteFQDN >> /tmp/vars.txt
echo $httpsTermination >> /tmp/vars.txt
echo $syslogServer >> /tmp/vars.txt
echo $webServerType >> /tmp/vars.txt
echo $dbServerType >> /tmp/vars.txt
echo $fileServerType >> /tmp/vars.txt
echo $storageAccountName >> /tmp/vars.txt
echo $storageAccountKey >> /tmp/vars.txt
echo $nfsVmName >> /tmp/vars.txt
echo $nfsByoIpExportPath >> /tmp/vars.txt
echo $htmlLocalCopySwitch >> /tmp/vars.txt
echo $adminpass >> /tmp/vars.txt
echo $dbadminlogin >> /tmp/vars.txt
echo $serverName >> /tmp/vars.txt
echo $Lampdbname >> /tmp/vars.txt
# check_fileServerType_param $fileServerType
{
# make sure the system does automatic update
sudo apt-get -y update
sudo apt-get -y install unattended-upgrades
# install pre-requisites
sudo apt-get -y install python-software-properties unzip rsyslog
sudo apt-get -y install postgresql-client mysql-client git
#configure gluster repository & install gluster client
sudo add-apt-repository ppa:gluster/glusterfs-3.10 -y
sudo apt-get -y update
sudo apt-get -y install glusterfs-client
# Set up a silent install of MySQL
export DEBIAN_FRONTEND=noninteractive
echo mysql-server-5.6 mysql-server/root_password password $adminpass | debconf-set-selections
echo mysql-server-5.6 mysql-server/root_password_again password $adminpass | debconf-set-selections
# install the base stack
sudo apt-get -y install varnish php php-cli php-curl php-zip php-pear php-mbstring php-dev mcrypt
if [ "$webServerType" = "nginx" -o "$httpsTermination" = "VMSS" ]; then
sudo apt-get -y install nginx
fi
# install apache pacakges
sudo apt-get -y install apache2 libapache2-mod-php
# Lamp requirements
sudo apt-get install -y graphviz aspell php-soap php-json php-redis php-bcmath php-gd php-pgsql php-mysql php-xmlrpc php-intl php-xml php-bz2
# PHP Version
PhpVer=$(get_php_version)
# Mount gluster fs for /azlamp
sudo mkdir -p /azlamp
sudo chown www-data /azlamp
sudo chmod 770 /azlamp
sudo echo -e 'Adding Gluster FS to /etc/fstab and mounting it'
setup_and_mount_gluster_share $glusterNode $glusterVolume /azlamp
#SetUp Of WordPress On Virtual machone
# setup_wordpress_on_vm $Lampdbname $dbadminlogin $adminpass $serverName
# Configure syslog to forward
cat <<EOF >> /etc/rsyslog.conf
\$ModLoad imudp
\$UDPServerRun 514
EOF
cat <<EOF >> /etc/rsyslog.d/40-remote.conf
local1.* @${syslogServer}:514
local2.* @${syslogServer}:514
EOF
service syslog restart
if [ "$webServerType" = "nginx" -o "$httpsTermination" = "VMSS" ]; then
# Build nginx config
cat <<EOF > /etc/nginx/nginx.conf
user www-data;
worker_processes 2;
pid /run/nginx.pid;
events {
worker_connections 2048;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 0;
proxy_max_temp_file_size 0;
server_names_hash_bucket_size 128;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
proxy_buffering off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
EOF
if [ "$httpsTermination" != "None" ]; then
cat <<EOF >> /etc/nginx/nginx.conf
map \$http_x_forwarded_proto \$fastcgi_https {
default \$https;
http '';
https on;
}
EOF
fi
cat <<EOF >> /etc/nginx/nginx.conf
log_format Lamp_combined '\$remote_addr - \$upstream_http_x_Lampuser [\$time_local] '
'"\$request" \$status \$body_bytes_sent '
'"\$http_referer" "\$http_user_agent"';
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
EOF
fi # if [ "$webServerType" = "nginx" -o "$httpsTermination" = "VMSS" ];
# Set up html dir local copy if specified
mkdir -p /var/www/html
rsync -av --delete /azlamp/html/. /var/www/html
setup_html_local_copy_cron_job
# Configure Apache/php
sed -i "s/Listen 80/Listen 81/" /etc/apache2/ports.conf
a2enmod rewrite && a2enmod remoteip && a2enmod headers
config_all_sites_on_vmss $htmlLocalCopySwitch $httpsTermination $webServerType
# php config
PhpIni=/etc/php/${PhpVer}/apache2/php.ini
sed -i "s/memory_limit.*/memory_limit = 512M/" $PhpIni
sed -i "s/max_execution_time.*/max_execution_time = 18000/" $PhpIni
sed -i "s/max_input_vars.*/max_input_vars = 100000/" $PhpIni
sed -i "s/max_input_time.*/max_input_time = 600/" $PhpIni
sed -i "s/upload_max_filesize.*/upload_max_filesize = 1024M/" $PhpIni
sed -i "s/post_max_size.*/post_max_size = 1056M/" $PhpIni
sed -i "s/;opcache.use_cwd.*/opcache.use_cwd = 1/" $PhpIni
sed -i "s/;opcache.validate_timestamps.*/opcache.validate_timestamps = 1/" $PhpIni
sed -i "s/;opcache.save_comments.*/opcache.save_comments = 1/" $PhpIni
sed -i "s/;opcache.enable_file_override.*/opcache.enable_file_override = 0/" $PhpIni
sed -i "s/;opcache.enable.*/opcache.enable = 1/" $PhpIni
sed -i "s/;opcache.memory_consumption.*/opcache.memory_consumption = 256/" $PhpIni
sed -i "s/;opcache.max_accelerated_files.*/opcache.max_accelerated_files = 8000/" $PhpIni
# Remove the default site. Lamp is the only site we want
rm -f /etc/nginx/sites-enabled/default_type
rm -f /etc/apache2/sites-enabled/000-default.conf
setup_azlamp_mount_dependency_for_systemd_service apache2 || exit 1
sudo service apache2 restart
# Configure varnish startup for 16.04
VARNISHSTART="ExecStart=\/usr\/sbin\/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f \/etc\/varnish\/Lamp.vcl -S \/etc\/varnish\/secret -s malloc,1024m -p thread_pool_min=200 -p thread_pool_max=4000 -p thread_pool_add_delay=2 -p timeout_linger=100 -p timeout_idle=30 -p send_timeout=1800 -p thread_pools=4 -p http_max_hdr=512 -p workspace_backend=512k"
sed -i "s/^ExecStart.*/${VARNISHSTART}/" /lib/systemd/system/varnish.service
# Configure varnish VCL for Lamp
cat <<EOF >> /etc/varnish/Lamp.vcl
vcl 4.0;
import std;
import directors;
backend default {
.host = "localhost";
.port = "81";
.first_byte_timeout = 3600s;
.connect_timeout = 600s;
.between_bytes_timeout = 600s;
}
sub vcl_recv {
# Varnish does not support SPDY or HTTP/2.0 untill we upgrade to Varnish 5.0
if (req.method == "PRI") {
return (synth(405));
}
if (req.restarts == 0) {
if (req.http.X-Forwarded-For) {
set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", " + client.ip;
} else {
set req.http.X-Forwarded-For = client.ip;
}
}
# Non-RFC2616 or CONNECT HTTP requests methods filtered. Pipe requests directly to backend
if (req.method != "GET" &&
req.method != "HEAD" &&
req.method != "PUT" &&
req.method != "POST" &&
req.method != "TRACE" &&
req.method != "OPTIONS" &&
req.method != "DELETE") {
return (pipe);
}
# Varnish don't mess with healthchecks
if (req.url ~ "^/admin/tool/heartbeat" || req.url ~ "^/healthcheck.php")
{
return (pass);
}
# Pipe requests to backup.php straight to backend - prevents problem with progress bar long polling 503 problem
# This is here because backup.php is POSTing to itself - Filter before !GET&&!HEAD
if (req.url ~ "^/backup/backup.php")
{
return (pipe);
}
# Varnish only deals with GET and HEAD by default. If request method is not GET or HEAD, pass request to backend
if (req.method != "GET" && req.method != "HEAD") {
return (pass);
}
### Rules for Lamp and Totara sites ###
# Lamp doesn't require Cookie to serve following assets. Remove Cookie header from request, so it will be looked up.
if ( req.url ~ "^/altlogin/.+/.+\.(png|jpg|jpeg|gif|css|js|webp)$" ||
req.url ~ "^/pix/.+\.(png|jpg|jpeg|gif)$" ||
req.url ~ "^/theme/font.php" ||
req.url ~ "^/theme/image.php" ||
req.url ~ "^/theme/javascript.php" ||
req.url ~ "^/theme/jquery.php" ||
req.url ~ "^/theme/styles.php" ||
req.url ~ "^/theme/yui" ||
req.url ~ "^/lib/javascript.php/-1/" ||
req.url ~ "^/lib/requirejs.php/-1/"
)
{
set req.http.X-Long-TTL = "86400";
unset req.http.Cookie;
return(hash);
}
# Perform lookup for selected assets that we know are static but Lamp still needs a Cookie
if( req.url ~ "^/theme/.+\.(png|jpg|jpeg|gif|css|js|webp)" ||
req.url ~ "^/lib/.+\.(png|jpg|jpeg|gif|css|js|webp)" ||
req.url ~ "^/pluginfile.php/[0-9]+/course/overviewfiles/.+\.(?i)(png|jpg)$"
)
{
# Set internal temporary header, based on which we will do things in vcl_backend_response
set req.http.X-Long-TTL = "86400";
return (hash);
}
# Serve requests to SCORM checknet.txt from varnish. Have to remove get parameters. Response body always contains "1"
if ( req.url ~ "^/lib/yui/build/Lamp-core-checknet/assets/checknet.txt" )
{
set req.url = regsub(req.url, "(.*)\?.*", "\1");
unset req.http.Cookie; # Will go to hash anyway at the end of vcl_recv
set req.http.X-Long-TTL = "86400";
return(hash);
}
# Requests containing "Cookie" or "Authorization" headers will not be cached
if (req.http.Authorization || req.http.Cookie) {
return (pass);
}
# Almost everything in Lamp correctly serves Cache-Control headers, if
# needed, which varnish will honor, but there are some which don't. Rather
# than explicitly finding them all and listing them here we just fail safe
# and don't cache unknown urls that get this far.
return (pass);
}
sub vcl_backend_response {
# Happens after we have read the response headers from the backend.
#
# Here you clean the response headers, removing silly Set-Cookie headers
# and other mistakes your backend does.
# We know these assest are static, let's set TTL >0 and allow client caching
if ( beresp.http.Cache-Control && bereq.http.X-Long-TTL && beresp.ttl < std.duration(bereq.http.X-Long-TTL + "s", 1s) && !beresp.http.WWW-Authenticate )
{ # If max-age < defined in X-Long-TTL header
set beresp.http.X-Orig-Pragma = beresp.http.Pragma; unset beresp.http.Pragma;
set beresp.http.X-Orig-Cache-Control = beresp.http.Cache-Control;
set beresp.http.Cache-Control = "public, max-age="+bereq.http.X-Long-TTL+", no-transform";
set beresp.ttl = std.duration(bereq.http.X-Long-TTL + "s", 1s);
unset bereq.http.X-Long-TTL;
}
else if( !beresp.http.Cache-Control && bereq.http.X-Long-TTL && !beresp.http.WWW-Authenticate ) {
set beresp.http.X-Orig-Pragma = beresp.http.Pragma; unset beresp.http.Pragma;
set beresp.http.Cache-Control = "public, max-age="+bereq.http.X-Long-TTL+", no-transform";
set beresp.ttl = std.duration(bereq.http.X-Long-TTL + "s", 1s);
unset bereq.http.X-Long-TTL;
}
else { # Don't touch headers if max-age > defined in X-Long-TTL header
unset bereq.http.X-Long-TTL;
}
# Here we set X-Trace header, prepending it to X-Trace header received from backend. Useful for troubleshooting
if(beresp.http.x-trace && !beresp.was_304) {
set beresp.http.X-Trace = regsub(server.identity, "^([^.]+),?.*$", "\1")+"->"+regsub(beresp.backend.name, "^(.+)\((?:[0-9]{1,3}\.){3}([0-9]{1,3})\)","\1(\2)")+"->"+beresp.http.X-Trace;
}
else {
set beresp.http.X-Trace = regsub(server.identity, "^([^.]+),?.*$", "\1")+"->"+regsub(beresp.backend.name, "^(.+)\((?:[0-9]{1,3}\.){3}([0-9]{1,3})\)","\1(\2)");
}
# Gzip JS, CSS is done at the ngnix level doing it here dosen't respect the no buffer requsets
# if (beresp.http.content-type ~ "application/javascript.*" || beresp.http.content-type ~ "text") {
# set beresp.do_gzip = true;
#}
}
sub vcl_deliver {
# Revert back to original Cache-Control header before delivery to client
if (resp.http.X-Orig-Cache-Control)
{
set resp.http.Cache-Control = resp.http.X-Orig-Cache-Control;
unset resp.http.X-Orig-Cache-Control;
}
# Revert back to original Pragma header before delivery to client
if (resp.http.X-Orig-Pragma)
{
set resp.http.Pragma = resp.http.X-Orig-Pragma;
unset resp.http.X-Orig-Pragma;
}
# (Optional) X-Cache HTTP header will be added to responce, indicating whether object was retrieved from backend, or served from cache
if (obj.hits > 0) {
set resp.http.X-Cache = "HIT";
} else {
set resp.http.X-Cache = "MISS";
}
# Set X-AuthOK header when totara/varnsih authentication succeeded
if (req.http.X-AuthOK) {
set resp.http.X-AuthOK = req.http.X-AuthOK;
}
# If desired "Via: 1.1 Varnish-v4" response header can be removed from response
unset resp.http.Via;
unset resp.http.Server;
return(deliver);
}
sub vcl_backend_error {
# More comprehensive varnish error page. Display time, instance hostname, host header, url for easier troubleshooting.
set beresp.http.Content-Type = "text/html; charset=utf-8";
set beresp.http.Retry-After = "5";
synthetic( {"
<!DOCTYPE html>
<html>
<head>
<title>"} + beresp.status + " " + beresp.reason + {"</title>
</head>
<body>
<h1>Error "} + beresp.status + " " + beresp.reason + {"</h1>
<p>"} + beresp.reason + {"</p>
<h3>Guru Meditation:</h3>
<p>Time: "} + now + {"</p>
<p>Node: "} + server.hostname + {"</p>
<p>Host: "} + bereq.http.host + {"</p>
<p>URL: "} + bereq.url + {"</p>
<p>XID: "} + bereq.xid + {"</p>
<hr>
<p>Varnish cache server
</body>
</html>
"} );
return (deliver);
}
sub vcl_synth {
#Redirect using '301 - Permanent Redirect', permanent redirect
if (resp.status == 851) {
set resp.http.Location = req.http.x-redir;
set resp.http.X-Varnish-Redirect = true;
set resp.status = 301;
return (deliver);
}
#Redirect using '302 - Found', temporary redirect
if (resp.status == 852) {
set resp.http.Location = req.http.x-redir;
set resp.http.X-Varnish-Redirect = true;
set resp.status = 302;
return (deliver);
}
#Redirect using '307 - Temporary Redirect', !GET&&!HEAD requests, dont change method on redirected requests
if (resp.status == 857) {
set resp.http.Location = req.http.x-redir;
set resp.http.X-Varnish-Redirect = true;
set resp.status = 307;
return (deliver);
}
#Respond with 403 - Forbidden
if (resp.status == 863) {
set resp.http.X-Varnish-Error = true;
set resp.status = 403;
return (deliver);
}
}
EOF
# Restart Varnish
systemctl daemon-reload
service varnish restart
} > /tmp/setup.log
|
<filename>src/main/java/com/test/MyFirstFeature.java
package com.test;
public class MyFirstFeature {
public String getFeatureMethod(boolean isThrowException) throws Exception {
if (isThrowException) {
throw new Exception("this is my exception");
}
return "test-value";
}
}
|
<gh_stars>1-10
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package models.fe.tradingpremises
import models.des.tradingpremises.Msb
import play.api.libs.json._
import utils.CommonMethods
sealed trait MsbService
case object TransmittingMoney extends MsbService
case object CurrencyExchange extends MsbService
case object ChequeCashingNotScrapMetal extends MsbService
case object ChequeCashingScrapMetal extends MsbService
case object ForeignExchange extends MsbService
case class MsbServices(msbServices : Set[MsbService])
object MsbService {
implicit val jsonR: Reads[MsbService] =
Reads {
case JsString("01") => JsSuccess(TransmittingMoney)
case JsString("02") => JsSuccess(CurrencyExchange)
case JsString("03") => JsSuccess(ChequeCashingNotScrapMetal)
case JsString("04") => JsSuccess(ChequeCashingScrapMetal)
case JsString("05") => JsSuccess(ForeignExchange)
case _ => JsError(JsPath -> JsonValidationError("error.invalid"))
}
implicit val jsonW = Writes[MsbService] {
case TransmittingMoney => JsString("01")
case CurrencyExchange => JsString("02")
case ChequeCashingNotScrapMetal => JsString("03")
case ChequeCashingScrapMetal => JsString("04")
case ForeignExchange => JsString("05")
}
}
object MsbServices {
implicit val formats = Json.format[MsbServices]
implicit def convMsb(msb: Msb): Option[MsbServices]= {
val `empty` = Set.empty[MsbService]
val services = Set(CommonMethods.getSpecificType[MsbService](msb.mt, TransmittingMoney),
CommonMethods.getSpecificType[MsbService](msb.ce, CurrencyExchange),
CommonMethods.getSpecificType[MsbService](msb.nonSmdcc, ChequeCashingNotScrapMetal),
CommonMethods.getSpecificType[MsbService](msb.smdcc, ChequeCashingScrapMetal),
CommonMethods.getSpecificType[MsbService](msb.fx, ForeignExchange)).flatten
services match {
case `empty` => None
case _ => Some(MsbServices(services))
}
}
}
|
#!/bin/sh
set -e
set -u
set -o pipefail
function on_error {
echo "$(realpath -mq "${0}"):$1: error: Unexpected failure"
}
trap 'on_error $LINENO' ERR
if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then
# If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy
# frameworks to, so exit 0 (signalling the script phase was successful).
exit 0
fi
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
# Used as a return value for each invocation of `strip_invalid_archs` function.
STRIP_BINARY_RETVAL=0
# This protects against multiple targets copying the same framework dependency at the same time. The solution
# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html
RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????")
# Copies and strips a vendored framework
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
elif [ -r "$1" ]; then
local source="$1"
fi
local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
# Use filter instead of exclude so missing patterns don't throw errors.
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
local basename
basename="$(basename -s .framework "$1")"
binary="${destination}/${basename}.framework/${basename}"
if ! [ -r "$binary" ]; then
binary="${destination}/${basename}"
elif [ -L "${binary}" ]; then
echo "Destination binary is symlinked..."
dirname="$(dirname "${binary}")"
binary="${dirname}/$(readlink "${binary}")"
fi
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
strip_invalid_archs "$binary"
fi
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u)
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
fi
}
# Copies and strips a vendored dSYM
install_dsym() {
local source="$1"
if [ -r "$source" ]; then
# Copy the dSYM into a the targets temp dir.
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}"
local basename
basename="$(basename -s .framework.dSYM "$source")"
binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}"
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then
strip_invalid_archs "$binary"
fi
if [[ $STRIP_BINARY_RETVAL == 1 ]]; then
# Move the stripped file into its final destination.
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}"
else
# The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing.
touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM"
fi
fi
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identity
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'"
if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then
code_sign_cmd="$code_sign_cmd &"
fi
echo "$code_sign_cmd"
eval "$code_sign_cmd"
fi
}
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
# Get architectures for current target binary
binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)"
# Intersect them with the architectures we are building for
intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)"
# If there are no archs supported by this binary then warn the user
if [[ -z "$intersected_archs" ]]; then
echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)."
STRIP_BINARY_RETVAL=0
return
fi
stripped=""
for arch in $binary_archs; do
if ! [[ "${ARCHS}" == *"$arch"* ]]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary"
stripped="$stripped $arch"
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
STRIP_BINARY_RETVAL=1
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/BGLDUtilsKit-kit/BGLDUtilsKit_kit.framework"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/BGLDUtilsKit-kit/BGLDUtilsKit_kit.framework"
fi
if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then
wait
fi
|
package com.zebra.domain;
public class OtherInfo{
private String reportTimeStr;
private Integer appTypeCode = 0;
private Long procdureStartTime = 0L;
private Long procdureEndTime = 0L;
private Long trafficUL = 0L;
private Long trafficDL = 0L;
private Long retranUL = 0L;
private Long retranDL = 0L;
private Integer transStatus = -1;
private String interruptType = "fail";
public Long getTrafficUL() {
return trafficUL;
}
public void setTrafficUL(Long trafficUL) {
this.trafficUL = trafficUL;
}
public Long getTrafficDL() {
return trafficDL;
}
public void setTrafficDL(Long trafficDL) {
this.trafficDL = trafficDL;
}
public Long getRetranUL() {
return retranUL;
}
public void setRetranUL(Long retranUL) {
this.retranUL = retranUL;
}
public Long getRetranDL() {
return retranDL;
}
public void setRetranDL(Long retranDL) {
this.retranDL = retranDL;
}
public String getReportTimeStr() {
return reportTimeStr;
}
public void setReportTimeStr(String reportTimeStr) {
this.reportTimeStr = reportTimeStr;
}
public Integer getAppTypeCode() {
return appTypeCode;
}
public void setAppTypeCode(Integer appTypeCode) {
this.appTypeCode = appTypeCode;
}
public Long getProcdureStartTime() {
return procdureStartTime;
}
public void setProcdureStartTime(Long procdureStartTime) {
this.procdureStartTime = procdureStartTime;
}
public Long getProcdureEndTime() {
return procdureEndTime;
}
public void setProcdureEndTime(Long procdureEndTime) {
this.procdureEndTime = procdureEndTime;
}
public Integer getTransStatus() {
return transStatus;
}
public void setTransStatus(Integer transStatus) {
this.transStatus = transStatus;
}
public String getInterruptType() {
return interruptType;
}
public void setInterruptType(String interruptType) {
this.interruptType = interruptType;
}
}
|
export default {
namespace: 'app',
state: {
chartRoute: {
group: 'bar',
type: 'bar-basic-column',
query: {},
},
},
subscriptions: {
setup({ dispatch, history }) {
return history.listen(({ pathname }) => {
const { query } = history.location;
dispatch({
type: 'changeChartRoute',
payload: {
pathname,
query,
},
});
});
},
},
effects: {},
reducers: {
changeChartRoute(state, { payload }) {
const { pathname, query } = payload;
const arrData = pathname.split('?');
const arr = arrData[0].substr(1).split('/');
const [group, type] = arr;
return {
...state,
chartRoute: {
group,
type,
query,
},
};
},
},
};
|
<gh_stars>1-10
package app.habitzl.elasticsearch.status.monitor.tool.client.data.shard;
import javax.annotation.concurrent.Immutable;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;
@Immutable
public class NodeAllocationDecision {
private final String nodeId;
private final String nodeName;
private final List<String> decisions;
public NodeAllocationDecision(final String nodeId, final String nodeName, final List<String> decisions) {
this.nodeId = nodeId;
this.nodeName = nodeName;
this.decisions = Objects.isNull(decisions) ? List.of() : List.copyOf(decisions);
}
public String getNodeId() {
return nodeId;
}
public String getNodeName() {
return nodeName;
}
public List<String> getDecisions() {
return decisions;
}
@Override
@SuppressWarnings("CyclomaticComplexity")
public boolean equals(final Object o) {
boolean isEqual;
if (this == o) {
isEqual = true;
} else if (o == null || getClass() != o.getClass()) {
isEqual = false;
} else {
NodeAllocationDecision that = (NodeAllocationDecision) o;
isEqual = Objects.equals(nodeId, that.nodeId)
&& Objects.equals(nodeName, that.nodeName)
&& Objects.equals(decisions, that.decisions);
}
return isEqual;
}
@Override
public int hashCode() {
return Objects.hash(nodeId, nodeName, decisions);
}
@Override
public String toString() {
return new StringJoiner(", ", NodeAllocationDecision.class.getSimpleName() + "[", "]")
.add("nodeId='" + nodeId + "'")
.add("nodeName='" + nodeName + "'")
.add("decisions=" + decisions)
.toString();
}
}
|
#!/usr/bin/python3
"""
Helper class to parse the ini files.
Please note that there is also a python module named configparser. However,
as the example ini module contanined no section header for the first
entry (HOSTKEY), we wrote our own
"""
class IniParser:
"""
Initializes a DHT_TRACE_REPLY message to send later.
:param filename: The filename. Example: "config.ini"
:type filename: string
"""
def __init__(self, filename):
self.data = {}
self.read_file(filename)
def read_file(self, filename):
"""
Open a new file and parse it
:param filename: The filename
:type filename: string
"""
currentsection = "" # The current seciotn in the parser (like [DHT] for example)
self.data = {}
self.data[currentsection] = {}
with open(filename) as f:
for line in f:
if line.strip()!="":
try:
if line != "":
if line.startswith('['):
currentsection = line.strip()[1:-1]
self.data[currentsection] = {}
else:
ar = line.split('=', 1 )
self.data[currentsection][ar[0].strip()] = ar[1].strip()
except:
print("NOTE: Could not parse line:", line)
def get(self, attribute, section=""):
"""
get an attribute of an ini file
:param attribute: The attribute
:param section: The section. Default is no section
:type attribute: string
:Example:
.. code-block:: python
#test.ini:
#[DHT]
#PORT = 123
inip = IniParser("test.ini")
inip.get("PORT", "DHT") # returns 123
"""
if section in self.data and attribute in self.data[section]:
return self.data[section][attribute]
else:
return None
|
#!/bin/bash
ARGS=$@
TESTS=${ARGS:=test*.py}
pytest --capture=no ${TESTS}
echo "Tests complete. All tests should be successful."
echo "Running rebot to get the HTML report and log file."
rebot output.xml
|
package com.google.teampot.model;
import com.google.api.server.spi.config.AnnotationBoolean;
import com.google.api.server.spi.config.ApiResourceProperty;
import com.google.api.services.bigquery.model.TableRow;
import com.google.teampot.tablerow.ProjectActivityEventTableRowWriter;
import com.google.teampot.tablerow.TaskActivityEventTableRowWriter;
import com.google.teampot.transformer.Enum2StringTransformer;
import com.google.teampot.transformer.Ref2EntityTransformer;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.annotation.Subclass;
@Subclass(index=true)
public class ProjectActivityEvent extends ActivityEvent {
private ProjectActivityEventVerb verb;
public ProjectActivityEvent() {
// TODO Auto-generated constructor stub
}
public ProjectActivityEvent(Project project, User actor, ProjectActivityEventVerb verb) {
super();
this.setProject(project);
this.setActor(actor);
this.setVerb(verb);
}
public ProjectActivityEvent(Project project, User actor) {
this(project,actor,null);
}
@ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public Ref<Project> getProject() {
return project;
}
@ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public void setProject(Ref<Project> project) {
this.project = project;
}
@ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public void setProject(Project project) {
this.project = Ref.create(project);
}
@ApiResourceProperty(name = "project")
public Project getProjectEntity() {
Ref2EntityTransformer<Project> t = new Ref2EntityTransformer<Project>();
return t.transformTo(this.project);
}
@ApiResourceProperty(name = "project")
public void setProjectEntity(Project task) {
Ref2EntityTransformer<Project> t = new Ref2EntityTransformer<Project>();
this.project = t.transformFrom(task);
}
@ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public ProjectActivityEventVerb getVerb() {
return verb;
}
@ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public void setVerb(ProjectActivityEventVerb verb) {
this.verb = verb;
}
@ApiResourceProperty(name = "verb")
public String getVerbString() {
Enum2StringTransformer<ProjectActivityEventVerb> t = new Enum2StringTransformer<ProjectActivityEventVerb>(ProjectActivityEventVerb.class);
return t.transformTo(this.verb);
}
@ApiResourceProperty(name = "verb")
public void setVerbString(String verb) {
Enum2StringTransformer<ProjectActivityEventVerb> t = new Enum2StringTransformer<ProjectActivityEventVerb>(ProjectActivityEventVerb.class);
this.verb = t.transformFrom(verb);
}
@Override
@ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public TableRow getTableRow() {
return new ProjectActivityEventTableRowWriter(this).getRow();
}
}
|
import numpy as np
from sklearn.linear_model import LinearRegression
# define the features
X = np.array([[temperature], [humidity]])
# define the labels
y = np.array([air_quality])
# create the model
model = LinearRegression()
# fit the model to the data
model.fit(X, y) |
#!/bin/bash
for f in `ls -A poc/*`; do
echo "test $f"
mkdir testdir
./ShellgeiBot -test testconfig.json "$f" &&
[[ "$(ls -A testdir | wc -l)" -eq "0" ]] && echo OK || echo NG
rm -r testdir
echo -e "==============================================\n"
done
|
package de.lmu.cis.ocrd.ml;
import weka.core.Instance;
import weka.core.Instances;
import java.io.Writer;
public class DLEEvaluator {
private final Instances instances;
private final LogisticClassifier classifier;
private final Writer writer;
private final int i;
private int good, bad, missed, total;
public DLEEvaluator(Writer w, LogisticClassifier c, Instances is, int i) {
this.writer = w;
this.classifier = c;
this.instances = is;
this.i = i;
this.good = 0;
this.bad = 0;
this.missed = 0;
this.total = 0;
}
public void evaluate() throws Exception {
for (Instance instance : instances) {
evaluate(instance);
}
writer.write(String.format("total number of tokens: %d\n", total));
writer.write(String.format("number of good extensions: %d\n", good));
writer.write(String.format("number of bad extensions: %d\n", bad));
writer.write(String.format("number of missed opportunities: %d\n", missed));
final String title = String.format(
"===================\nResults (%d):\n", i+1);
final String data = classifier.evaluate(title, instances);
writer.write(data);
}
private void evaluate(Instance instance) throws Exception {
final Prediction p = classifier.predict(instance);
final int gt = (int) instance.classValue();
final int got = (int) p.getValue();
total++;
// 0 is true :(
if (gt == 0) {
if (got == 0) {
good++;
} else {
missed++;
}
} else {
if (got == 0) {
bad++;
}
}
}
}
|
import meeting, { initialState } from './Meeting'
import * as actions from '../actions/Meeting'
describe('Reducers', () => {
describe('WAIT_REQUEST', () => {
it('should wait reqeusts', () => {
expect(meeting(
initialState,
actions.waitRequest()
)).toEqual({...initialState, postDone: false, loadDone: false})
});
});
});
|
<filename>datalad_next/patches/tests/test_push.py
from datalad.tests.utils import (
DEFAULT_REMOTE,
assert_result_count,
with_tempfile,
)
from datalad.distribution.dataset import Dataset
from datalad.core.distributed.clone import Clone
# run all -core tests, because with _push() we patched a central piece
from datalad.core.distributed.tests.test_push import *
# we override this specific test, because the original behavior is no longer
# value, because our implementation behaves "better"
@with_tempfile()
@with_tempfile()
def test_gh1811(srcpath, clonepath):
# `annex=false` is the only change from the -core implementation
# of the test. For normal datasets with an annex, the problem underlying
# gh1811 is no longer valid, because of more comprehensive analysis of
# what needs pushing in this case
orig = Dataset(srcpath).create(annex=False)
(orig.pathobj / 'some').write_text('some')
orig.save()
clone = Clone.__call__(source=orig.path, path=clonepath)
(clone.pathobj / 'somemore').write_text('somemore')
clone.save()
clone.repo.call_git(['checkout', 'HEAD~1'])
res = clone.push(to=DEFAULT_REMOTE, on_failure='ignore')
assert_result_count(res, 1)
assert_result_count(
res, 1,
path=clone.path, type='dataset', action='publish',
status='impossible',
message='There is no active branch, cannot determine remote '
'branch',
)
|
<reponame>suckatrash/puppet-jmxtrans<filename>lib/puppet/functions/jmxtrans/to_json.rb
Puppet::Functions.create_function(:'jmxtrans::to_json') do
dispatch :data_to_json do
param 'Data', :data
end
def data_to_json(data)
require 'json'
data.to_json
end
end
|
#!/usr/bin/env sh
# abort on errors
set -e
# build
npm run build
# navigate into the build output directory
cd dist
git init
git add -A
git commit -m 'deploy'
git push -f git@github.com:miguelsilva5989/vuesort.github.io.git master:gh-pages
### np --help to check release types
cd ..
np minor # to increment release number
# np patch
cd -
|
<reponame>vfreitas-/ShopCar<filename>ShopCar/src/shopcar/view/VendaVeiculo.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package shopcar.view;
import shopcar.entities.Cliente;
import shopcar.entities.Veiculo;
import javax.inject.Inject;
import shopcar.controller.VendeCarro;
import shopcar.repository.JpaDAO;
/**
*
* @author info1
*/
public class VendaVeiculo
{
@Inject private JpaDAO<Veiculo> daoVeiculo;
@Inject private JpaDAO<Cliente> daoCliente;
@Inject private VendeCarro vendeCarro;
public void Vender(String placa)
{
try
{
Veiculo v;
v = daoVeiculo.getById(placa);
Cliente c = daoCliente.getById(Long.valueOf("1"));
vendeCarro.Vender(v, c);
}
catch (Exception e)
{
System.out.println("Erro ao chamar o vende veiculo" + e.getMessage());
}
}
}
|
<filename>public/js/app.js
Vue.http.headers.common['X-CSRF-TOKEN'] = $("meta[name=token]").attr("value");
new Vue({
el: '#appPhone',
data: {
create: false,
searchTerm: '',
phones: [],
phone: {
description: '',
phone: ''
},
errors: {
description: [],
phone: [],
permission: false
},
success: false
},
ready: function() {
this.fetchPhones();
},
methods: {
fetchPhones: function() {
var self = this;
self.$http.get('/api/phones', function(response) {
self.phones = response;
});
},
save: function(e) {
var self = this;
e.preventDefault();
self.$http.post('/api/phones', this.phone, function(response) {
console.log(response);
if (response.success) {
self.create = false;
self.success = true;
self.phones.push(response.data);
} else {
self.errors = response.errors;
}
});
return false;
},
cancel: function(e){
this.create = false;
this.resetErrors();
},
resetErrors: function(e) {
this.errors = {
description: [],
phone: [],
permisson: false
}
}
}
});
//# sourceMappingURL=app.js.map |
<reponame>drkitty/cyder
from parsley import wrapGrammar
from ometa.grammar import OMeta
from ometa.runtime import OMetaBase
from constants import *
from dhcp_objects import (Host, Pool, Parameter, Option, Subnet, Group, Allow,
Deny, ClientClass)
from utils import prepare_arguments, is_mac, is_ip
import sys
from bisect import insort_left, bisect_left
from ipaddr import IPv4Address, IPv6Address
from sys import stdout
def strip_comments(content):
return "".join(line[:line.find('#')] if '#' in line else line for line in content)
grammar = open('cyder/management/commands/lib/dhcpd_compare/'
'isc.parsley').read()
class DhcpConfigContext(
OMeta.makeGrammar(
grammar,
name='DhcpConfigContext').createParserClass(OMetaBase, globals())):
stdout = stdout
def __init__(self, *args, **kwargs):
self.hosts = set()
self.subnets = set()
self.groups = set()
self.classes = set()
self.options = set()
self.parameters = set()
super(DhcpConfigContext, self).__init__(*args, **kwargs)
def apply_attrs(self, host, attrs):
for attr in attrs:
host.add_option_or_parameter(attr)
def add_subnet(self, subnet):
self.subnets.add(subnet)
def add_host(self, host):
self.hosts.add(host)
def add_group(self, group):
self.groups.add(group)
def add_option(self, option):
self.options.add(option)
def add_parameter(self, parameter):
self.parameters.add(parameter)
def add_class(self, dhcp_class):
self.classes.add(dhcp_class)
def add_subclass(self, name, mac):
for _class in self.classes:
if _class.name == name:
_class.add_subclass(mac)
return True
return False
def __eq__(self, other):
return self.hosts == other.hosts and \
self.subnets == other.subnets and \
self.groups == other.groups and \
self.classes == other.classes
def diff(self, other):
if not (self == other):
first_subnets = self.subnets - other.subnets
second_subnets = other.subnets - self.subnets
first_hosts = self.hosts - other.hosts
second_hosts = other.hosts - self.hosts
first_groups = self.groups - other.groups
second_groups = other.groups - self.groups
first_classes = self.classes - other.classes
second_classes = other.classes - self.classes
if first_subnets:
print '### Subnets found only in the first config ###'
for subnet in first_subnets:
stdout.write(str(subnet))
if second_subnets:
print '### Subnets found only in the second config ###'
for subnet in second_subnets:
stdout.write(str(subnet))
if first_hosts:
print '### Hosts found only in the first config ###'
for host in first_hosts:
stdout.write(str(host))
if second_hosts:
print '### Hosts found only in the second config ###'
for host in second_hosts:
stdout.write(str(host))
if first_groups:
print '### Groups found only in the first config ###'
for group in first_groups:
stdout.write(str(group))
if second_groups:
print '### Groups found only in the second config ###'
for group in second_groups:
stdout.write(str(group))
if first_classes:
print '### Classes found only in the first config ###'
for klass in first_classes:
stdout.write(str(klass))
if second_classes:
print '### Classes found only in the second config ###'
for klass in second_classes:
stdout.write(str(klass))
iscgrammar = wrapGrammar(DhcpConfigContext)
def compare(file1, file2):
parse1 = iscgrammar(strip_comments(open(file1))).GlobalParse()
parse2 = iscgrammar(strip_comments(open(file2))).GlobalParse()
parse1.diff(parse2)
|
#!/bin/bash
ROOTFS=$1
# Check if rootfs dir exists
if [ ! -d "${ROOTFS}" ]; then
echo "Missing rootfs (${ROOTFS}) directory."
exit 1
fi
# Mount dev directory to rootfs/dev
sudo -S mount --bind /dev ${ROOTFS}/dev
# Enter chroot environment and run bash with provided arguments
sudo -S chroot ${ROOTFS} env HOME=/root LC_ALL=C /bin/bash $@ |
<reponame>opentaps/opentaps-1
/*
* Copyright (c) Open Source Strategies, Inc.
*
* Opentaps is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Opentaps 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Opentaps. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentaps.financials.domain.billing.lockbox;
import java.util.List;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityUtil;
import org.opentaps.domain.DomainsDirectory;
import org.opentaps.base.entities.EftAccount;
import org.opentaps.base.entities.PaymentMethodAndEftAccount;
import org.opentaps.domain.billing.invoice.Invoice;
import org.opentaps.domain.billing.invoice.InvoiceRepositoryInterface;
import org.opentaps.domain.billing.lockbox.LockboxBatch;
import org.opentaps.domain.billing.lockbox.LockboxBatchItem;
import org.opentaps.domain.billing.lockbox.LockboxBatchItemDetail;
import org.opentaps.domain.billing.lockbox.LockboxRepositoryInterface;
import org.opentaps.domain.party.Party;
import org.opentaps.domain.party.PartyRepositoryInterface;
import org.opentaps.foundation.entity.EntityNotFoundException;
import org.opentaps.foundation.repository.RepositoryException;
import org.opentaps.foundation.repository.ofbiz.Repository;
/**
* Repository for Lockbox entities to handle interaction of domain with the entity engine (database) and the service engine.
*/
public class LockboxRepository extends Repository implements LockboxRepositoryInterface {
private static final String MODULE = LockboxRepository.class.getName();
private InvoiceRepositoryInterface invoiceRepository;
private PartyRepositoryInterface partyRepository;
/**
* Default constructor.
*/
public LockboxRepository() {
super();
}
/** {@inheritDoc} */
public LockboxBatch getBatchById(String lockboxBatchId) throws RepositoryException, EntityNotFoundException {
return findOneNotNull(LockboxBatch.class, map(LockboxBatch.Fields.lockboxBatchId, lockboxBatchId));
}
/** {@inheritDoc} */
public LockboxBatchItem getBatchItemById(String lockboxBatchId, String itemSeqId) throws RepositoryException, EntityNotFoundException {
return findOneNotNull(LockboxBatchItem.class, map(LockboxBatchItem.Fields.lockboxBatchId, lockboxBatchId, LockboxBatchItem.Fields.itemSeqId, itemSeqId));
}
/** {@inheritDoc} */
public LockboxBatchItemDetail getBatchItemDetailById(String lockboxBatchId, String itemSeqId, String detailSeqId) throws RepositoryException, EntityNotFoundException {
return findOneNotNull(LockboxBatchItemDetail.class, map(LockboxBatchItemDetail.Fields.lockboxBatchId, lockboxBatchId, LockboxBatchItemDetail.Fields.itemSeqId, itemSeqId, LockboxBatchItemDetail.Fields.detailSeqId, detailSeqId));
}
/** {@inheritDoc} */
public List<LockboxBatch> getPendingBatches() throws RepositoryException {
return findList(LockboxBatch.class, EntityCondition.makeCondition(LockboxBatch.Fields.outstandingAmount.getName(), EntityOperator.GREATER_THAN, 0));
}
/** {@inheritDoc} */
public Invoice getRelatedInvoice(LockboxBatchItemDetail detail) throws RepositoryException {
try {
return getInvoiceRepository().getInvoiceById(detail.getInvoiceNumber());
} catch (EntityNotFoundException e) {
return null;
}
}
/** {@inheritDoc} */
public Party getRelatedCustomer(LockboxBatchItemDetail detail) throws RepositoryException {
return findOne(Party.class, map(Party.Fields.partyId, detail.getCustomerId()));
}
/** {@inheritDoc} */
public boolean isHashExistent(String hash) throws RepositoryException {
return UtilValidate.isNotEmpty(findList(LockboxBatch.class, map(LockboxBatch.Fields.fileHashMark, hash)));
}
/** {@inheritDoc} */
public List<LockboxBatch> getBatchesByHash(String hash) throws RepositoryException {
return findList(LockboxBatch.class, map(LockboxBatch.Fields.fileHashMark, hash));
}
/** {@inheritDoc} */
public PaymentMethodAndEftAccount getPaymentMethod(String accountNumber, String routingNumber) throws RepositoryException {
EntityCondition conditions = EntityCondition.makeCondition(EntityOperator.AND,
EntityCondition.makeCondition(PaymentMethodAndEftAccount.Fields.routingNumber.name(), EntityOperator.EQUALS, routingNumber),
EntityUtil.getFilterByDateExpr());
List<PaymentMethodAndEftAccount> results = findList(PaymentMethodAndEftAccount.class, conditions);
if (results.size() > 1) {
Debug.logWarning("Found more than one active PaymentMethodAndEftAccount for given account number and routing number [" + routingNumber + "]", MODULE);
}
if (results.isEmpty()) {
Debug.logWarning("Did not find any PaymentMethodAndEftAccount", MODULE);
return null;
} else {
for (PaymentMethodAndEftAccount eft : results) {
// TODO: #921 Encrypted fields are not available in view entities
EftAccount eftAcc = eft.getEftAccount();
if (accountNumber.equals(eftAcc.getAccountNumber())) {
return eft;
}
}
Debug.logWarning("No matching EFT account for the given account number.", MODULE);
return null;
}
}
protected InvoiceRepositoryInterface getInvoiceRepository() throws RepositoryException {
if (invoiceRepository == null) {
invoiceRepository = DomainsDirectory.getDomainsDirectory(this).getBillingDomain().getInvoiceRepository();
}
return invoiceRepository;
}
protected PartyRepositoryInterface getPartyRepository() throws RepositoryException {
if (partyRepository == null) {
partyRepository = DomainsDirectory.getDomainsDirectory(this).getPartyDomain().getPartyRepository();
}
return partyRepository;
}
}
|
package com.github.paolorotolo.gitty_reporter_example;
import android.os.Bundle;
import com.github.paolorotolo.gitty_reporter.GittyReporter;
public class GittyReporterExample extends GittyReporter {
@Override
public void init(Bundle savedInstanceState) {
//noinspection HardCodedStringLiteral
setTargetRepository("Inversion-NL", "GittyReporter");
//noinspection HardCodedStringLiteral
setGuestOAuth2Token("a6b7c9af61e91fba5c8dd72987d0f919f54818bb");
}
} |
<gh_stars>1-10
export default /* glsl */ `varying float vPixelSize;
float getTriangleUpMask(vec2 uv) {
uv.y -= .25;
return max(-uv.y, abs(uv.x) * .866 + uv.y * .5 + .6);
}
`; |
import React from "react"
import Layout from "../components/layout"
export default function Testimonials() {
return (
<Layout>
<div class="col-lg-12">
<h2 class="about-heading">Testimonials - here's what our lovely clients had to say about their experience with us...</h2>
</div>
<div class="flex-container">
<div class="flex-item test">
<p class="testimonial">"Laura is fantastic. She provides excellent massages for myself and my husband in our home. Laura is warm, friendly, and makes you feel completely at ease. She is very knowledgeable and helps ease your problem areas. I can't recommend her enough." </p>
<p class="name">- <NAME>.</p>
</div>
<div class="flex-item test">
<p class="testimonial">"Laura really knows how to work with the body, getting deeply into every muscle. I feel so relaxed, restored and revitalised. Utter bliss."</p>
<p class="name">- <NAME>.</p>
</div>
<div class="flex-item test">
<p class="testimonial">"I started pre-natal massage with Laura in my second trimester. Laura tailored every session to my (ever changing) needs. I was so relaxed and reassured during every treatment. However what I loved most about Laura is her personable and professional demeanour. I highly recommend her."</p>
<p class="name">- <NAME>.</p>
</div>
<div class="flex-item test">
<p class="testimonial">"I had a one hour swedish massage on my back and shoulders from Laura after she was recommended by my sister-in-law. She was very friendly and professional. The massage was fantastic. I've had various massages in different spas and this was definitely among the best."</p>
<p class="name">- <NAME>.</p>
</div>
<div class="flex-item test">
<p class="testimonial">"I just had the most incredible massage from Laura. It was like she was drawn to every knot in my back and the relief was like nothing else."</p>
<p class="name">- <NAME>.</p>
</div>
<div class="flex-item test">
<p class="testimonial">"Laura provided some much needed care to our members at our annual conference. She provided a friendly and professional service and we look forward to working with her again in the future."</p>
<p class="name">- Royal Blind</p>
</div>
<div class="flex-item test">
<p class="testimonial">"Fantastic pregnancy massage and reflexology. Laura eased all my aches and pains and I slept better than I have in months." </p>
<p class="name">- <NAME>.</p>
</div>
<div class="flex-item test">
<p class="testimonial">"Just had an amazing massage from Laura! She was very knowledable and knew exactly where all my knots were. She created an amazing ambiance right in my home. The massage was so relaxing and I look forward to her next visit!" </p>
<p class="name">- <NAME>.</p>
</div>
<div class="flex-item test">
<p class="testimonial">"What an experience! After having a sports back injury few months ago and explained to Laura what happend she found and eased every nook and cranny! The differance was amazing! Every knot and bit of tension eased in one session!" </p>
<p class="name">- <NAME>.</p>
</div>
<div class="flex-item test">
<p class="testimonial">"Laura has provided treatments to our elderly ladies several times now and she is just wonderful. She always takes the time to find the most beneficial treatment for them - all with a smile.
All our members report an improvement in their aches and pains after seeing her. I would definitely recommend her services." </p>
<p class="name">- Maryhill Parish Church</p>
</div>
</div>
</Layout>
)
} |
def prime_list(start, end):
# List to store all prime numbers
primes = []
# Iterate over all numbers between start to end
for num in range(start, end+1):
#Check whether the number is prime or not
if check_prime(num):
primes.append(num)
return primes
def check_prime(num):
# Check if num is divisible by any number from 2 to num
for i in range(2, num):
if (num % i == 0):
return False
# Return True if the number is prime
return True |
<filename>amp-admin/src/api/image.js
import request from '@/utils/request'
export function fetchProductSliderImages(query) {
return request({
url: '/image/product/list',
method: 'get',
params: query
})
}
export function uploadImage(query) {
return request({
url: '/image/upload',
method: 'post',
params: query
})
}
const uploadImagePath = process.env.BASE_API + 'qiniu/upload'
export { uploadImagePath }
|
#!/usr/bin/env bash
set -e
set -o pipefail
if [[ ! -d system/src ]]; then
echo "compile-system.bash: no system/src directory" >&2
exit 1
fi
function verbosely {
echo "$@"
"$@"
}
mkdir -p system/out
rm -f system/out/*
for src in system/src/*.c; do
out="${src/src/out}"
out="${out/.c}"
verbosely clang -Wall -Wextra -Werror -std=c11 "${src}" -o "${out}"
if [[ "${out}" == *-privileged && -n "${RIJU_PRIVILEGED}" ]]; then
sudo chown root:docker "${out}"
sudo chmod a=,g=rx,u=rwxs "${out}"
fi
done
|
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
firstName : String,
secondName : String,
email : {
type: String,
unique: true,
required: true
},
profilePhoto : {
type: String
},
password: {
type: String,
required: true
},
posts : {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
});
UserSchema.pre('save', function(next) {
const user = this
bcrypt.hash(user.password, 12, function(error, encrypt) {
user.password = encrypt
next()
})
})
module.exports = mongoose.model('User', UserSchema)
|
/*
* Tencent is pleased to support the open source community by making 蓝鲸 available.,
* Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the ",License",); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an ",AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package mainline
import (
"context"
"fmt"
"net/http"
"configcenter/src/common/blog"
"configcenter/src/common/metadata"
"configcenter/src/common/util"
)
// SearchMainlineModelTopo get topo tree of model on mainline
func (m *topoManager) SearchMainlineModelTopo(ctx context.Context, header http.Header, withDetail bool) (*metadata.TopoModelNode, error) {
rid := util.ExtractRequestIDFromContext(ctx)
obj, err := NewModelMainline(m.DbProxy)
if err != nil {
blog.Errorf("new model mainline failed, err: %+v, rid: %s", err, rid)
return nil, fmt.Errorf("new model mainline failed, err: %+v", err)
}
return obj.GetRoot(ctx, header, withDetail)
}
|
/*
* =============================================================================
*
* Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
package org.thymeleaf.templateparser.reader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public final class ParserLevelCommentTextReaderTest {
@Test
public void test01() throws Exception {
final String[] allMessages = computeAllParserLevelMessages();
for (int i = 0; i < allMessages.length; i++) {
testMessage(allMessages[i], computeParserLevelEquivalent(allMessages[i]));
}
}
@Test
public void test02() throws Exception {
testMessage("/* hello */", "/* hello */");
testMessage("/* /*[- hello -]]*/ -]*/", "/* ");
testMessage("/* /*[- hello -]]*/ -]*/ */", "/* */");
testMessage("/* /*[[- hello -]]*/ -]*/ */", "/* /*[[- hello -]]*/ -]*/ */");
testMessage("/* /*[[- hello -]]*/ -]*/ /*[- -]*/*/", "/* /*[[- hello -]]*/ -]*/ */");
testMessage("/* /*[[--- hello ---]]*/ -]*/ */", "/* /*[[--- hello ---]]*/ -]*/ */");
testMessage("/* /*[[--- hello ---]]*/ -]*/ /*[- -]*/*/", "/* /*[[--- hello ---]]*/ -]*/ */");
testMessage("hello", "hello");
testMessage("/*[- hello -]***/ -]*/", "");
testMessage("/*[- hello -]***/ -]*/", "");
testMessage("/***[- hello -]***/ -]*/", "/***[- hello -]***/ -]*/");
testMessage("/***[- hello -]***/ -]*/ */", "/***[- hello -]***/ -]*/ */");
testMessage("/***[- hello -]***/ -]*/ /*[- -]*/*/", "/***[- hello -]***/ -]*/ */");
testMessage("/***[- hello -]***/ -]*/ /*[- -]*/", "/***[- hello -]***/ -]*/ ");
}
private void testMessage(final String message, final String expected) throws IOException {
for (int j = 1; j <= (message.length() + 10); j++) {
for (int k = 1; k <= j; k++) {
for (int l = 0; l < k; l++) {
final Reader stringReader =
new ParserLevelCommentTextReader(new StringReader(message));
final char[] buffer = new char[j];
final StringBuilder strBuilder = new StringBuilder();
int read = 0;
while (read >= 0) {
read = stringReader.read(buffer, l, (k - l));
if (read >= 0) {
strBuilder.append(buffer, l, read);
}
}
final String result = strBuilder.toString();
Assert.assertEquals("Checking: '" + message + "' (" + j + "," + k + "," + l + ")", expected, result);
}
}
}
}
private static String[] computeAllParserLevelMessages() {
final List<String> allMessages = new ArrayList<String>();
final String prefix = "/*[-";
final String suffix = "-]*/";
final String message = "0123456789";
for (int i = 0; i <= message.length(); i++) {
final StringBuilder msb1 = new StringBuilder(message);
msb1.insert(i, suffix);
for (int j = 0; j <= i; j++) {
final StringBuilder msb2 = new StringBuilder(msb1);
msb2.insert(j, prefix);
for (int k = 0; k <= j; k++) {
final StringBuilder msb3 = new StringBuilder(msb2);
msb3.insert(k, suffix);
allMessages.add(msb3.toString());
for (int l = 0; l <= k; l++) {
final StringBuilder msb4 = new StringBuilder(msb3);
msb4.insert(l, prefix);
allMessages.add(msb4.toString());
}
}
}
}
return allMessages.toArray(new String[allMessages.size()]);
}
private static String computeParserLevelEquivalent(final String message) {
final StringBuilder stringBuilder = new StringBuilder();
final int messageLen = message.length();
boolean inComment = false;
for (int i = 0; i < messageLen; i++) {
if (!inComment && message.charAt(i) == '/' && (i + 1) < messageLen && message.charAt(i + 1) == '*') {
inComment = true;
continue;
} else if (inComment && message.charAt(i) == '/' && i > 0 && message.charAt(i - 1) == '*') {
inComment = false;
continue;
}
if (!inComment) {
stringBuilder.append(message.charAt(i));
}
}
return stringBuilder.toString();
}
}
|
/**
*/
package edu.kit.ipd.sdq.kamp4hmi.model.HMIModificationmarks.presentation;
import edu.kit.ipd.sdq.kamp.model.modificationmarks.provider.ModificationmarksEditPlugin;
import edu.kit.ipd.sdq.kamp4hmi.model.Kamp4hmiModel.provider.Kamp4hmiModelEditPlugin;
import edu.kit.ipd.sdq.kamp4iec.model.IECRepository.provider.IECRepositoryEditPlugin;
import org.eclipse.emf.common.EMFPlugin;
import org.eclipse.emf.common.ui.EclipseUIPlugin;
import org.eclipse.emf.common.util.ResourceLocator;
/**
* This is the central singleton for the HMIModificationmarks editor plugin.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public final class HMIModificationmarksEditorPlugin extends EMFPlugin {
/**
* Keep track of the singleton.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final HMIModificationmarksEditorPlugin INSTANCE = new HMIModificationmarksEditorPlugin();
/**
* Keep track of the singleton.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static Implementation plugin;
/**
* Create the instance.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public HMIModificationmarksEditorPlugin() {
super
(new ResourceLocator [] {
IECRepositoryEditPlugin.INSTANCE,
Kamp4hmiModelEditPlugin.INSTANCE,
ModificationmarksEditPlugin.INSTANCE,
});
}
/**
* Returns the singleton instance of the Eclipse plugin.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the singleton instance.
* @generated
*/
@Override
public ResourceLocator getPluginResourceLocator() {
return plugin;
}
/**
* Returns the singleton instance of the Eclipse plugin.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the singleton instance.
* @generated
*/
public static Implementation getPlugin() {
return plugin;
}
/**
* The actual implementation of the Eclipse <b>Plugin</b>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class Implementation extends EclipseUIPlugin {
/**
* Creates an instance.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Implementation() {
super();
// Remember the static instance.
//
plugin = this;
}
}
}
|
package ofp
const OFPP_V13 = 4
const OFPP_V15 = 6
func ExpectedType(msgType uint8) uint8 {
switch msgType {
case 2, 5, 7, 18, 20, 22, 24, 26:
return msgType + 1
default:
return msgType
}
}
func IsAsymmetric(msgType uint8) bool {
switch msgType {
case 1, 10, 11, 12:
return true
default:
return false
}
}
const (
// Symetric controller/switch messages
OFPT_HELLO = 0
OFPT_ERROR = 1
OFPT_ECHO_REQUEST = 2
OFPT_ECHO_REPLY = 3
OFPT_EXPERIMENTER = 4
// Symetric controller/switch messages
OFPT_FEATURES_REQUEST = 5
OFPT_FEATURES_REPLY = 6
OFPT_GET_CONFIG_REQUEST = 7
OFPT_GET_CONFIG_REPLY = 8
OFPT_SET_CONFIG = 9
// Asymmetric messages
OFPT_PACKET_IN = 10
OFPT_FLOW_REMOVED = 11
OFPT_PORT_STATUS = 12
// Symetric controller/switch messages
OFPT_PACKET_OUT = 13
OFPT_FLOW_MOD = 14
OFPT_GROUP_MOD = 15
OFPT_PORT_MOD = 16
OFPT_TABLE_MOD = 17
OFPT_MULTIPART_REQUEST = 18
OFPT_MULTIPART_REPLY = 19
OFPT_BARRIER_REQUEST = 20
OFPT_BARRIER_REPLY = 21
OFPT_QUEUE_GET_CONFIG_REQUEST = 22
OFPT_QUEUE_GET_CONFIG_REPLY = 23
OFPT_ROLE_REQUEST = 24
OFPT_ROLE_REPLY = 25
OFPT_GET_ASYNC_REQUEST = 26
OFPT_GET_ASYNC_REPLY = 27
OFPT_SET_ASYNC = 28
OFPT_METER_MOD = 29
)
// Match oxm type
const (
OFPMT_STANDARD = iota
OFPMT_OXM
)
// Match oxm classes
const (
OFPXMC_NXM_0 = 0x0000
OFPXMC_NXM_1 = 0x0001
OFPXMC_OPENFLOW_BASIC = 0x8000
OFPXMC_EXPERIMENTER = 0xffff
)
// oxm fields
const (
OFPXMT_OFB_IN_PORT = iota
OFPXMT_OFB_IN_PHY_PORT
OFPXMT_OFB_METADATA
OFPXMT_OFB_ETH_DST
OFPXMT_OFB_ETH_SRC
OFPXMT_OFB_ETH_TYPE
OFPXMT_OFB_VLAN_VID
OFPXMT_OFB_VLAN_PCP
OFPXMT_OFB_IP_DSCP
OFPXMT_OFB_IP_ECN
OFPXMT_OFB_IP_PROTO
OFPXMT_OFB_IPV4_SRC
OFPXMT_OFB_IPV4_DST
OFPXMT_OFB_TCP_SRC
OFPXMT_OFB_TCP_DST
OFPXMT_OFB_UDP_SRC
OFPXMT_OFB_UDP_DST
OFPXMT_OFB_SCTP_SRC
OFPXMT_OFB_SCTP_DST
OFPXMT_OFB_ICMPV4_TYPE
OFPXMT_OFB_ICMPV4_CODE
OFPXMT_OFB_ARP_OP
OFPXMT_OFB_ARP_SPA
OFPXMT_OFB_ARP_TPA
OFPXMT_OFB_ARP_SHA
OFPXMT_OFB_ARP_THA
OFPXMT_OFB_IPV6_SRC
OFPXMT_OFB_IPV6_DST
OFPXMT_OFB_IPV6_FLABEL
OFPXMT_OFB_ICMPV6_TYPE
OFPXMT_OFB_ICMPV6_CODE
OFPXMT_OFB_IPV6_ND_TARGET
OFPXMT_OFB_IPV6_ND_SLL
OFPXMT_OFB_IPV6_ND_TLL
OFPXMT_OFB_MPLS_LABEL
OFPXMT_OFB_MPLS_TC
OFPXMT_OFB_MPLS_BOS
OFPXMT_OFB_PBB_ISID
OFPXMT_OFB_TUNNEL_ID
OFPXMT_OFB_IPV6_EXTHDR
OFPXMT_OFB_PBB_UCA
OFPXMT_OFB_TCP_FLAGS
OFPXMT_OFB_ACTSET_OUTPUT
OFPXMT_OFB_PACKET_TYPE
)
const (
OFPVID_PRESENT = 0x1000
OFPVID_NONE = 0x0000
)
const (
OFP_VLAN_NONE = OFPVID_NONE
)
|
require "snow_flake/version"
# /**
# * Twitter_Snowflake<br>
# * SnowFlake的结构如下(每部分用-分开):<br>
# * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
# * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br>
# * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)
# * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
# * 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br>
# * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br>
# * 加起来刚好64位,为一个Long型。<br>
# * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。
# */
module SnowFlake
# example
# SnowFlake::ID.new(1,1).next_id
class ID
attr_accessor :twepoch, :worker_id_bits, :datacenter_id_bits, :max_worker_id, :max_datacenter_id, :sequence_bits,
:worker_id_shift, :datacenter_id_shift, :timestamp_left_shift, :sequence_mask, :worker_id,
:datacenter_id, :sequence, :last_timestamp
# @param worker_id 工作ID (0~31)
# @param datacenter_id 数据中心ID (0~31)
def initialize(worker_id, datacenter_id)
self.twepoch = 1420041600000 # start time (2015-01-01)
self.worker_id_bits = 5 # worker id bits
self.datacenter_id_bits = 5 # datacenter id bits
# Supported maximum worker id, resulting in 31
self.max_worker_id = -1 ^ (-1 << worker_id_bits)
# Supported maximum datacenter id, resulting in 31
self.max_datacenter_id = -1 ^ (-1 << datacenter_id_bits)
self.sequence_bits = 12 # The number of sequences in ID
# The machine ID moves to the left 12 bits.
self.worker_id_shift = sequence_bits
# The data identification ID moves to the left 17 bits (12+5)
self.datacenter_id_shift = sequence_bits + worker_id_bits
# The time is shifted to the left by 22 bits(5+5+12)
self.timestamp_left_shift = sequence_bits + worker_id_bits + datacenter_id_bits
# The mask of generating sequence is 4095 (0b111111111111=0xfff=4095)
self.sequence_mask = -1 ^ (-1 << sequence_bits)
self.sequence = 0 # Millisecond sequence(0~4095)
self.last_timestamp = -1 # Last timestamp of ID generation
if worker_id > max_worker_id || worker_id < 0
raise "worker Id can't be greater than #{max_worker_id} or less than 0"
end
if datacenter_id > max_datacenter_id || datacenter_id < 0
raise "datacenter Id can't be greater than #{max_datacenter_id} or less than 0"
end
self.worker_id = worker_id # worker ID(0~31)
self.datacenter_id = datacenter_id # datacenter ID(0~31)
end
def next_id
timestamp = time_gen
if timestamp < last_timestamp
raise "Clock moved backwards. Refusing to generate id for #{last_timestamp - timestamp} milliseconds"
end
if last_timestamp == timestamp
self.sequence = (sequence + 1) & sequence_mask
timestamp = till_next_millis(last_timestamp) if sequence.zero?
else
self.sequence = 0
end
self.last_timestamp = timestamp
((timestamp - twepoch) << timestamp_left_shift) | (datacenter_id << datacenter_id_shift) | (worker_id << worker_id_shift) | sequence
end
def till_next_millis(last_timestamp)
timestamp = time_gen
timestamp = time_gen while timestamp <= last_timestamp
timestamp
end
def time_gen
(Time.now.to_f * 1000).floor
end
end
end
|
#!/bin/bash
source subr.sh
CONFIG_DIR="$(setup)"
echo "config dir: $CONFIG_DIR"
test -f "$CONFIG_DIR/syndicate.conf" || test_fail "Missing syndicate.conf"
test -d "$CONFIG_DIR/users" || test_fail "Missing users/"
test -d "$CONFIG_DIR/volumes" || test_fail "Missing volumes/"
test -d "$CONFIG_DIR/gateways" || test_fail "Missing gateways/"
test -d "$CONFIG_DIR/syndicate" || test_fail "Missing syndicate/"
test -f "$CONFIG_DIR/users/$SYNDICATE_ADMIN_EMAIL.cert" || test_fail "Missing admin cert"
test -f "$CONFIG_DIR/users/$SYNDICATE_ADMIN_EMAIL.pkey" || test_fail "Missing admin private key"
test -f "$CONFIG_DIR/syndicate/localhost:8080.pub" || test_fail "Missing Syndicate public key"
test_success
exit 0
|
<filename>leetcode/997 Finding The Town Judge/main.go<gh_stars>0
package main
func findJudge(N int, trust [][]int) int {
indegree := make([]int, N)
outdegree := make([]int, N)
for _, v := range trust {
a, b := v[0] - 1, v[1] - 1
outdegree[a]++
indegree[b]++
}
for i := range indegree {
in := indegree[i]
out := outdegree[i]
if in == N - 1 && out == 0 {
return i + 1
}
}
return -1
}
func main() {
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_DRIVE_DRIVE_FEED_LOADER_H_
#define CHROME_BROWSER_CHROMEOS_DRIVE_DRIVE_FEED_LOADER_H_
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/memory/scoped_vector.h"
#include "base/observer_list.h"
#include "chrome/browser/chromeos/drive/drive_resource_metadata.h"
#include "chrome/browser/google_apis/gdata_errorcode.h"
#include "googleurl/src/gurl.h"
class FilePath;
namespace base {
class Value;
}
namespace google_apis {
class DocumentFeed;
class DriveServiceInterface;
}
namespace drive {
class DriveCache;
class DriveFeedLoaderObserver;
class DriveWebAppsRegistryInterface;
struct GetDocumentsUiState;
struct LoadFeedParams;
// Callback run as a response to LoadFromServer.
typedef base::Callback<void(scoped_ptr<LoadFeedParams> params,
DriveFileError error)>
LoadDocumentFeedCallback;
// Set of parameters sent to LoadFromServer and LoadDocumentFeedCallback.
// Value of |start_changestamp| determines the type of feed to load - 0 means
// root feed, every other value would trigger delta feed.
// In the case of loading the root feed we use |root_feed_changestamp| as its
// initial changestamp value since it does not come with that info.
//
// Loaded feed may be partial due to size limit on a single feed. In that case,
// the loaded feed will have next feed url set. Iff |load_subsequent_feeds|
// parameter is set, feed loader will load all subsequent feeds.
//
// When all feeds are loaded, |feed_load_callback| is invoked with the retrieved
// feeds. Then |load_finished_callback| is invoked with the error code.
//
// If invoked as a part of content search, query will be set in |search_query|.
// If |feed_to_load| is set, this is feed url that will be used to load feed.
//
// |feed_load_callback| must not be null.
// |load_finished_callback| may be null.
struct LoadFeedParams {
explicit LoadFeedParams(const LoadDocumentFeedCallback& feed_load_callback);
~LoadFeedParams();
// Changestamps are positive numbers in increasing order. The difference
// between two changestamps is proportional equal to number of items in
// delta feed between them - bigger the difference, more likely bigger
// number of items in delta feeds.
int64 start_changestamp;
int64 root_feed_changestamp;
std::string search_query;
std::string directory_resource_id;
GURL feed_to_load;
bool load_subsequent_feeds;
const LoadDocumentFeedCallback feed_load_callback;
FileOperationCallback load_finished_callback;
ScopedVector<google_apis::DocumentFeed> feed_list;
scoped_ptr<GetDocumentsUiState> ui_state;
// On initial feed load for Drive API, remember root ID for
// DriveResourceData initialization later in UpdateFromFeed().
std::string root_resource_id;
};
// Defines set of parameters sent to callback OnProtoLoaded().
struct LoadRootFeedParams {
explicit LoadRootFeedParams(const FileOperationCallback& callback);
~LoadRootFeedParams();
std::string proto;
DriveFileError load_error;
base::Time last_modified;
// Time when filesystem began to be loaded from disk.
base::Time load_start_time;
const FileOperationCallback callback;
};
// DriveFeedLoader is used to load feeds from WAPI (codename for
// Documents List API) and load the cached proto file.
class DriveFeedLoader {
public:
DriveFeedLoader(
DriveResourceMetadata* resource_metadata,
google_apis::DriveServiceInterface* drive_service,
DriveWebAppsRegistryInterface* webapps_registry,
DriveCache* cache,
scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_);
~DriveFeedLoader();
// Adds and removes the observer.
void AddObserver(DriveFeedLoaderObserver* observer);
void RemoveObserver(DriveFeedLoaderObserver* observer);
// Starts root feed load from the cache, and runs |callback| to tell the
// result to the caller.
// |callback| must not be null.
void LoadFromCache(const FileOperationCallback& callback);
// Starts retrieving feed for a directory specified by |directory_resource_id|
// from the server. Upon completion, |feed_load_callback| is invoked.
// |feed_load_callback| must not be null.
void LoadDirectoryFromServer(
const std::string& directory_resource_id,
const LoadDocumentFeedCallback& feed_load_callback);
// Starts retrieving search results for |search_query| from the server.
// If |next_feed| is set, this is the feed url that will be fetched.
// If |next_feed| is an empty string, the default URL is used.
// Upon completion, |feed_load_callback| is invoked.
// |feed_load_callback| must not be null.
void SearchFromServer(const std::string& search_query,
const GURL& next_feed,
const LoadDocumentFeedCallback& feed_load_callback);
// Retrieves account metadata and determines from the last change timestamp
// if the feed content loading from the server needs to be initiated.
// |callback| must not be null.
void ReloadFromServerIfNeeded(const FileOperationCallback& callback);
// Updates whole directory structure feeds collected in |feed_list|.
// Record file statistics as UMA histograms.
//
// See comments at DriveFeedProcessor::ApplyFeeds() for
// |start_changestamp| and |root_feed_changestamp|.
// |root_resource_id| is used for Drive API.
void UpdateFromFeed(
const ScopedVector<google_apis::DocumentFeed>& feed_list,
int64 start_changestamp,
int64 root_feed_changestamp,
const std::string& root_resource_id);
// Indicates whether there is a feed refreshing server request is in flight.
bool refreshing() const { return refreshing_; }
private:
// Starts root feed load from the server, with details specified in |params|.
void LoadFromServer(scoped_ptr<LoadFeedParams> params);
// Callback for handling root directory refresh from the cache.
void OnProtoLoaded(LoadRootFeedParams* params);
// Continues handling root directory refresh after the resource metadata
// is fully loaded.
void ContinueWithInitializedResourceMetadata(LoadRootFeedParams* params,
DriveFileError error);
// Helper callback for handling results of metadata retrieval initiated from
// ReloadFromServerIfNeeded(). This method makes a decision about fetching
// the content of the root feed during the root directory refresh process.
void OnGetAccountMetadata(
const FileOperationCallback& callback,
google_apis::GDataErrorCode status,
scoped_ptr<base::Value> feed_data);
// Helper callback for handling results of account data retrieval initiated
// from ReloadFromServerIfNeeded() for Drive V2 API.
// This method makes a decision about fetching the content of the root feed
// during the root directory refresh process.
void OnGetAboutResource(
const FileOperationCallback& callback,
google_apis::GDataErrorCode status,
scoped_ptr<base::Value> feed_data);
// Callback for handling response from |DriveAPIService::GetApplicationInfo|.
// If the application list is successfully parsed, passes the list to
// Drive webapps registry.
void OnGetApplicationList(google_apis::GDataErrorCode status,
scoped_ptr<base::Value> json);
// Callback for handling feed content fetching while searching for file info.
// This callback is invoked after async feed fetch operation that was
// invoked by StartDirectoryRefresh() completes. This callback will update
// the content of the refreshed directory object and continue initially
// started FindEntryByPath() request.
void OnFeedFromServerLoaded(scoped_ptr<LoadFeedParams> params,
DriveFileError error);
// Callback for handling response from |GDataWapiService::GetDocuments|.
// Invokes |callback| when done.
// |callback| must not be null.
void OnGetDocuments(
scoped_ptr<LoadFeedParams> params,
base::TimeTicks start_time,
google_apis::GDataErrorCode status,
scoped_ptr<base::Value> data);
// Callback for handling results of feed parse.
void OnParseFeed(scoped_ptr<LoadFeedParams> params,
base::TimeTicks start_time,
scoped_ptr<google_apis::DocumentFeed>* current_feed);
// Callback for handling response from |DriveAPIService::GetDocuments|.
// Invokes |callback| when done.
// |callback| must not be null.
void OnGetChangelist(scoped_ptr<LoadFeedParams> params,
base::TimeTicks start_time,
google_apis::GDataErrorCode status,
scoped_ptr<base::Value> data);
// Save filesystem to disk.
void SaveFileSystem();
// Callback for handling UI updates caused by document fetching.
void OnNotifyDocumentFeedFetched(
base::WeakPtr<GetDocumentsUiState> ui_state);
DriveResourceMetadata* resource_metadata_; // Not owned.
google_apis::DriveServiceInterface* drive_service_; // Not owned.
DriveWebAppsRegistryInterface* webapps_registry_; // Not owned.
DriveCache* cache_; // Not owned.
scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_;
ObserverList<DriveFeedLoaderObserver> observers_;
// Indicates whether there is a feed refreshing server request is in flight.
bool refreshing_;
// Note: This should remain the last member so it'll be destroyed and
// invalidate its weak pointers before any other members are destroyed.
base::WeakPtrFactory<DriveFeedLoader> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(DriveFeedLoader);
};
} // namespace drive
#endif // CHROME_BROWSER_CHROMEOS_DRIVE_DRIVE_FEED_LOADER_H_
|
<filename>demo/server.js
const express = require('express');
const app = express();
const cors = require('cors')
const dotenv = require('dotenv');
dotenv.config()
const Scrapers = require('./Scrapers');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors())
// api routes
app.get('/', (req, res) => {
res.send('welcome!')
})
app.post('/api/v1/scrape', (req, res) => {
let productUrl = req.body.url
let scraper = new Scrapers()
scraper.scrapeAmazonStore(productUrl)
.then(data => {
res.status(200).json({
status: true,
message:data
})
})
.catch(err => {
res.status(400).json({
status: false,
message: err
})
})
})
// catch 404 and forward to error handler
app.use((req, res, next) => {
next(res.status(400).json({
status: false,
data: 'Bad request'
}));
});
// error handler
app.use((err, req, res) => {
// render the error page
res.status(err.status || 500).json({
status: false,
data: 'internal server error'
});
});
app.listen( process.env.PORT, () =>
console.log(` listening at http://localhost:${process.env.PORT}`)
) |
<gh_stars>0
package operatorconfig
import (
"context"
"github.com/go-logr/logr"
kube "github.com/infinispan/infinispan-operator/pkg/kubernetes"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
const (
ControllerName = "operator-config-controller"
configMapName = "infinispan-operator-config"
)
const (
grafanaDashboardNamespaceKey = "grafana.dashboard.namespace"
grafanaDashboardNameKey = "grafana.dashboard.name"
grafanaDashboardMonitoringKey = "grafana.dashboard.monitoring.key"
)
var ctx = context.Background()
// DefaultConfig default configuration for operator config controller
var defaultOperatorConfig = map[string]string{
grafanaDashboardMonitoringKey: "middleware",
grafanaDashboardNameKey: "infinispan",
}
// ReconcileInfinispan reconciles a Infinispan object
type ReconcileOperatorConfig struct {
client client.Client
scheme *runtime.Scheme
Log logr.Logger
Kube *kube.Kubernetes
}
func Add(mgr manager.Manager) error {
return addOperatorConfig(mgr)
}
// addOperatorConfig installs a reconciler for a specific object.
// Only events coming from operatorNs/infinispan-operator-config will be processed
func addOperatorConfig(mgr manager.Manager) error {
r := &ReconcileOperatorConfig{client: mgr.GetClient(), scheme: mgr.GetScheme(), Log: logf.Log.WithName("operator-config-controller"), Kube: kube.NewKubernetesFromController(mgr)}
// Create a new controller
c, err := controller.New(ControllerName, mgr, controller.Options{Reconciler: r})
if err != nil {
return err
}
operatorNS, err := kube.GetOperatorNamespace()
if err != nil {
return err
}
operatorConfigPredicate := predicate.Funcs{
DeleteFunc: func(e event.DeleteEvent) bool {
return e.Meta.GetName() == configMapName && e.Meta.GetNamespace() == operatorNS
},
CreateFunc: func(e event.CreateEvent) bool {
return e.Meta.GetName() == configMapName && e.Meta.GetNamespace() == operatorNS
},
UpdateFunc: func(e event.UpdateEvent) bool {
return e.MetaNew.GetName() == configMapName && e.MetaNew.GetNamespace() == operatorNS
},
GenericFunc: func(e event.GenericEvent) bool {
return e.Meta.GetName() == configMapName && e.Meta.GetNamespace() == operatorNS
},
}
// Watch for changes to global operator config
err = c.Watch(&source.Kind{Type: &corev1.ConfigMap{}}, &handler.EnqueueRequestForObject{}, operatorConfigPredicate)
if err != nil {
return err
}
return nil
}
var _ reconcile.Reconciler = &ReconcileOperatorConfig{}
var currentConfig map[string]string = make(map[string]string)
// Reconcile reads the operator configuration in the `infinispan-operator-config` ConfigMap and
// applies the configuration to the cluster.
func (r *ReconcileOperatorConfig) Reconcile(request reconcile.Request) (reconcile.Result, error) {
operatorNs, err := kube.GetOperatorNamespace()
if err != nil {
r.Log.Error(err, "Error getting operator runtime namespace")
return reconcile.Result{Requeue: true}, nil
}
configMap := &corev1.ConfigMap{}
err = r.client.Get(ctx, types.NamespacedName{Namespace: operatorNs, Name: configMapName}, configMap)
if err != nil && !errors.IsNotFound(err) {
r.Log.Error(err, "Error getting operator configuration resource")
return reconcile.Result{Requeue: true}, nil
}
config := make(map[string]string)
// Copy defaults
for k, v := range defaultOperatorConfig {
config[k] = v
}
// Merge config value with defaults
for k, v := range configMap.Data {
config[k] = v
}
res, err := r.reconcileGrafana(config, currentConfig, operatorNs)
return *res, err
}
|
<gh_stars>10-100
/*
* Copyright (c) 2004-2021, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.program.programindicatorengine.internal.variable;
import com.google.common.collect.ImmutableMap;
import org.hisp.dhis.android.core.parser.internal.expression.CommonExpressionVisitor;
import org.hisp.dhis.android.core.parser.internal.expression.ExpressionItem;
import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramExpressionItem;
import org.hisp.dhis.antlr.ParserExceptionWithoutContext;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.ExprContext;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.V_COMPLETED_DATE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.V_CREATION_DATE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.V_CURRENT_DATE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.V_DUE_DATE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.V_ENROLLMENT_COUNT;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.V_ENROLLMENT_DATE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.V_ENROLLMENT_STATUS;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.V_EVENT_COUNT;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.V_EVENT_DATE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.V_INCIDENT_DATE;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.V_TEI_COUNT;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.V_VALUE_COUNT;
import static org.hisp.dhis.parser.expression.antlr.ExpressionParser.V_ZERO_POS_VALUE_COUNT;
@SuppressWarnings({"PMD.TooManyStaticImports"})
public class ProgramVariableItem extends ProgramExpressionItem {
private final static ImmutableMap<Integer, ExpressionItem>
PROGRAM_VARIABLES = ImmutableMap.<Integer, ExpressionItem>builder()
.put(V_ENROLLMENT_DATE, new VEnrollmentDate())
.put(V_INCIDENT_DATE, new VIncidentDate())
.put(V_EVENT_DATE, new VEventDate())
.put(V_DUE_DATE, new VDueDate())
.put(V_CURRENT_DATE, new VCurrentDate())
.put(V_CREATION_DATE, new VCreationDate())
.put(V_COMPLETED_DATE, new VCompletedDate())
.put(V_TEI_COUNT, new VTeiCount())
.put(V_ENROLLMENT_STATUS, new VEnrollmentStatus())
.put(V_ENROLLMENT_COUNT, new VEnrollmentCount())
.put(V_EVENT_COUNT, new VEventCount())
.put(V_VALUE_COUNT, new VValueCount())
.put(V_ZERO_POS_VALUE_COUNT, new VZeroPosValueCount())
.build();
@Override
public Object evaluate(ExprContext ctx, CommonExpressionVisitor visitor) {
ExpressionItem programVariable = getProgramVariable(ctx);
return programVariable.evaluate(ctx, visitor);
}
@Override
public Object count(ExprContext ctx, CommonExpressionVisitor visitor) {
ExpressionItem programVariable = getProgramVariable(ctx);
return programVariable.count(ctx, visitor);
}
// -------------------------------------------------------------------------
// Supportive methods
// -------------------------------------------------------------------------
private ExpressionItem getProgramVariable(ExprContext ctx) {
ExpressionItem programVariable = PROGRAM_VARIABLES.get(ctx.programVariable().var.getType());
if (programVariable == null) {
throw new ParserExceptionWithoutContext("Can't find program variable " +
ctx.programVariable().var.getText());
}
return programVariable;
}
}
|
#!/usr/bin/env bash
# Developer: Maik Ellerbrock <opensource@frapsoft.com>
#
# GitHub: https://github.com/ellerbrock
# Twitter: https://twitter.com/frapsoft
# Docker: https://hub.docker.com/frapsoft
[[ ! ${CONFIG_LOADED} ]] && echo "ERROR: PLEASE DON'T RUN DIRETLY (CONFIGURATION REQUIRED)" && exit 1
#
# Examples
#
print_logo
press_a_key
status_message_examples
press_a_key
error_message_examples
press_a_key
gui_examples
press_a_key
color_example
echo "... this was the color example :)"
press_a_key
echo "Thats it for now."
echo "Check on GitHub for new releases!"
echo "https://bash-framework.com"
press_a_key
|
#
# 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.
# multi-registry
array+=("multi-registry/go-server")
# async
array=("async/go-server")
# attachment
array+=("attachment/go-server")
# config-api
array+=("config-api/go-server")
# config center
array+=("configcenter/apollo/go-server")
array+=("configcenter/nacos/go-server")
array+=("configcenter/zookeeper/go-server")
# context
array+=("context/go-server")
# direct
array+=("direct/go-server")
# filter
array+=("filter/custom/go-server")
array+=("filter/tpslimit/go-server")
array+=("filter/sentinel/go-server")
# game
#array+=("game/go-server-game")
#array+=("game/go-server-gate")
# general
array+=("general/dubbo/go-server")
array+=("general/grpc/go-server")
#array+=("general/jsonrpc/go-server")
array+=("general/rest/go-server")
# generic
array+=("generic/go-server")
# group
array+=("group/go-server-group-a")
array+=("group/go-server-group-b")
# hello world
array+=("helloworld/go-server")
# metric
array+=("metric/go-server")
# registry
#array+=("registry/etcd/go-server")
#array+=("registry/nacos/go-server")
#array+=("registry/servicediscovery/consul/go-server")
#array+=("registry/servicediscovery/etcd/go-server")
#array+=("registry/servicediscovery/file/go-server")
#array+=("registry/servicediscovery/nacos/go-server")
array+=("registry/servicediscovery/zookeeper/go-server")
# router
#array+=("router/condition/go-server")
#array+=("router/tag/go-server")
# tls
#array+=("tls/go-server")
# version
array+=("version/go-server-v1")
array+=("version/go-server-v2")
for((i=0;i<${#array[*]};i++))
do
./integrate_test.sh ${array[i]}
result=$?
if [ $result -gt 0 ]; then
exit $result
fi
done
# chain
# multi-zone |
package weixin.iplimit.entity;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
/**
* Created by aa on 2016/3/22.
*/
@Entity
@Table(name = "weixin_ip", schema = "")
@SuppressWarnings("serial")
public class IPLimitEntity implements java.io.Serializable {
private String id; //主键id
private String ip; //ip地址
private String acctid; //商户id
private Date createDate; //创建时间
private Date operateDate; //修改时间
@Id
@GeneratedValue(generator = "paymentableGenerator")
@GenericGenerator(name = "paymentableGenerator", strategy = "uuid")
@Column(name ="ID",nullable=false,length=36)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(name ="ip")
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
@Column(name ="acctid")
public String getAcctid() {
return acctid;
}
public void setAcctid(String acctid) {
this.acctid = acctid;
}
@Column(name ="createDate")
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@Column(name ="operateDate")
public Date getOperateDate() {
return operateDate;
}
public void setOperateDate(Date operateDate) {
this.operateDate = operateDate;
}
}
|
#!/bin/bash
# Author: yeho <lj2007331 AT gmail.com>
# BLOG: https://linuxeye.com
#
# Notes: OneinStack for CentOS/RedHat 7+ Debian 8+ and Ubuntu 16+
#
# Project home page:
# https://oneinstack.com
# https://github.com/oneinstack/oneinstack
Install_phpMyAdmin() {
if [ -e "${php_install_dir}/bin/phpize" ]; then
pushd ${oneinstack_dir}/src > /dev/null
PHP_detail_ver=`${php_install_dir}/bin/php-config --version`
PHP_main_ver=${PHP_detail_ver%.*}
if [[ "${PHP_main_ver}" =~ ^5.[3-6]$|^7.[0-1]$ ]]; then
tar xzf phpMyAdmin-${phpmyadmin_oldver}-all-languages.tar.gz
/bin/mv phpMyAdmin-${phpmyadmin_oldver}-all-languages ${wwwroot_dir}/default/phpMyAdmin
else
tar xzf phpMyAdmin-${phpmyadmin_ver}-all-languages.tar.gz
/bin/mv phpMyAdmin-${phpmyadmin_ver}-all-languages ${wwwroot_dir}/default/phpMyAdmin
fi
/bin/cp ${wwwroot_dir}/default/phpMyAdmin/{config.sample.inc.php,config.inc.php}
mkdir ${wwwroot_dir}/default/phpMyAdmin/{upload,save}
sed -i "s@UploadDir.*@UploadDir'\] = 'upload';@" ${wwwroot_dir}/default/phpMyAdmin/config.inc.php
sed -i "s@SaveDir.*@SaveDir'\] = 'save';@" ${wwwroot_dir}/default/phpMyAdmin/config.inc.php
sed -i "s@host'\].*@host'\] = '127.0.0.1';@" ${wwwroot_dir}/default/phpMyAdmin/config.inc.php
sed -i "s@blowfish_secret.*;@blowfish_secret\'\] = \'$(cat /dev/urandom | head -1 | base64 | head -c 45)\';@" ${wwwroot_dir}/default/phpMyAdmin/config.inc.php
chown -R ${run_user}:${run_group} ${wwwroot_dir}/default/phpMyAdmin
popd > /dev/null
fi
}
|
export const LOGIN_START = 'LOGIN_START';
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGIN_FAILURE = 'LOGIN_FAILURE';
export const LOGOUT_START = 'LOGOUT_START';
export const LOGOUT_SUCCESS = 'LOGOUT_SUCCESS';
export const REGISTER_START = 'REGISTER_START';
export const REGISTER_SUCCESS = 'REGISTER_SUCCESS';
export const REGISTER_FAILURE = 'REGISTER_FAILURE';
export const PREDICT_START = 'PREDICT_START';
export const PREDICT_SUCCESS = 'PREDICT_SUCCESS';
export const PREDICT_FAILURE = 'PREDICT_FAILURE';
export const DELETE_USER_START = 'DELETE_USER_START';
export const DELETE_USER_SUCCESS = 'DELETE_USER_SUCCESS';
export const DELETE_USER_FAILURE = 'DELETE_USER_FAILURE';
export const UPDATE_USER_START = 'UPDATE_USER_START';
export const UPDATE_USER_SUCCESS = 'UPDATE_USER_SUCCESS';
export const UPDATE_USER_FAILURE = 'UPDATE_USER_FAILURE';
|
#!/bin/bash
source `dirname $0`/../common.sh
docker run -v $OUTPUT_DIR:/tmp/output -v $CACHE_DIR:/tmp/cache -e VERSION=2.5.7 -e STACK=cedar-14 hone/ruby-builder:cedar-14
|
<gh_stars>0
package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.merchant.mrchsurp.activitysignup.create response.
*
* @author auto create
* @since 1.0, 2021-06-25 14:02:36
*/
public class AlipayMerchantMrchsurpActivitysignupCreateResponse extends AlipayResponse {
private static final long serialVersionUID = 1596885596484994967L;
/**
* 报名成功后返回报名记录ID,报名失败无该字段
*/
@ApiField("signup_record_id")
private String signupRecordId;
public void setSignupRecordId(String signupRecordId) {
this.signupRecordId = signupRecordId;
}
public String getSignupRecordId( ) {
return this.signupRecordId;
}
}
|
/* eslint-disable no-undef */
console.log('Background.js LOADED');
/* const defaultUninstallURL = () => {
return process.env.NODE_ENV === 'production'
? 'https://wwww.github.com/kryptokinght'
: '';
}; */
browser.runtime.onMessage.addListener(function (message) {
console.log(message);
});
// if (chrome.identity == null) {
// console.log("user is not registered")
// }
// else {
// chrome.identity.getProfileUserInfo(function(userInfo) {
// console.log(JSON.stringify(userInfo));
// });
// }
|
<gh_stars>0
package br.com.zup.mercadolivre.pergunta;
public interface DisparadorEmail {
void enviarEmail(Pergunta pergunta);
}
|
<gh_stars>10-100
require 'rails_helper'
RSpec.describe CancellationDecorator do
let!(:visit) { create(:cancelled_visit) }
let(:cancellation) { create(:cancellation, visit: visit) }
subject { described_class.decorate(cancellation) }
describe '#formatted_reasons' do
before do
cancellation.reasons = reasons
end
context 'when containing child protection' do
let(:reasons) { [Cancellation::CHILD_PROTECTION_ISSUES] }
it 'has the correct explanation' do
expect(
subject.formatted_reasons.map(&:explanation)
).to eq([
"there are restrictions around this prisoner. You may be able to visit them at a later date."
])
end
end
context 'when containing prisoner non association' do
let(:reasons) { [Cancellation::PRISONER_NON_ASSOCIATION] }
it 'has the correct explanation' do
expect(
subject.formatted_reasons.map(&:explanation)
).to eq([
"there are restrictions around this prisoner. You may be able to visit them at a later date."
])
end
end
context 'when containing visitor banned' do
let(:reasons) { [Cancellation::VISITOR_BANNED] }
it 'has the correct explanation' do
expect(
subject.formatted_reasons.map(&:explanation)
).to eq([
"you have been banned from visiting this prison. We’ve sent you a letter with further details."
])
end
end
context 'when containing both a no association and another non-restriction reason' do
let(:reasons) do
[
Cancellation::PRISONER_NON_ASSOCIATION,
Cancellation::CHILD_PROTECTION_ISSUES
]
end
it 'has a restricted and another restricted reasons' do
expect(subject.formatted_reasons.map(&:explanation)).
to contain_exactly("there are restrictions around this prisoner. You may be able to visit them at a later date.")
end
end
end
end
|
#!/bin/bash
FILES=/bio/lillyl1/EE283/Bioinformatics_Course/data/od_rawdata/*/DNAseq/*SANGER.fq.gz
for f in $FILES
do
mv $f "$(dirname $(dirname "$f"))/DNAseq.SANGER"
done
|
import ServerJSImpl from 'bigpipe-util/src/ServerJS';
export default class ServerJS extends ServerJSImpl {
}
|
class LinearEquation:
def __init__(self, m, c):
self.m = m
self.c = c
def __repr__(self):
return f"y = {self.m}x + {self.c}"
def evaluate(self, x):
return self.m * x + self.c
def find_root(self):
return -self.c / self.m |
<gh_stars>0
export function assignButtons() {
const links = document.querySelector('.footer-links').children;
links[0].addEventListener('click', home);
links[1].addEventListener('click', randomVersion);
links[2].addEventListener('click', latestVersion);
}
function randomVersion() {
const menu = [...document.querySelectorAll('.dropdown-content')].flatMap(e => [...e.children]);
const random = Math.floor(Math.random() * menu.length);
menu[random].click();
}
function latestVersion() {
const menu = [...document.querySelectorAll('.dropdown-content')]
.flatMap(e => [...e.children])
.filter(e => e.parentElement.parentElement.querySelector('button').innerText !== 'Others');
menu[menu.length - 1].click();
}
function home() {
document.querySelector('.home').style.display = 'flex';
document.querySelector('.content').innerHTML = '';
document.title = 'VersionCraft - Home';
}
|
//
// TeamView.h
// Team Communicator
//
// Created by <NAME> on 16.04.10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "PersonalRecordingItem.h"
#import "ItemCreateViewController.h"
#import <MessageUI/MessageUI.h>
#import "OutputFormatter.h"
#import <iAd/iAd.h>
@interface ItemViewController : UIViewController <UINavigationControllerDelegate, MFMailComposeViewControllerDelegate, ModalScreenCloser, ADBannerViewDelegate> {
PersonalRecordingItem* recordingitem;
IBOutlet UILabel* teamName;
IBOutlet UILabel* teamKeywords;
IBOutlet UIImageView* teamImage;
IBOutlet UILabel* plannedEffortLabel;
IBOutlet UILabel* actualEffortLabel;
IBOutlet UILabel* lastTimeRecord;
IBOutlet UIButton* startStopButton;
ItemCreateViewController* itemController;
ADBannerView* adBannerView;
BOOL adVisible;
NSTimer* timer;
}
@property(assign) IBOutlet UILabel* teamName;
@property(assign) IBOutlet UILabel* teamKeywords;
@property(assign) IBOutlet UIImageView* teamImage;
@property(assign) IBOutlet UILabel* plannedEffortLabel;
@property(assign) IBOutlet UILabel* actualEffortLabel;
@property(assign) IBOutlet UILabel* lastTimeRecord;
@property(assign) IBOutlet UIButton* startStopButton;
@property(assign) PersonalRecordingItem* recordingitem;
@property(assign) IBOutlet ADBannerView* adBannerView;
-(void)refreshUI;
-(IBAction)editItem;
-(IBAction)recordTime;
-(IBAction)showTimeRecords;
-(IBAction)startStopTimeRecording;
-(void)refreshQuickRecordingButtonLabel;
@end
|
import { uniqueColumnNames } from "./array.ts";
import { assertEquals } from "../../testdeps.ts";
Deno.test("uniqueColumnNames() -> should remove duplicate column names", () => {
const columns = uniqueColumnNames(["name", "email", "password", "email"]);
assertEquals(columns, ["name", "email", "password"]);
});
Deno.test("uniqueColumnNames() -> should remove duplicate column names with aliases", () => {
const columns = uniqueColumnNames([
["name", "users_name"],
["email", "users_email"],
"password",
["name", "users_email"],
]);
assertEquals(columns, [
["name", "users_name"],
["email", "users_email"],
"password",
]);
});
|
unique_dict = {
'alec' : 'alec',
'bob' : 'bob',
'sara' : 'sara',
'john' : 'john',
'elon' : 'elon'
} |
<reponame>erik168/san
/**
* @file 服务
*/
import data from './data'
/**
* 对象属性拷贝
*
* @inner
* @param {Object} target 目标对象
* @param {Object} source 源对象
* @return {Object} 返回目标对象
*/
function extend(target, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
return target;
}
export default {
todos: function (category) {
var categoryMap = {};
for (var i = 0; i < data.category.length; i++) {
var item = data.category[i];
categoryMap[item.id] = item;
}
var todos = [];
for (var i = 0; i < data.list.length; i++) {
var item = data.list[i];
if (!category || item.categoryId === category) {
item = extend({}, item);
todos.push(item);
if (item.categoryId) {
item.category = extend({}, categoryMap[item.categoryId]);
}
}
}
return todos;
},
todo: function (id) {
var categoryMap = {};
for (var i = 0; i < data.category.length; i++) {
var item = data.category[i];
categoryMap[item.id] = item;
}
for (var i = 0; i < data.list.length; i++) {
var item = data.list[i];
if (item.id === id) {
if (item.categoryId) {
item = extend({}, item);
item.category = extend({}, categoryMap[item.categoryId]);
}
return item;
}
}
return null;
},
categories: function () {
var categories = [];
for (var i = 0; i < data.category.length; i++) {
categories.push(extend({}, data.category[i]));
}
return categories;
},
doneTodo: function (id) {
for (var i = 0; i < data.list.length; i++) {
var item = data.list[i];
if (item.id === id) {
item.done = true;
break;
}
}
},
rmTodo: function (id) {
id = +id;
for (var i = 0; i < data.list.length; i++) {
var item = data.list[i];
if (item.id === id) {
data.list.splice(i, 1);
break;
}
}
},
addTodo: function (todo) {
var first = data.list[0];
var id = 1;
if (first) {
id = first.id + 1;
}
todo = extend({}, todo);
todo.id = id;
data.list.unshift(todo);
},
editTodo: function (todo) {
todo = extend({}, todo);
for (var i = 0; i < data.list.length; i++) {
var item = data.list[i];
if (item.id === todo.id) {
data.list[i] = todo;
break;
}
}
},
addCategory: function (category) {
var first = data.category[0];
var id = 1;
if (first) {
id = first.id + 1;
}
category = extend({}, category);
category.id = id;
data.category.unshift(category);
},
rmCategory: function (id) {
id = +id;
for (var i = 0; i < data.category.length; i++) {
var item = data.category[i];
if (item.id === id) {
data.category.splice(i, 1);
break;
}
}
},
editCategory: function (category) {
category = extend({}, category);
for (var i = 0; i < data.category.length; i++) {
var item = data.category[i];
if (item.id === category.id) {
data.category[i] = category;
break;
}
}
}
};
|
<reponame>xThundr/cit111_ccac<filename>FoodLand.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package objects1;
/**
*
* @author Tyler
*/
public class FoodLand {
public static void main(String[]args){
//new donut object
Donut glazed;
glazed= new Donut();
glazed.name= "Glazed";
//new salad object
Salad house;
house= new Salad();
house.name= "House";
house.containsNuts= false;
house.lettuceType= "Iceberg";
house.vegetarian= false;
//new burger object
Burger whopper;
whopper= new Burger();
whopper.name= "Whopper";
whopper.temperature= "medium-well";
whopper.numPatties= 2;
whopper.includeSteakSauce= false;
//running methods to display each object's variable statuses
getDonutData(glazed);
getSaladData(house);
getBurgerData(whopper);
//running donut methods
glazed.simulateEating(25);
glazed.getPercRemaining();
//running salad methods
house.eatSalad(40);
house.addMeat();
//running burger methods
whopper.eatBurger(70);
whopper.addSteakSauce();
//displaying object's variables again to compare to originals
getDonutData(glazed);
getSaladData(house);
getBurgerData(whopper);
}//close main method
public static void getDonutData(Donut inputDonut){
System.out.println("------STATS-------");
System.out.println("Name: "+inputDonut.name);
System.out.println("PercRemaining: "+inputDonut.percRemaining);
System.out.println("------------------");
}//close method
public static void getSaladData(Salad inputSalad){
System.out.println("------STATS-------");
System.out.println("Name: "+inputSalad.name);
System.out.println("PercRemaining: "+inputSalad.percRemaining);
System.out.println("Contains Nuts: "+inputSalad.containsNuts);
System.out.println("Lettuce Type: "+inputSalad.lettuceType);
System.out.println("Vegetarian: "+inputSalad.vegetarian);
System.out.println("------------------");
}//close method
public static void getBurgerData(Burger inputBurger){
System.out.println("------STATS-------");
System.out.println("Name: "+inputBurger.name);
System.out.println("PercRemaining: "+inputBurger.percRemaining);
System.out.println("Temperature: "+inputBurger.temperature);
System.out.println("Number of Patties: "+inputBurger.numPatties);
System.out.println("Steak Sauce Included: "+inputBurger.includeSteakSauce);
System.out.println("------------------");
}//close method
}//close class
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clientenvoifichiertexteOLD;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.util.regex.Pattern;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
/**
* CLIENT GUI CLASS
*
* @author <NAME>
*/
public final class FenetreClient extends JFrame{
//implements Runnable
// Le pattern de l'adresse IP adresse
private static final String ipv4Pattern = "(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])";
// Le pattern du numéro du port
private static final String portPattern = "^[0-9]+$";
// Le menu
private JMenu menu;
private JMenuBar menuBar;
private JMenuItem item1, item2, item3, item4;
private File fichier;
private static JFileChooser fileChooser;
private BufferedReader bufferReader;
private String fichierTxtEnvParClient;
private String ligne;
// Le container des panneaux
private Container ConteneurDesPanneaux;
// Les panneaux
private JPanel panneauEntrees;
private JPanel panneauCsMsgs;
private JPanel panneauCtrlBoutons;
// Les Entrées
private JLabel serveurAdresseLbl;
private JLabel portnumeroLbl;
private JTextField serveurAdresse;
private JTextField portnumero;
// Les zones de messages
private JLabel clientMsgLbl;
private JLabel serveurMsgLbl;
private JTextArea clientMsg;
private JTextArea serveurMsg;
private JScrollPane clientMsgscroll;
private JScrollPane serveurMsgscroll;
// Les boutons
private JButton connexionBtn;
private JButton terminerBtn;
// Heure et autres
private JLabel labeldateheure1;
private JLabel lblvide;
// Les Classes de MonClient et autres.
private MonClient monClient = null; //monClient ou mc ds le code du serveur
//
private MonServeur monServeur = null; //
public JMenu creerMenu() {
// Création et ajout de la barre de menu
menu = new JMenu("Fichier");
menu.setMnemonic(KeyEvent.VK_F); // ajout de mnémonique (correspondant au soulignement de la lettre << F >> dans Fichier
menuBar = new JMenuBar();
setJMenuBar(menuBar);
menuBar.add(menu);
// Création et ajout des éléments du menu ainsi que de leur écouteur d'événements
item1 = new JMenuItem("Ouvrir");
item1.setMnemonic(KeyEvent.VK_O);
//item1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_DOWN_MASK + KeyEvent.SHIFT_DOWN_MASK));// ajoute d'accélérateur 'F' ctrl+shift+O
item1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_MASK));// ajoute d'accélérateur 'F'
// item2 = new JMenuItem("Connexion");
// item2.setMnemonic(KeyEvent.VK_C);
// item3 = new JMenuItem("Terminé");
// item4 = new JMenuItem("Quitter");
menu.add(item1);
// menu.add(item2);
// menu.add(item3);
// menu.add(item4);
item1.addActionListener(new OpenListener());
// item2.addActionListener(new OpenListener());
// item3.addActionListener(new OpenListener());
// item4.addActionListener(new OpenListener());
return menu; // Retourner le menu si la méthode "creerMenu()" est appellée
}
// Création de la méthode "creerPanneauEntrees()"
public JPanel creerPanneauEntrees() {
panneauEntrees = new JPanel(new GridLayout(3, 3));
//Séparation des elements labels et textfield correspondant à chaque entree
JPanel zone1= new JPanel();
JPanel zone2= new JPanel();
JPanel zone3= new JPanel();
//Heure affichage ds zone 2
labeldateheure1 = new JLabel("Horloge"); //Instantiation du label "labeldateheure1" pour y afficher l'heure
labeldateheure1.setFont(new Font("sansserif", Font.PLAIN, 40));
zone3.add(labeldateheure1);
panneauEntrees.add(zone3);
// Création des elements d'entrees
serveurAdresseLbl= new JLabel("Serveur :");
serveurAdresse= new JTextField("localhost",25);
portnumeroLbl= new JLabel(" Port :");
portnumero= new JTextField("2222",25);
// Ajout des éléments d'entrées à chaque zone dans le panneaux des entrees
zone1.add(serveurAdresseLbl);
zone1.add(serveurAdresse);
panneauEntrees.add(zone1);
zone2.add(portnumeroLbl);
zone2.add(portnumero);
panneauEntrees.add(zone2);
ConteneurDesPanneaux = this.getContentPane();
ConteneurDesPanneaux.add(panneauEntrees,BorderLayout.NORTH);
return panneauEntrees; // Retourner le panneau d'Entrees si la méthode "creerPanneauEntrees()" est appellée
}
// Création de la méthode "creerpanneauCsMsgs()"
public Container creerPanneauCsMsgs() {
panneauCsMsgs = new JPanel();
//Séparation des elements labels et textfield correspondant à chaque entree
JPanel zoneOuest= new JPanel(new GridBagLayout());
JPanel zoneEst= new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL;
// TextArea du Client
clientMsgLbl= new JLabel("Client" );
c.insets = new Insets(10,10,10,20); //top padding - espace de 5
c.gridx = 0;
zoneOuest.add(clientMsgLbl,c);
clientMsg = new JTextArea("",20, 40);
//clientMsg.getDocument().addDocumentListener(new MyDocumentListener()); // Docment listener
clientMsgscroll=new JScrollPane(clientMsg);
clientMsgscroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
zoneOuest.add(clientMsgscroll,c);
add(zoneOuest,BorderLayout.WEST);
panneauCsMsgs.add(zoneOuest, BorderLayout.CENTER);
// TextArea du Serveur
serveurMsgLbl= new JLabel("Serveur");
c.insets = new Insets(10,10,10,20); //top padding - espace de 5
c.gridx = 0;
c.gridwidth = 0;
zoneEst.add(serveurMsgLbl,c);
serveurMsg = new JTextArea("",20, 40);
serveurMsg.setEditable(false);
//serveurMsg.addTextListener(new MyTextListener("Text Area"));
serveurMsgscroll=new JScrollPane(serveurMsg);
serveurMsgscroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
zoneEst.add(serveurMsgscroll);
add(zoneEst,BorderLayout.EAST);
panneauCsMsgs.add(zoneEst, BorderLayout.CENTER);
ConteneurDesPanneaux = this.getContentPane();
ConteneurDesPanneaux.add(panneauCsMsgs,BorderLayout.CENTER);
return panneauCsMsgs;// Retourner le panneau d'Entrees si la méthode "creerpanneauCsMsgs()" est appellée
}
// Création de la méthode "creerPanneauCtrlBoutons()"
public JPanel creerPanneauCtrlBoutons() {
panneauCtrlBoutons = new JPanel();
// Création du bouton "Connexion" ainsi que de son écouteur d'événements
connexionBtn =new JButton("Connexion");
connexionBtn.addActionListener(new OpenListener());
panneauCtrlBoutons.add(connexionBtn,BorderLayout.WEST);
// Création du bouton "Terminé" ainsi que de son écouteur d'événements
terminerBtn=new JButton("Terminé");
terminerBtn.addActionListener(new OpenListener());
panneauCtrlBoutons.add(terminerBtn,BorderLayout.EAST);
terminerBtn.setEnabled(false);
ConteneurDesPanneaux = this.getContentPane();
ConteneurDesPanneaux.add(panneauCtrlBoutons,BorderLayout.SOUTH);
return panneauCtrlBoutons;// Retourner le panneau d'Entrées si la méthode "panneauCtrlBoutons()" est appellée
}
/**
* Valide l'adresse ip avec une expression regulière
* @param ipStr adresse ip pour la validation
* @return boolean -true pour la valide adresse ip et false pour l'invalide adresse ip
*/
public boolean validateIP(String ipStr) {
String regex = ipv4Pattern;
// Si adresse IP est localhost
if(ipStr.equals("localhost")) return Pattern.matches("localhost", ipStr);
// Si le cas contraire
if ( Pattern.matches(regex, ipStr)==false) {
JOptionPane.showMessageDialog(null, "Adresse IP invalide -Entrer le bon format","Erreur",JOptionPane.ERROR_MESSAGE);
System.err.println(Pattern.matches(regex, ipStr)+" - Adresse IP " +ipStr + " est non valide");
System.out.println("-------------------------------------------------------------");
}
return Pattern.matches(regex, ipStr);
}
/**
* Valide le numéro de port avec une expression régulière
* @param portStr numéro de port pour la validation
* @return boolean -true pour le valide numéro de port et false pour l'invalide numéro de port
*/
public boolean validatePort(String portStr) {
String regex = portPattern ;
if ( Pattern.matches(regex, portStr)==false ){
JOptionPane.showMessageDialog(null, "Port invalide -Entrer que des chifres Ex:2222 ","Erreur",JOptionPane.ERROR_MESSAGE);
System.err.println(Pattern.matches(regex, portStr)+" - Numéro de port " +portStr + " non valide");
System.out.println("-------------------------------------------------------------");
}
return Pattern.matches(regex, portStr);
}
//255.245.188.123 -ok
//255.245.188.451 -no ok
/**
* Lance les processus de validation des entrées (adresse IP et du Port)
*/
public void checkZoneDeText (){
System.out.println("-------------------------------------------------------------");
//Validation de l'adresse IP et du Port
if((validateIP(serveurAdresse.getText()))==false)
serveurAdresse.requestFocus();
if(validatePort(portnumero.getText())==false)
portnumero.requestFocus();
}
/**methode qui permet de choisir un fichier avec une interface graphique
*
* @return string qui contient le chemin du fichier
*/
public String obtenirCheminDuFichier(){
JFileChooser fileChooser = new JFileChooser();
if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){
// retourner le chemin du fichier choisie
return fileChooser.getSelectedFile().getPath();
}
return "";
}
private class OpenListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// Création et assignation de ma commande à ma chaîne de caractères "btnSelectionner"
String btnSelectionner;
btnSelectionner = e.getActionCommand();
// Si btnSelectionner est "Ouvrir"
if (btnSelectionner.equals("Ouvrir")) {
System.out.println("++++L'ecouteur du bouton \"Ouvrir\" recoit un ActionEvent");
System.out.println("-->Lancemet du Thread CLientEnvoiFIchierTexte");
// CLientEnvoiFIchierTexte Thread
Thread Lecture;
Lecture=new Thread(new Runnable() {
public void run() {
//
fichierTxtEnvParClient = obtenirCheminDuFichier();
try { bufferReader = new BufferedReader(new FileReader(fichierTxtEnvParClient)); }
catch (FileNotFoundException e1) { }
try { ligne = bufferReader.readLine(); }
catch (IOException e1) {}
// Mon EDT: invokeLater
EventQueue.invokeLater(new Runnable() {
public void run() {
//
while (ligne != null) {
clientMsg.append(ligne + "\n");
try { ligne = bufferReader.readLine();}
catch (IOException e1) { }
}
}
});
}
});
Lecture.start();
}
// Si btnSelectionner est "Connexion"
if (btnSelectionner.equals("Connexion")) {
// Faire si le bouton "Connexion" est cliqué
System.out.println("-------------------------------------------------------------");
System.out.println("+L'ecouteur du bouton\"Connexion\" recoit un ActionEvent");
// Appelle de la méthode de vérification des entrées - zones de textes (adresse IP et port)
checkZoneDeText();
// Création d'un nouveau client si pas existant
if (monClient==null){
try {
monClient =new MonClient(serveurAdresse.getText(),Integer.parseInt(portnumero.getText()));
System.out.println("mc = "+monClient+ "client:"+monClient);
connexionBtn.setText("Transmettre");
serveurMsg.append(monClient.lireServeur()+'\n');
serveurAdresse.setEnabled(false);
portnumero.setEnabled(false);
terminerBtn.setEnabled(true);// Active le bouton "Terminé"
connexionBtn.addActionListener(new OpenListener2());
clientMsg.requestFocus();
}
catch (IOException ex) {
//Logger.getLogger(FenetreClient.class.getName()).log(Level.SEVERE, null, ex);
System.err.println("!! monClient= "+monClient);
}
}
else {
monClient.ecrireServeur(clientMsg.getText());
serveurMsg.append(monClient.lireServeur()+" : "+clientMsg.getText() +'\n'); //Ecrire ce que le serveur répond dans la jTextArea du serveur
clientMsg.setText("");
clientMsg.requestFocus();
}
}
// Si btnSelectionner est "Terminé"
if (btnSelectionner.equals("Terminé")) {
// Faire si le bouton Terminé" est cliqué
System.out.println("++L'ecouteur du bouton \"Terminé\" recoit un ActionEvent");
clientMsg.setText("fin");
monClient.ecrireServeur(clientMsg.getText());
terminerBtn.setEnabled(false);
if (clientMsg.getText().equals("fin")) {
serveurMsg.append(monClient.lireServeur());
clientMsg.setText("");
clientMsg.setVisible(false);
connexionBtn.setEnabled(false);
clientMsg.setEditable(false);
JOptionPane.showMessageDialog(null,"Déconnexion du serveur effectué ","Information",JOptionPane.INFORMATION_MESSAGE);
terminerBtn.setText("Quitter");
terminerBtn.setEnabled(true);
}
}
// Si btnSelectionner est "Quitter"
if (btnSelectionner.equals("Quitter")) {
// Faire si le bouton "Quitter" est cliqué
System.out.println("+++L'ecouteur du bouton \"Quitter\" du menu ou pas du menu recoit un ActionEvent");
System.exit(0); // Fermer la fenetre ou quitter le programme.
}
}
}
private class OpenListener2 implements ActionListener {
@Override
public void actionPerformed(ActionEvent e2) {
// Création et assignation de ma commande à ma chaîne de caractères "btnSelectionner"
String btnSelectionner2;
btnSelectionner2 = e2.getActionCommand();
// Si btnSelectionner est "Transmettre"
if (btnSelectionner2.equals("Transmettre")) {
// Faire clientMsg est vide
if(clientMsg.getText().equals("")) {
JOptionPane.showMessageDialog(null,"!!Pas d'instructions entrées par le client !! ","Information",JOptionPane.ERROR_MESSAGE);
clientMsg.requestFocus();
}
// Faire si non vide
while (!clientMsg.getText().equals("")){
if (monClient==null){
try {
monClient =new MonClient(serveurAdresse.getText(),Integer.parseInt(portnumero.getText()));
clientMsg.requestFocus();
terminerBtn.setEnabled(true);// Active le bouton "Terminé"
monClient.ecrireServeur(clientMsg.getText());
serveurMsg.append(monClient.lireServeur()+'\n'); //Ecrire ce que le serveur répond dans la jTextArea du serveur
clientMsg.setText("");
clientMsg.requestFocus();
}
catch (IOException ex) {
Logger.getLogger(FenetreClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{ // Faire au cas de commande "fin"
monClient.ecrireServeur(clientMsg.getText());
if (clientMsg.getText().equals("fin")) {
serveurMsg.append(monClient.lireServeur());
connexionBtn.setEnabled(false);
clientMsg.setText("");
clientMsg.setVisible(false);
clientMsg.setEditable(false);
JOptionPane.showMessageDialog(null,"Déconnexion du serveur effectué ","Information",JOptionPane.INFORMATION_MESSAGE);
terminerBtn.setText("Quitter");
terminerBtn.setEnabled(true);
}
// Faire Sinon
else {
serveurMsg.append(monClient.lireServeur()+" : "+clientMsg.getText()+'\n'); //Ecrire ce que le serveur répond dans la jTextArea du serveur
clientMsg.setText("");
clientMsg.requestFocus();
}
}
}
}
}
}
// constructeur par défaut
FenetreClient() {
setTitle("Interface Client pour se connecter à serveur spécifié et un port indiqué");
setSize(200,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // choix du comportement à la fermeture de la fenetre
// Appelle des méthodes de créations du menu , des panneaux d'entrées, de messages et des boutons de contrôle
creerMenu(); // appelle de la méthode "creerMenu()"
creerPanneauEntrees(); // appelle de la méthode "creerPanneauEntrees()"
creerPanneauCsMsgs(); // appelle de la méthode "creerMenu()"
creerPanneauCtrlBoutons(); // appelle de la méthode "creerMenu()"
//CREATION DE NOTRE TIMER
Timer timer = new Timer(1000, new HorlogeListener());//Nouveau thread (timer) va se creer
timer.start();//Lancer l'affichage du timer
}
public void run() {
while (true) {
;
}
}
/*
GESTION DU TIMER ET DU CONTENU DES JLIST QUAND VALEUR DE L'HEURE OU DATE DEPASSE OU OBSOLETE
-->ASSOCIATION D'UNE CLASSE DÉTECTEUR D'ÉVÉNEMENT (ÉCOUTEUR)AU TIMER
*/
class HorlogeListener implements ActionListener {
//ce que l'on fait quand on détecte un événement :
public void actionPerformed(ActionEvent e) {
//MON FORMAT AFFICHAGE DATE ET HEURE COURANTE DANS HORLOGE
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
labeldateheure1.setText(df.format(Calendar.getInstance().getTime()));
}
}
}
|
import { useState } from 'react'
import '../styles/tasklist.scss'
import { FiTrash, FiCheckSquare } from 'react-icons/fi'
interface Task {
id: number;
title: string;
isComplete: boolean;
}
export function TaskList() {
const [tasks, setTasks] = useState<Task[]>([]);
const [newTaskTitle, setNewTaskTitle] = useState('');
// funcao que manipula a criaçao de uma nova tarefa
function handleCreateNewTask() {
// impede que seja criada uma task vazia
if(!newTaskTitle) return;
const addNewTask = {
id:Math.random(),
title:newTaskTitle,
isComplete: false
}
/* 'setState' pode ser usado na forma de callback
usando o conceito de "spreadoperator " que mantem o estado anterior"oldState" */
setTasks(oldState=>[...oldState,addNewTask]);
setNewTaskTitle('');
}
// funcao que vai manipular a comutacao de estado da variavel "isComplete" e seta-lo
/* precisamos ir na task ,mapear a task pelo id especifico ,entao altera-lo
e seta-lo no estado.
para isso usamos o operador TERNARIO*/
function handleToggleTaskCompletion(id: number) {
const newTasks = tasks.map(task=>task.id == id ?{
...task,
isComplete:!task.isComplete
}:task)
setTasks(newTasks)
}
function handleRemoveTask(id: number) {
//remover tarefa:
const filteredTasks = tasks.filter(task=>task.id !== id);
// Aqui estamos setando a array de tasks com as tasks filtradas
// criando um novo objeto nunca alterando(imutabilidade)
// alocando um novo espaço na memoria(mais inteligente)
setTasks(filteredTasks);
}
return (
<section className="task-list container">
<header>
<h2>Minhas tasks</h2>
<div className="input-group">
<input
type="text"
placeholder="Adicionar novo todo"
onChange={(e) => setNewTaskTitle(e.target.value)}
value={newTaskTitle}
/>
<button type="submit" data-testid="add-task-button" onClick={handleCreateNewTask}>
<FiCheckSquare size={16} color="#fff"/>
</button>
</div>
</header>
<main>
<ul>
{tasks.map(task => (
<li key={task.id}>
<div className={task.isComplete ? 'completed' : ''} data-testid="task" >
<label className="checkbox-container">
<input
type="checkbox"
readOnly
checked={task.isComplete}
onClick={() => handleToggleTaskCompletion(task.id)}
/>
<span className="checkmark"></span>
</label>
<p>{task.title}</p>
</div>
<button type="button" data-testid="remove-task-button" onClick={() => handleRemoveTask(task.id)}>
<FiTrash size={16}/>
</button>
</li>
))}
</ul>
</main>
</section>
)
} |
<reponame>wm3418925/modbus-utils
package wangmin.modbus.entity.type;
/**
* Created by wm on 2017/1/3.
*/
public enum ModbusByteOrderType {
/**
* 如有多个寄存器,则存储低字节的寄存器在前,每个寄存器内部大端排序,modbus模拟器默认 0 GRM503对应编码 3412
*/
LowFirstBigEndian(0),
/**
* 如有多个寄存器,则存储高字节的寄存器在前,每个寄存器内部大端排序 GRM503对应编码 1234
*/
HighFirstBigEndian(1),
/**
* 如有多个寄存器,则存储低字节的寄存器在前,每个寄存器内部小端排序 GRM503对应编码 4321
*/
LowFirstLittleEndian(2),
/**
* 如有多个寄存器,则存储高字节的寄存器在前,每个寄存器内部小端排序 GRM503对应编码 2143
*/
HighFirstLittleEndian(3);
protected static final ModbusByteOrderType defaultEnum = HighFirstBigEndian;
protected final int value;
private ModbusByteOrderType(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public static int getValue(ModbusByteOrderType status) {
if (status == null)
return defaultEnum.value;
else
return status.value;
}
public static ModbusByteOrderType valueOf(int value) {
ModbusByteOrderType[] list = ModbusByteOrderType.values();
for (int i=0; i<list.length; ++i) {
if (list[i].value == value)
return list[i];
}
return defaultEnum;
}
}
|
<filename>src/main/java/org/rs2server/rs2/action/impl/WieldItemAction.java
package org.rs2server.rs2.action.impl;
import org.rs2server.rs2.action.Action;
import org.rs2server.rs2.model.Item;
import org.rs2server.rs2.model.Mob;
import org.rs2server.rs2.model.Skills;
import org.rs2server.rs2.model.Sound;
import org.rs2server.rs2.model.container.Equipment;
import org.rs2server.rs2.model.container.Equipment.EquipmentType;
import org.rs2server.rs2.model.equipment.EquipmentDefinition.Skill;
public class WieldItemAction extends Action {
/**
* The item's id.
*/
private int id;
/**
* The item's slot.
*/
private int slot;
public WieldItemAction(Mob mob, int id, int slot, int ticks) {
super(mob, ticks);
this.id = id;
this.slot = slot;
}
@Override
public CancelPolicy getCancelPolicy() {
return CancelPolicy.ALWAYS;
}
@Override
public StackPolicy getStackPolicy() {
return StackPolicy.NEVER;
}
@Override
public AnimationPolicy getAnimationPolicy() {
return AnimationPolicy.RESET_ALL;
}
@Override
public void execute()
{
this.stop();
Item item = getMob().getInventory() != null ? getMob().getInventory().get(slot) : null;
if(item == null || item.getId() != id) {
return;
}
if(!getMob().canEmote()) {
return;
}
if(item.getEquipmentDefinition() == null || item.getEquipmentDefinition().getType() == null) {
if(getMob().getActionSender() != null) {
getMob().getActionSender().sendMessage("You can't wear that because it doesn't have definitions.");
}
return;
}
EquipmentType type = Equipment.getType(item);
if(item.getEquipmentDefinition() != null && item.getEquipmentDefinition().getSkillRequirements() != null) {
for(Skill skill : item.getEquipmentDefinition().getSkillRequirements().keySet()) {
if(getMob().getSkills().getLevelForExperience(skill.getId()) < item.getEquipmentDefinition().getSkillRequirement(skill.getId())) {
if(getMob().getActionSender() != null) {
String level = "a ";
if(Skills.SKILL_NAME[skill.getId()].toLowerCase().startsWith("a")) {
level = "an ";
}
level += Skills.SKILL_NAME[skill.getId()].toLowerCase();
getMob().getActionSender().sendMessage("You need to have " + level + " level of " + item.getEquipmentDefinition().getSkillRequirement(skill.getId()) + ".");
}
return;
}
}
}
long itemCount = item.getCount();
long equipCount = getMob().getEquipment().getCount(item.getId());
long totalCount = (itemCount + equipCount);
if(totalCount > Integer.MAX_VALUE) {
getMob().getActionSender().sendMessage("Not enough equipment space.");
return;
}
boolean inventoryFiringEvents = getMob().getInventory().isFiringEvents();
getMob().getInventory().setFiringEvents(false);
try {
if(type.getSlot() == 3 || type.getSlot() == 5) {
if(type == EquipmentType.WEAPON_2H) {
if(getMob().getEquipment().get(Equipment.SLOT_WEAPON) != null && getMob().getEquipment().get(Equipment.SLOT_SHIELD) != null) {
if(getMob().getInventory().freeSlots() < 1) {
if(getMob().getActionSender() != null) {
getMob().getActionSender().sendMessage("Not enough space in your inventory.");
}
return;
}
getMob().getInventory().remove(item, slot);
if(getMob().getEquipment().get(Equipment.SLOT_WEAPON) != null) {
getMob().getInventory().add(getMob().getEquipment().get(Equipment.SLOT_WEAPON), slot);
getMob().getEquipment().set(Equipment.SLOT_WEAPON, null);
}
if(getMob().getEquipment().get(Equipment.SLOT_SHIELD) != null) {
getMob().getInventory().add(getMob().getEquipment().get(Equipment.SLOT_SHIELD), slot - 1);
getMob().getEquipment().set(Equipment.SLOT_SHIELD, null);
}
getMob().getEquipment().set(type.getSlot(), item);
getMob().getCombatState().calculateBonuses();
if(getMob().getActionSender() != null) {
getMob().getActionSender().sendBonuses();
}
getMob().getInventory().fireItemsChanged();
return;
} else if(getMob().getEquipment().get(Equipment.SLOT_SHIELD) != null && getMob().getEquipment().get(Equipment.SLOT_WEAPON) == null) {
getMob().getInventory().remove(item, slot);
getMob().getEquipment().set(Equipment.SLOT_WEAPON, item);
getMob().getInventory().add(getMob().getEquipment().get(Equipment.SLOT_SHIELD), slot);
getMob().getEquipment().set(Equipment.SLOT_SHIELD, null);
getMob().getCombatState().calculateBonuses();
if(getMob().getActionSender() != null) {
getMob().getActionSender().sendBonuses();
}
getMob().getInventory().fireItemsChanged();
return;
}
}
if(type.getSlot() == Equipment.SLOT_SHIELD && getMob().getEquipment().get(Equipment.SLOT_WEAPON) != null
&& getMob().getEquipment().get(Equipment.SLOT_WEAPON).getEquipmentDefinition() != null
&& getMob().getEquipment().get(Equipment.SLOT_WEAPON).getEquipmentDefinition().getType() == EquipmentType.WEAPON_2H) {
getMob().getInventory().remove(item, slot);
getMob().getInventory().add(getMob().getEquipment().get(Equipment.SLOT_WEAPON), slot);
getMob().getEquipment().set(Equipment.SLOT_WEAPON, null);
getMob().getEquipment().set(Equipment.SLOT_SHIELD, item);
getMob().getCombatState().calculateBonuses();
if(getMob().getActionSender() != null) {
getMob().getActionSender().sendBonuses();
}
getMob().getInventory().fireItemsChanged();
return;
}
}
getMob().getInventory().remove(item, slot);
if(getMob().getEquipment().get(type.getSlot()) != null) {
if(getMob().getEquipment().get(type.getSlot()).getId() == item.getId()
&& item.getDefinition().isStackable()) {
item = new Item(item.getId(), getMob().getEquipment().get(type.getSlot()).getCount() + item.getCount());
} else {
if(getMob().getEquipment().get(type.getSlot()).getEquipmentDefinition() != null) {
for(int i = 0; i < getMob().getEquipment().get(type.getSlot()).getEquipmentDefinition().getBonuses().length; i++) {
getMob().getCombatState().setBonus(i, getMob().getCombatState().getBonus(i) - getMob().getEquipment().get(type.getSlot()).getEquipmentDefinition().getBonus(i));
}
}
getMob().getInventory().add(getMob().getEquipment().get(type.getSlot()), slot);
}
}
getMob().getEquipment().set(type.getSlot(), item);
switch(type)
{
default:
getMob().getActionSender().playSound(Sound.EQUIP_SOFT);
break;
case WEAPON:
getMob().getActionSender().playSound(Sound.EQUIP_SWORD);
break;
case WEAPON_2H:
getMob().getActionSender().playSound(Sound.EQUIP_CRUSH_WEP);
break;
case SHIELD:
getMob().getActionSender().playSound(Sound.EQUIP_SHIELD);
break;
case BODY:
case PLATEBODY:
getMob().getActionSender().playSound(Sound.EQUIP_PLATEBODY);
break;
case FULL_MASK:
case FULL_HELM:
getMob().getActionSender().playSound(Sound.EQUIP_HELM);
break;
case LEGS:
getMob().getActionSender().playSound(Sound.EQUIP_PLATELEGS);
break;
//case AMULET:
//case CAPE:
//case RING:
//getMob().getActionSender().playSound(Sound.EQUIP_SOFT);
//break;
}
if(item.getEquipmentDefinition() != null) {
for(int i = 0; i < item.getEquipmentDefinition().getBonuses().length; i++) {
getMob().getCombatState().setBonus(i, getMob().getCombatState().getBonus(i) + item.getEquipmentDefinition().getBonus(i));
}
}
if(getMob().getActionSender() != null) {
getMob().getActionSender().sendBonuses();
}
//if (!((Player)getMob()).hasQueuedSwitching()) {
getMob().getInventory().fireItemsChanged();
//}
if (item.getId() != 4153) {
getMob().resetInteractingEntity();
}
} finally {
getMob().getInventory().setFiringEvents(inventoryFiringEvents);
}
}
}
|
<reponame>lillianritchie/DWD-FINAL<gh_stars>0
//here is where we define what our database should expect from us
const mongoose = require('mongoose');
//schema is how we define what goes into our database
const Schema = mongoose.Schema;
const commentSchema = new Schema({
"name": String,
"location": String,
"email": String,
"comment": String
});
const db = mongoose.model('comments', commentSchema);
module.exports = db; |
gcloud beta app deploy --no-cache |
<gh_stars>0
import { all, put, takeLatest } from "redux-saga/effects";
import { LOAD_EVENTS, LOAD_FEATURED_EVENTS } from "./constants";
import events from "./mocks/Events";
import featuredEvents from "./mocks/FeaturedEvents";
import {
loadEventsSuccess,
loadEventsError,
loadFeaturedEventsSuccess,
loadFeaturedEventsError,
} from "./actions";
function* loadEvents() {
yield takeLatest(LOAD_EVENTS, fetchEvents);
}
function* loadFeaturedEvents() {
yield takeLatest(LOAD_FEATURED_EVENTS, fetchFeaturedEvents);
}
function* fetchEvents(action) {
try {
// use action param and call api
console.log("Events Tenant ID", action.tenantId);
console.log("Events skip", action.skip);
console.log("Events Take", action.take);
console.log("events", events);
yield put(loadEventsSuccess(events));
} catch (error) {
yield put(loadEventsError(error));
}
}
function* fetchFeaturedEvents(action) {
try {
// load Featured Events action and api call
console.log("Featured Events TenantId", action.tenantId);
console.log("Featured Skip", action.skip);
console.log("Featured Take", action.take);
console.log("featuredEvents", featuredEvents);
yield put(loadFeaturedEventsSuccess(featuredEvents));
} catch (error) {
yield put(loadFeaturedEventsError(error));
}
}
// Individual exports for testing
export default function* dashboardSaga() {
// See example in containers/HomePage/saga.js
yield all([loadEvents(), loadFeaturedEvents()]);
}
|
<filename>Source/Scene/ModelExperimental/ModelExperimentalSkin.js
import Matrix4 from "../../Core/Matrix4.js";
import Check from "../../Core/Check.js";
import defaultValue from "../../Core/defaultValue.js";
/**
* An in-memory representation of a skin that affects nodes in the {@link ModelExperimentalSceneGraph}.
* Skins should only be initialized after all of the {@link ModelExperimentalNode}s have been instantiated
* by the scene graph.
*
* @param {Object} options An object containing the following options:
* @param {ModelComponents.Skin} options.skin The corresponding skin components from the 3D model
* @param {ModelExperimentalSceneGraph} options.sceneGraph The scene graph this skin belongs to.
*
* @alias ModelExperimentalSkin
* @constructor
*
* @private
*/
export default function ModelExperimentalSkin(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
//>>includeStart('debug', pragmas.debug);
Check.typeOf.object("options.skin", options.skin);
Check.typeOf.object("options.sceneGraph", options.sceneGraph);
//>>includeEnd('debug');
this._sceneGraph = options.sceneGraph;
const skin = options.skin;
this._skin = skin;
this._inverseBindMatrices = undefined;
this._joints = [];
this._jointMatrices = [];
initialize(this);
}
Object.defineProperties(ModelExperimentalSkin.prototype, {
/**
* The internal skin this runtime skin represents.
*
* @memberof ModelExperimentalSkin.prototype
* @type {ModelComponents.Skin}
* @readonly
*
* @private
*/
skin: {
get: function () {
return this._skin;
},
},
/**
* The scene graph this skin belongs to.
*
* @type {ModelExperimentalSceneGraph}
* @readonly
*
* @private
*/
sceneGraph: {
get: function () {
return this._sceneGraph;
},
},
/**
* The inverse bind matrices of the skin.
*
* @memberof ModelExperimentalSkin.prototype
* @type {Matrix4[]}
* @readonly
*
* @private
*/
inverseBindMatrices: {
get: function () {
return this._inverseBindMatrices;
},
},
/**
* The joints of the skin.
*
* @memberof ModelExperimentalSkin.prototype
* @type {ModelExperimentalNode[]}
* @readonly
*
* @private
*/
joints: {
get: function () {
return this._joints;
},
},
/**
* The joint matrices for the skin, where each joint matrix is computed as
* jointMatrix = jointWorldTransform * inverseBindMatrix.
*
* Each node that references this skin is responsible for pre-multiplying its inverse
* world transform to the joint matrices for its own use.
*
* @memberof ModelExperimentalSkin.prototype
* @type {Matrix4[]}
* @readonly
*
* @private
*/
jointMatrices: {
get: function () {
return this._jointMatrices;
},
},
});
function initialize(runtimeSkin) {
const skin = runtimeSkin.skin;
const inverseBindMatrices = skin.inverseBindMatrices;
runtimeSkin._inverseBindMatrices = inverseBindMatrices;
const joints = skin.joints;
const length = joints.length;
const runtimeNodes = runtimeSkin.sceneGraph._runtimeNodes;
const runtimeJoints = runtimeSkin.joints;
const runtimeJointMatrices = runtimeSkin._jointMatrices;
for (let i = 0; i < length; i++) {
const jointIndex = joints[i].index;
const runtimeNode = runtimeNodes[jointIndex];
runtimeJoints.push(runtimeNode);
const inverseBindMatrix = inverseBindMatrices[i];
const jointMatrix = computeJointMatrix(
runtimeNode,
inverseBindMatrix,
new Matrix4()
);
runtimeJointMatrices.push(jointMatrix);
}
}
function computeJointMatrix(joint, inverseBindMatrix, result) {
const jointWorldTransform = Matrix4.multiplyTransformation(
joint.transformToRoot,
joint.transform,
result
);
result = Matrix4.multiplyTransformation(
jointWorldTransform,
inverseBindMatrix,
result
);
return result;
}
/**
* Updates the joint matrices for the skin.
*
* @private
*/
ModelExperimentalSkin.prototype.updateJointMatrices = function () {
const jointMatrices = this._jointMatrices;
const length = jointMatrices.length;
for (let i = 0; i < length; i++) {
const joint = this.joints[i];
const inverseBindMatrix = this.inverseBindMatrices[i];
jointMatrices[i] = computeJointMatrix(
joint,
inverseBindMatrix,
jointMatrices[i]
);
}
};
|
<filename>test/essentials.js
import test from 'tape'
import ReactFauxDOM from '..'
import Element from '../lib/Element'
test('has a create method', function (t) {
t.plan(1)
t.equal(typeof ReactFauxDOM.createElement, 'function')
})
test('creates an element instance with a nodeName', function (t) {
t.plan(2)
var el = ReactFauxDOM.createElement('div')
t.ok(el instanceof ReactFauxDOM.Element)
t.equal(el.nodeName, 'div')
})
test('hyphenated properties are camel cased', function (t) {
var el = ReactFauxDOM.createElement('div')
el.setAttribute('text-align', 'right')
t.plan(3)
t.equal(el.getAttribute('text-align'), 'right')
t.equal(el.getAttribute('textAlign'), 'right')
t.equal(el.toReact().props.textAlign, 'right')
})
test('children and childNodes behave properly', function (t) {
var parentEl = ReactFauxDOM.createElement('div')
var el = ReactFauxDOM.createElement('div')
var elReact = ReactFauxDOM.createElement('div').toReact()
var textNode = ReactFauxDOM.createElement('TextElement')
textNode.nodeType = 3
parentEl.appendChild(el)
parentEl.appendChild(elReact)
parentEl.appendChild(textNode)
t.plan(5)
t.equal(parentEl.childNodes.length, 3)
t.equal(parentEl.children.length, 2)
t.ok(parentEl.childNodes[0] instanceof Element)
t.equal(parentEl.childNodes[1].type, el.nodeName)
t.equal(parentEl.childNodes[2].nodeType, 3)
})
|
curl -X GET http://localhost:4000/trade/trade-12/status -H "authorization: Bearer ${JWT_EXP}" ; echo
|
<gh_stars>0
const Discord = require('discord.js'),
SQLManager = require('./manager.js'),
fs = require('fs'),
sleep = require('util').promisify(setTimeout),
v = '3.0.3',
inviteCompile = /(?:https?:\/\/)?discord(?:app\.com\/invite|\.gg)\/?[a-zA-Z0-9]+\/?/,
replyCompile = /^:>([0-9]{18}).+/,
quoteComplie = /^::>([0-9]{18}).+/,
contractE =
new Discord.RichEmbed()
.setTitle('すみどらちゃん|Sigma 利用規約')
.setDescription(
'すみどらちゃんは、Discordのさらなる発展を目指して作られたシステムです。\n' +
'このシステムでは、サーバーの規定は反映されず、\n下記の利用規約が適応されます。'
).addField(
'本規約について',
'この利用規約(以下,「本規約」といいます。)は,すみどらちゃんコミュニティチーム(以下,「当チーム」といいます。)\n' +
'が提供するサービス"すみどらちゃん"(以下,「本サービス」といいます。)の利用条件を定めるものです。\n' +
'利用ユーザーの皆さま(以下,「ユーザー」といいます。)には,本規約に従い本サービスをご利用いただきます。'
).addField(
'第1条(適用)',
'本規約は,ユーザーと当チームとの間の本サービスの利用に関わる一切の関係に適用されるものとします。'
).addField(
'第2条(権限について)',
'すみどらちゃん 開発者のすみどら#8923 (id:212513828641046529)は、\n' +
'本サービスの全ての権限を保有します。'
).addField(
'第3条(禁止事項)',
'ユーザーは,本サービスの利用にあたり,以下の行為をしてはなりません。\n' +
'(1)法令または公序良俗に違反する行為\n' +
'(2)犯罪行為に関連する行為\n' +
'(3)当チームのサーバーまたはネットワークの機能を破壊したり,妨害したりする行為\n' +
'(4)当チームのサービスの運営を妨害するおそれのある行為\n' +
'(5)他のユーザーに関する個人情報等を収集または蓄積する行為\n' +
'(6)他のユーザーに成りすます行為\n' +
'(7)当チームのサービスに関連して,反社会的勢力に対して直接または間接に利益を供与する行為\n' +
'(8)当チーム,本サービスの他の利用者または第三者の知的財産権,肖像権,プライバシー,名誉その他の権利または利益を侵害する行為\n' +
'(9)過度に暴力的な表現,露骨な性的表現,人種,国籍,信条,性別,社会的身分,門地等による差別につながる表現,自殺,自傷行為,薬物乱用を誘引または助長する表現,その他反社会的な内容を含み他人に不快感を与える表現を,投稿または送信する行為\n' +
'(10)他のお客様に対する嫌がらせや誹謗中傷を目的とする行為,その他本サービスが予定している利用目的と異なる目的で本サービスを利用する行為\n' +
'(11)宗教活動または宗教団体への勧誘行為\n' +
'(12)その他,当チームが不適切と判断する行為\n' +
'(13) Discord利用規約に違反する行為\n' +
' (14) discordのinviteを投稿する行為'
).addField(
'第4条(global chatについて)',
'Global Chatでは、次のことをしてはいけません。\n' +
'(1)r18発言をする行為(ただしnsfw指定が必要なカテゴリーは除きます。)\n' +
'(2)r18,r18g画像を投稿する行為\n' +
'(3)他人を煽る行為\n' +
'(4)運営に対して反逆的な態度をとる行為\n' +
'(5)その他、運営が不適切と判断した行為'
).addField(
'第5条(利用制限および登録抹消)',
'当チームは以下の場合等には,事前の通知なく投稿データを削除し,ユーザーに対して本サービスの全部もしくは一部の利用を制限し、またはユーザーとしての登録を抹消することができるものとします。\n' +
'(1)本規約のいずれかの条項に違反した場合\n' +
'(2)当チームからの問い合わせその他の回答を求める連絡に対して7日間以上応答がない場合\n' +
'(3)その他,当チームが本サービスの利用を適当でないと判断した場合\n' +
'当チームは,当チームの運営行為によりユーザーに生じたいかなる損害についても、一切の責任を免責されるものとします。\n' +
'また、ユーザー様同士のトラブルにつきましては、自己責任による当事者同士の解決を基本とし、当チームは一切の責任を免責されるものとします。'
).addField(
'利用規約への同意について',
'本サービスを使用している時点で、利用規約に同意したこととなります。'
).addField('公式サーバー', 'https://discord.gg/fVsAjm9')
.addField('BOT招待', 'https://discordapp.com/api/oauth2/authorize?client_id=437917527289364500&permissions=671410193&scope=bot');
function saveBanMembers(_list) {
fs.writeFileSync('ban.txt', _list.join(','));
}
function loadBanMembers() {
try {
return fs.readFileSync('ban.txt', 'utf8').split(',');
} catch (ex) {
// Log exception
return [];
}
}
function saveChannelWebhook(_dict) {
fs.writeFileSync('channels.json', JSON.stringify(_dict));
}
function loadChannelWebhook() {
try {
return JSON.parse(fs.readFileSync('channels.json', 'utf8'));
} catch (ex) {
// Log exception
return {'global-chat': {}, 'global-r18': {}};
}
}
class MyClient extends Discord.Client {
constructor(options) {
super(options);
this.webhooks = loadChannelWebhook();
this.bans = loadBanMembers();
this.sqlManager = new SQLManager(this);
this.channelsConnected = {};
this.connecting = 0;
this.debug = [];
this.checking = [];
for (const [key, value] of Object.entries(this.webhooks)) {
const values = Object.keys(value);
this.connecting += values.length;
for (const k of values) {
this.channels[k] = key;
}
}
this.on('ready', this.onReady);
this.on('message', this.onMessage);
}
async limitBan(message, times, reason) {
this.bans.push(message.author.id);
await message.channel.send(`<@${message.author.id}>, あなたは${reason}ため、制限時間付きbanを受けました。制限時間は${times}分です。`);
const user = await this.fetchUser('212513828641046529');
await user.send(`<@${message.author.id}>(${message.author.username},${message.author.id})は${reason}ため、制限時間付きbanを受けました。制限時間は${times}分です。`);
await sleep(times * 60 * 1000);
this.bans.pop(message.author.id);
}
async setPref() {
await this.user.setPresence({game: {name: `>help | ${this.connecting} channels`}});
}
async onReady() {
await this.setPref();
await this.sendGlobalNotice({text: 'すみどらちゃんが起動しました。', title: '起動告知'});
}
end() {
saveChannelWebhook(this.webhooks);
saveBanMembers(this.bans);
}
async convertMessage(message, embed, content = '') {
// returns: return {content: content, embed: embed, settings: settings};
const settings = {};
if (replyCompile.test(content)) {
const _id = replyCompile.exec(content)[1],
m = await this.sqlManager.getMessageFromId(_id);
if (!m) return {content: content, embed: embed, settings: settings};
if (!embed) embed = new Discord.RichEmbed();
settings['reply'] = m;
content = content.replace(`:>${_id}`, '`Reply`');
embed.addField('reply from', m.content)
.setAuthor(m.author.username, m.author.displayAvatarURL)
.setTimestamp(m.createdAt);
}
if (quoteComplie.test(content)) {
const _id = quoteComplie.exec(content)[1],
m = await this.sqlManager.getMessageFromId(_id);
if (!m) return {content: content, embed: embed, settings: settings};
if (!embed) embed = new Discord.RichEmbed();
content = content.replace(`::>${_id}`, '`Quote`');
embed.addField('quote from', m.content)
.setAuthor(m.author.username, m.author.displayAvatarURL)
.setTimestamp(m.createdAt);
}
return {content: content, embed: embed, settings: settings};
}
async sendGlobalMessage(message, name) {
const channel = message.channel,
author = message.author,
messageIdList = [message.id],
channelIdList = [message.channel.id];
let content = message.cleanContent,
settings = {};
if (inviteCompile.test(message.content)) {
process.nextTick(this.limitBan.bind(this), message, 60, '招待を送信しようとした');
return;
}
if (message.mentions.everyone) {
process.nextTick(this.limitBan.bind(this), message, 60, 'everyoneメンションを送信しようとした');
return;
}
if (message.content.length > 1000) {
process.nextTick(this.limitBan.bind(this), message, 60, '1000文字以上の文字を送信しようとした');
return;
}
let cat = '',
embed;
if (message.attachments && message.attachments.size > 0) {
embed = new Discord.RichEmbed().setImage(message.attachments.first().url);
} else {
embed = null;
}
for (const [key_, value] of Object.entries(this.webhooks)) {
for (const [k, v] of Object.entries(value)) {
if (k == channel.id) {
cat = key_;
break;
}
}
}
// Extensions
if (!content.startsWith('*')) {
({content, embed, settings} = await this.convertMessage(message, embed, content));
} else {
content = content.substring(1);
}
for (const [_key, value] of Object.entries(this.webhooks[cat])) {
if (message.channel.id == _key) continue;
const send = async (webhookUrl, _content, key) => {
try {
const webhook = await this._webhookFromUrl(webhookUrl);
if ('reply' in settings) {
if (key == settings['reply'].channel.id) {
_content = `<@${settings['reply'].author.id}>\n` + _content;
} else {
_content = `@${settings['reply'].author.username}\n` + _content;
}
}
const result = await webhook.send(
_content,
{
username: author.username,
avatarURL: author.displayAvatarURL,
embeds: embed !== null ? [embed] : null,
}
);
messageIdList.push(result.id);
channelIdList.push(key);
} catch (ex) {
return;
}
};
process.nextTick(send.bind(this), value, content, _key);
}
await sleep(2 * 1000);
await this.sqlManager.save(message, channelIdList, messageIdList, content);
if (this.checking.includes(message.guild.id)) {
process.nextTick(this.sendingCheck.bind(this), message);
}
for (const [_key, value] of Object.entries(this.webhooks[cat])) {
const ch = this.channels.get(_key);
if (!ch) continue;
if (this.debug.includes(ch.guild.id)) {
const embed =
new Discord.RichEmbed()
.setTitle('DEBUG')
.setDescription(content)
.setTimestamp(message.createdAt)
.setAuthor(message.author.username, message.author.displayAvatarURL)
.setFooter(message.guild.name, message.guild.iconURL);
await ch.send(embed);
}
}
}
async sendGlobalNotice(options) {
const {name = 'global-chat', text = '```\n```', title = 'お知らせ', mode = 'normal'} = options;
let embed;
if (mode === 'normal') {
embed =
new Discord.RichEmbed()
.setTitle(title)
.setDescription(text)
.setColor(0x00bfff);
} else if (mode === 'error') {
embed =
new Discord.RichEmbed()
.setTitle(title || 'エラー')
.setDescription(text)
.setColor(0xff0000);
} else if (mode === 'update') {
embed =
new Discord.RichEmbed()
.setTitle(title || 'アップデート')
.setDescription(text)
.setColor(0x00ff00);
for (const value of options['_list']) {
for (let x = 1; x < options['_list'].length; x++) {
embed.addField(x, value);
}
}
}
for (const [channel, webhooks] of Object.entries(this.webhooks)) {
if (channel !== name) continue;
for (const [_id, webhook] of Object.entries(webhooks)) {
const send = async webhookUrl => {
try {
const webhook = await this._webhookFromUrl(webhookUrl);
await webhook.send(
{
username: this.user.username,
avatarURL: this.user.displayAvatarURL,
embeds: [embed],
}
);
} catch (ex) {
console.error(ex);
return;
}
};
process.nextTick(send.bind(this), webhook);
}
}
return;
}
async sendingCheck(message) {
await message.react(String.fromCodePoint(0x0001f44c))
.then(async r => {
await sleep(2 * 1000);
r.remove();
});
}
userCheck(message) {
if (message.author.id === '212513828641<PASSWORD>') return 0;
if (message.guild.ownerID === message.author.id) return 1;
if (message.member.hasPermission(Discord.Permissions.FLAGS.MANAGE_CHANNELS)) return 2;
return 3;
}
async addChannelGlobal(channel, guild, name = 'global-chat') {
let webhook;
try {
const webhooks = await channel.fetchWebhooks();
if (webhooks && webhooks.size > 0) webhook = webhooks.first();
else webhook = await channel.createWebhook('global-chat');
} catch (ex) {
console.error(ex);
try {
await channel.send('webhookの権限がありません!');
} catch (ex) {
void 0;
}
return;
}
this.webhooks[name][channel.id] = `https://discordapp.com/api/webhooks/${webhook.id}/${webhook.token}`;
this.channels[channel.id] = name;
process.nextTick(this.sendGlobalNotice.bind(this), {name: name, text: `${guild.name}がコネクトしました`});
this.connecting += 1;
await this.setPref();
}
getMemberIdFromName(name) {
return this.users.findKey('username', name);
}
async onMessage(message) {
if (message.author.id === '<PASSWORD>') void 0;
if (this.bans.includes(message.author.id)) return;
if (message.author.bot) return;
if (message.content.startsWith('>')) {
await this.command(message);
return;
}
if (message.channel.id in this.channels) {
await this.sendGlobalMessage(message, this.channels[message.channel.id]);
}
}
async command(message) {
let command,
args;
try {
args = message.content.split(' ');
command = args.shift();
} catch (ex) {
command = message.content;
args = [];
}
if (command === '>connect') {
if (!(this.userCheck(message) <= 2)) return;
if (message.channel.id in this.channels) return;
if (!args || args.length === 0) {
process.nextTick(this.addChannelGlobal.bind(this), message.channel, message.guild, 'global-chat');
} else {
if (args[0] === 'global-r18') {
if (!message.channel.nsfw) {
await message.channel.send('NSFW指定をしてください。');
return;
}
process.nextTick(this.addChannelGlobal.bind(this), message.channel, message.guild, 'global-r18');
} else if (args[0] in this.webhooks) {
process.nextTick(this.addChannelGlobal.bind(this), message.channel, message.guild, args[0]);
}
}
} else if (command === '>disconnect') {
if (!(this.userCheck(message) <= 2)) return;
let category = false;
for (const [key, value] of Object.entries(this.webhooks)) {
if (message.channel.id in value) {
category = key;
break;
}
}
if (!category) return;
delete this.webhooks[category][message.channel.id];
delete this.channels[message.channel.id];
this.connecting -=1;
await message.channel.send('接続解除しました。');
} else if (command === '>s') {
let channelId,
messageId;
try {
({first: channelId, second: messageId} = await this.sqlManager.getMessageIds(args[0]));
if (!channelId) return;
} catch (ex) {
await message.channel.send('なし');
return;
}
const channel = this.channels.get(channelId),
_message = await channel.fetchMessage(messageId),
embed = new Discord.RichEmbed()
.setTitle(`id:${args[0]}のデータ`)
.setDescription(_message.content)
.setColor(0x00bfff)
.setTimestamp(_message.createdAt)
.setAuthor(_message.author.username, _message.author.displayAvatarURL)
.setFooter(_message.guild.name, _message.guild.iconURL);
await message.channel.send(embed);
} else if (command === '>del') {
if (this.userCheck(message) !== 0) return;
if (!args || args.length === 0) return;
const _id = this.getMemberIdFromName(args[0]),
messages = await this.sqlManager.getMessages(_id);
for (const m of messages) {
try {
await m.delete();
} catch (ex) {
void 0;
}
}
} else if (command === '>get') {
if (!args || args.length === 0) return;
const _id = this.getMemberIdFromName(args[0]);
if (!_id) {
await message.channel.send('なし');
return;
}
await message.channel.send(_id);
} else if (command === '>ban') {
if (this.userCheck(message) !== 0) return;
if (!args || args.length === 0) return;
let _id;
if (Number.isNaN(Number.parseInt(args[0]))) {
_id = this.getMemberIdFromName(args[0]);
} else {
_id = args[0];
}
this.bans.push(_id);
await message.channel.send('追加しました');
} else if (command === '>unban') {
console.log(this.bans);
if (this.userCheck(message) !== 0) return;
if (!args || args.length === 0) return;
let _id;
if (Number.isNaN(Number.parseInt(args[0]))) {
_id = this.getMemberIdFromName(args[0]);
} else {
_id = args[0];
}
if (!this.bans.includes(_id)) {
await message.channel.send('いません');
return;
}
this.bans = this.bans.filter(uid => uid !== _id);
await message.channel.send('削除しました');
} else if (command === '>banlist') {
if (this.userCheck(message) !== 0) return;
let text = '```\n';
for (const _id of this.bans) {
if (!_id) continue;
const u = await this.fetchUser(_id);
text += `${u.username}(${u.id})\n`;
}
text += '```';
await message.channel.send(text);
} else if (command === '>notice') {
const desc = args.shift();
await this.sendGlobalNotice({
text: desc,
mode: 'update',
name: '更新情報',
_list: args,
});
} else if (command === '>debug') {
if (!(this.userCheck(message) <= 2)) return;
if (this.debug.includes(message.guild.id)) {
this.debug = this.debug.filter(gid => gid !== message.guild.id);
await message.channel.send('デバッグ機能をオフにしました。');
return;
}
this.debug.push(message.guild.id);
await message.channel.send('デバッグ機能をオンにしました。');
} else if (command === '>checking') {
if (!(this.userCheck(message) <= 2)) return;
if (this.checking.includes(message.guild.id)) {
this.checking = this.checking.filter(gid => gid !== message.guild.id);
await message.channel.send('送信チェック機能をオフにしました。');
return;
}
this.checking.push(message.guild.id);
await message.channel.send('送信チェック機能をオンにしました。');
} else if (command === '>help') {
const embed =
new Discord.RichEmbed()
.setTitle(`Global Chat ${v} for Discord`)
.setDescription('製作者: すみどら#8923')
.setColor(0x00ff00)
.addField('>tos', 'Terms of service(利用規約)をDMに送信します。', false)
.addField('>get [ユーザー名]', '名前からユーザーidを取得します。', false)
.addField('>s [メッセージid]', 'global chatに送信されたメッセージを取得します。', false)
.addField('>connect', 'コネクトします。チャンネル管理の権限が必要です。', false)
.addField('>connect [カテゴリーネーム]', '指定したカテゴリーのチャンネルにコネクトします。チャンネル管理の権限が必要です。\nカテゴリーは追加次第お知らせします。', false)
.addField('>disconnect', 'コネクト解除します。チャンネル管理の権限が必要です。', false)
.addField('>debug', 'デバッグ機能をオンにします。もう一度実行するとオフになります。チャンネル管理の権限が必要です。', false)
.addField('>checking', '送信チェック機能をオンにします。もう一度実行するとオフになります。チャンネル管理の権限が必要です。', false)
.addField('>adminhelp', 'for すみどら', false);
await message.channel.send(embed);
} else if (command === '>adminhelp') {
const embed =
new Discord.RichEmbed()
.setTitle(`Global Chat ${v} for Discord`)
.setDescription('製作者: すみどら#8923')
.setColor(0xff0000)
.addField('>ban [ユーザーネーム or id]', '無期限banします。', false)
.addField('>unban [ユーザーネーム or id]', 'banを解除します。', false)
.addField('>banlist', 'banされているユーザーを表示します。', false)
.addField('>notice [description] <args>', 'おしらせします。', false);
await message.channel.send(embed);
} else if (command === '>tos') {
try {
await message.author.send(contractE);
} catch (ex) {
void 0;
}
} else if (command === '>die') {
this.destroy();
}
}
destroy() {
saveChannelWebhook(this.webhooks);
saveBanMembers(this.bans);
return super.destroy();
}
_webhookFromUrl(url) {
const idReExp = /discordapp.com\/api\/webhooks\/(\d+)/.exec(url);
if (!idReExp || !idReExp[1]) return;
return this.fetchWebhook(idReExp[1]);
}
}
const client = new MyClient();
client.login(process.argv.pop());
|
package org.springaop.chapter.two.advice;
import java.lang.reflect.Method;
import java.util.logging.Logger;
import org.springframework.aop.AfterReturningAdvice;
public class AfterAdvice implements AfterReturningAdvice {
public void afterReturning(Object returnValue, Method m, Object[] args, Object target) {
logger.fine(traceResultInvocation(m, args, target, returnValue));
}
private String traceResultInvocation(Method m, Object[] args, Object target, Object returnValue) {
StringBuilder sb = new StringBuilder("Invoked method :").append(m.getName());
sb.append("with args :").append(args);
sb.append("on object :").append(target);
sb.append("return value :").append(returnValue);
return sb.toString();
}
private Logger logger;
}
|
<reponame>fiesta-iot/in-house-dynamic-discovery<gh_stars>0
var globals = require('./globals.js');
module.exports = {
resources_endpoint : globals.config.iot_registry + '/resources',
observations_endpoint : globals.config.iot_registry + '/observations',
sparql_execute_endpoint: globals.config.iot_registry + '/queries/execute/resources',
sparql_execute_endpoint_global: globals.config.iot_registry + '/queries/execute/global',
// openam_authentication_endpoint: 'https://platform.fiesta-iot.eu/openam/json/authenticate',
// openam_authentication_endpoint: 'https://platform.fiesta-iot.eu/openam/json/authenticate',
};
|
#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
trap "exit" INT
# Removes CSS imports
# Reason: Next.js forbids CSS imports outside `_app.js`.
sed -i.bak '/import "\.\.\/\.\.\/css\/awesomplete\.css";/d' node_modules/auspice/src/components/controls/search.js
sed -i.bak '/import "\.\.\/\.\.\/css\/entropy\.css";/d' node_modules/auspice/src/components/entropy/index.js
# Removes requires for '@extensions' modules from `extensions.js`
# Reason: We don't use extensions and don't want to setup webpack aliases for that.
sed -i.bak '/.*@extensions.*/d' node_modules/auspice/src/util/extensions.js
# Removes references to `window`
# Reason: Next.js prerendering step is performed server-side and does not have access to `window` global
sed -i.bak 's/sidebarOpen: window.innerWidth > controlsHiddenWidth,/sidebarOpen: true,/g' node_modules/auspice/src/reducers/controls.js
sed -i.bak 's/if (window.location.pathname.includes("gisaid")) {/if (false) {/g' node_modules/auspice/src/reducers/controls.js
sed -i.bak 's/width: window.innerWidth,/width: 0,/g' node_modules/auspice/src/reducers/browserDimensions.js
sed -i.bak 's/height: window.innerHeight,/height: 0,/g' node_modules/auspice/src/reducers/browserDimensions.js
sed -i.bak 's/docHeight: window.document.body.clientHeight/docHeight: 0,/g' node_modules/auspice/src/reducers/browserDimensions.js
# Removes warning when `geoResolutions` is undefined in input data
# Reason: We don't use geo resolutions and this warning is irrelevant for our application
sed -i.bak '/console.warn("JSONs did not include `geoResolutions`");/d' node_modules/auspice/src/actions/recomputeReduxState.js
|
def classify_vowels_consonants(string):
vowels = []
consonants = []
for char in string:
if char.lower() in "aeiou":
vowels.append(char)
else:
consonants.append(char)
return vowels, consonants |
import React, { useState } from "react"
import { css } from "@emotion/core"
import { Link } from "gatsby"
import Img from "gatsby-image"
import { colors } from "../utils/colors"
import useMenu from "../utils/useMenu"
import Headroom from "react-headroom"
import Logo from "../images/logo.inline.svg"
import Hamburger from "./hamburger"
const Header = () => {
const { prismicMenu } = useMenu()
const [currentIndex, setCurrentIndex] = useState(0)
const [showMegamenu, setShowMegamenu] = useState(false)
const [timer, setTimer] = useState(null)
const [menuOpened, setMenuOpened] = useState(false)
return (
<Headroom
css={css`
.headroom--pinned header {
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}
`}
>
<header
css={css`
padding-top: 3rem;
padding-bottom: 1.5rem;
background-color: ${colors.lightgray};
position: relative;
z-index: 1200;
.menu {
.logo {
width: 54px;
height: auto;
.complete-a {
opacity: 0;
transition: all 0.3s ease-in-out;
}
.dot {
transition: all 0.3s ease-in-out;
}
&:hover {
.complete-a {
opacity: 1;
}
.dot {
opacity: 0;
}
}
}
nav {
margin-left: auto;
position: fixed;
width: 100%;
height: 100vh;
top: 0;
left: 0;
z-index: 1200;
background-color: #fff;
display: flex;
justify-content: center;
transform: translateX(-100%);
transition: all 0.3s ease-in-out;
font-size: 1.2rem;
.mobile-wa {
margin-bottom: 4rem;
text-align: center;
}
&.is-opened {
transform: translateX(0);
}
@media (min-width: 768px) {
position: relative;
width: auto;
height: auto;
transform: translateX(0);
background-color: transparent;
font-size: 1rem;
.mobile-wa {
display: none;
}
}
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
@media (min-width: 768px) {
flex-direction: row;
}
li {
margin-bottom: 2rem;
&:first-of-type,
&:last-of-type {
margin-top: auto;
}
@media (min-width: 768px) {
margin-left: 2.5rem;
margin-bottom: 0;
}
a {
display: block;
color: #000000;
position: relative;
letter-spacing: 0.1rem;
&:before,
&:after {
content: "";
display: block;
position: absolute;
margin: auto;
opacity: 0;
pointer-events: none;
transition: all 0.3s ease-in-out;
}
&:after {
width: 100%;
height: 2px;
background-color: ${colors.lightgray};
bottom: 0;
top: 0;
left: 0;
right: 0;
}
&:before {
width: 6px;
height: 6px;
border-radius: 50%;
background-color: #000000;
top: 0;
bottom: 0;
left: -8px;
}
&:hover,
&.active {
&:before,
&:after {
opacity: 1;
}
}
}
}
}
}
.megamenu {
position: absolute;
left: 0;
bottom: 0;
width: 100%;
padding-top: 1.5rem;
padding-bottom: 3rem;
transform: translateY(95%);
background: ${colors.lightgray};
opacity: 0;
transition: all 0.3s ease-in-out;
pointer-events: none;
box-shadow: 0 20px 20px -20px rgba(0, 0, 0, 0.1);
display: none;
@media (min-width: 992px) {
display: block;
}
&.show {
opacity: 1;
transform: translateY(100%);
bottom: 1px;
pointer-events: all;
}
&__item {
margin: auto;
display: none;
@media (min-width: 768px) {
max-width: 85%;
}
@media (min-width: 1200px) {
max-width: 100%;
}
&.visible {
display: flex;
}
& > div {
&:nth-of-type(1) {
width: 45%;
flex: 0 0 45%;
}
&:nth-of-type(2) {
width: 40%;
flex: 0 0 40%;
margin-left: auto;
}
}
}
}
.megamenu-content {
line-height: 2;
display: flex;
flex-direction: column;
& > div {
margin-top: auto;
a {
color: inherit;
}
}
}
`}
>
<div className="menu">
<div className="container d-flex items-center">
<Link to="/">
<Logo className="logo" />
</Link>
<Hamburger menuOpened={menuOpened} setMenuOpened={setMenuOpened} />
<nav className={menuOpened ? "is-opened" : ""}>
<ul>
{prismicMenu.data.menu_item.map((item, index) => (
<li
key={`menu-item-${prismicMenu.id}-${index}`}
onMouseEnter={() => {
clearTimeout(timer)
setShowMegamenu(true)
setCurrentIndex(index)
}}
onMouseLeave={() => {
setTimer(
setTimeout(function () {
setShowMegamenu(false)
}, 500)
)
}}
>
{item.external ? (
<a href={item.link.text} target="_blank">
{item.titulo.text}
</a>
) : (
<Link to={item.link.text} activeClassName="active">
{item.titulo.text}
</Link>
)}
</li>
))}
<li className="mobile-wa">
<a href="https://wa.me/+524426084124" target="_blank">
Teléfono: <br />
442 608 4124
</a>
</li>
</ul>
</nav>
</div>
</div>
<div
className={`megamenu${showMegamenu ? " show" : ""}`}
onMouseEnter={() => {
clearTimeout(timer)
setShowMegamenu(true)
}}
onMouseLeave={() => {
setTimer(
setTimeout(function () {
setShowMegamenu(false)
}, 500)
)
}}
>
<div className="container">
{prismicMenu.data.menu_item.map((item, index) => (
<div
key={`megamenu-${prismicMenu.id}-${index}`}
className={`megamenu__item${
currentIndex === index ? " visible" : ""
}`}
>
<div className="megamenu-content">
<h3>{item.titulo.text}</h3>
{item.content.text}
<div>
<a href="https://wa.me/+524426084124" target="_blank">
Teléfono: 442 608 4124
</a>
</div>
</div>
<div>
<Img fluid={item.image.fluid} />
</div>
</div>
))}
</div>
</div>
</header>
</Headroom>
)
}
export default Header
// import { Link } from "gatsby"
// import PropTypes from "prop-types"
// import React from "react"
// const Header = ({ siteTitle }) => (
// <header
// style={{
// background: `rebeccapurple`,
// marginBottom: `1.45rem`,
// }}
// >
// <div
// style={{
// margin: `0 auto`,
// maxWidth: 960,
// padding: `1.45rem 1.0875rem`,
// }}
// >
// <h1 style={{ margin: 0 }}>
// <Link
// to="/"
// style={{
// color: `white`,
// textDecoration: `none`,
// }}
// >
// {siteTitle}
// </Link>
// </h1>
// </div>
// </header>
// )
// Header.propTypes = {
// siteTitle: PropTypes.string,
// }
// Header.defaultProps = {
// siteTitle: ``,
// }
// export default Header
|
#!/bin/bash
dirs=(./rpc ./fabnet ./logger)
echo "mode: set" > coverage.out
for Dir in ${dirs[*]};
do
if ls $Dir/*.go &> /dev/null;
then
go test -coverprofile=profile.out $Dir
if [ -f profile.out ]
then
cat profile.out | grep -v "mode: set" >> coverage.out
fi
fi
done
rm profile.out
|
from rest_framework import serializers
from Notes.models import Notes
class NoteSerializer(serializers.ModelSerializer):
class Meta:
model = Notes
exclude = ('user',)
def create(self, validated_data):
validated_data['user']=self.context['request'].user
note = Notes.objects.create(**validated_data)
return note
|
<filename>src/main/java/com/changqin/fast/event/EventResult.java
package com.changqin.fast.event;
public interface EventResult {
/**
* get a Event Result until time out value: timeoutForReturnResult
*
* @return
*/
Object get();
/**
* Blocking until get a Event Result
*
* @return
*/
Object getBlockedValue();
void send(Object eventResult);
}
|
package media
import (
"github.com/ungerik/go-start/model"
"github.com/ungerik/go-start/view"
)
func NewBlobRef(blob *Blob) *BlobRef {
blobRef := new(BlobRef)
blobRef.Set(blob)
return blobRef
}
type BlobRef string
func (self *BlobRef) String() string {
return string(*self)
}
func (self *BlobRef) SetString(str string) error {
*self = BlobRef(str)
return nil
}
// Blob loads the referenced blob, or returns nil if the reference is empty.
func (self *BlobRef) Get() (*Blob, error) {
if self.IsEmpty() {
return nil, nil
}
return Config.Backend.LoadBlob(self.String())
}
func (self *BlobRef) TryGet() (*Blob, bool, error) {
if self.IsEmpty() {
return nil, false, nil
}
blob, err := Config.Backend.LoadBlob(self.String())
if _, notFound := err.(ErrNotFound); notFound {
return nil, false, nil
}
return blob, err == nil, err
}
// SetBlob sets the ID of blob, or an empty reference if blob is nil.
func (self *BlobRef) Set(blob *Blob) {
if blob != nil {
self.SetString(blob.ID.String())
} else {
*self = ""
}
}
func (self *BlobRef) IsEmpty() bool {
return *self == ""
}
func (self *BlobRef) Required(metaData *model.MetaData) bool {
return metaData.BoolAttrib(model.StructTagKey, "required")
}
func (self *BlobRef) Validate(metaData *model.MetaData) error {
if self.Required(metaData) && self.IsEmpty() {
return model.NewRequiredError(metaData)
}
return nil
}
func (self *BlobRef) FileURL() (view.URL, error) {
blob, err := self.Get()
if err != nil {
return nil, err
}
return blob.FileURL(), nil
}
func (self *BlobRef) FileLink(class string) (*view.Link, error) {
blob, err := self.Get()
if err != nil {
return nil, err
}
return blob.FileLink(class), nil
}
|
<gh_stars>0
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
const SignIn = (props) => {
// hooks
const [user, setUser] = useState({});
// event handlers
const handleChanges = e => {
setUser({...user, [e.target.name]: e.target.value});
};
const handleSubmit = e => {
e.preventDefault();
axios.post('https://dadjokes-be.herokuapp.com/api/auth/login', user)
.then(response => {
console.log(response);
localStorage.setItem('token', response.data.token);
window.location.href='./profile';
})
.catch(error => {
console.log(error);
})
};
return(
<form className="signInDiv" onSubmit={e => handleSubmit(e)}>
<h2>Welcome back</h2>
<input className="default" type='text' placeholder='username or email' name='username' onChange={e => handleChanges(e)} />
<br />
<br />
<input className="default" type='password' placeholder='password' name='password' onChange={e => handleChanges(e)} />
<br />
<br />
<button>sign in</button>
<br />
<br />
<div>Don't have an account? <Link className="linkSignUp" to='/signup'>Sign up now</Link></div>
</form>
)
}
export default SignIn;
|
<filename>src/builder/__tests__/graphql.spec.ts
import buildGraphql from '../graphql';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const mockData = require('./__data__/graphql.json');
// example taken from https://fakerql.com/
describe('graphql', () => {
it('builds from graphql types', () => {
expect(buildGraphql(mockData.data.__schema)).toEqual([
{
name: 'AuthPayload',
properties: {
token: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
}
}
},
{
name: 'Mutation',
properties: {
createTodo: {
exportTypes: undefined,
importTypes: 'Todo',
required: false,
type: 'Todo'
},
login: {
exportTypes: undefined,
importTypes: 'AuthPayload',
required: false,
type: 'AuthPayload'
},
register: {
exportTypes: undefined,
importTypes: 'AuthPayload',
required: false,
type: 'AuthPayload'
},
updateUser: {
exportTypes: undefined,
importTypes: 'User',
required: false,
type: 'User'
}
}
},
{
name: 'Post',
properties: {
author: {
exportTypes: undefined,
importTypes: 'User',
required: true,
type: 'User'
},
body: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
},
createdAt: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
},
id: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
},
published: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'boolean'
},
title: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
}
}
},
{
name: 'Product',
properties: {
id: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
},
name: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
},
price: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
}
}
},
{
name: 'Query',
properties: {
Post: {
exportTypes: undefined,
importTypes: 'Post',
required: false,
type: 'Post'
},
Product: {
exportTypes: undefined,
importTypes: 'Product',
required: false,
type: 'Product'
},
Todo: {
exportTypes: undefined,
importTypes: 'Todo',
required: false,
type: 'Todo'
},
User: {
exportTypes: undefined,
importTypes: 'User',
required: false,
type: 'User'
},
allPosts: {
exportTypes: undefined,
importTypes: 'Post',
required: false,
type: 'Array<Post>'
},
allProducts: {
exportTypes: undefined,
importTypes: 'Product',
required: false,
type: 'Array<Product>'
},
allTodos: {
exportTypes: undefined,
importTypes: 'Todo',
required: false,
type: 'Array<Todo>'
},
allUsers: {
exportTypes: undefined,
importTypes: 'User',
required: false,
type: 'Array<User>'
},
me: {
exportTypes: undefined,
importTypes: 'User',
required: false,
type: 'User'
}
}
},
{
name: 'Subscription',
properties: {
todoAdded: {
exportTypes: undefined,
importTypes: 'Todo',
required: false,
type: 'Todo'
}
}
},
{
name: 'Todo',
properties: {
completed: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'boolean'
},
id: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
},
title: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
}
}
},
{
name: 'User',
properties: {
avatar: {
exportTypes: undefined,
importTypes: undefined,
required: false,
type: 'string'
},
email: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
},
firstName: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
},
id: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
},
lastName: {
exportTypes: undefined,
importTypes: undefined,
required: true,
type: 'string'
}
}
}
]);
});
it('resolves basic propert structure', () => {
const queryType = buildGraphql(mockData.data.__schema).find(
({ name }) => name === 'Query'
);
expect(queryType).toBeTruthy();
if (!queryType) throw new Error('Not an object');
expect(
Object.values(queryType.properties).every((property) => {
if (!(property instanceof Object)) throw new Error('Not an object');
return (
'exportTypes' in property &&
'importTypes' in property &&
'required' in property &&
'type' in property
);
})
).toBeTruthy();
});
});
|
serverName=${1:-test}
serverPort=${2:-27017}
rootUser=${3:-admin}
rootPass=${4:-admin}
mongoVersion=${5:-latest}
containerName=$serverName
echo "MONGO_INITDB_ROOT_USERNAME=$rootUser" > .env
echo "MONGO_INITDB_ROOT_PASSWORD=$rootPass" >> .env
echo "MONGO_VERSION=$mongoVersion" >> .env
echo "CONTAINER_NAME=$containerName" >> .env
echo "CONTAINER_PORT=$serverPort" >> .env
sudo mkdir -p /data/db
sudo docker-compose up -d
sudo docker port $containerName
|
//
// Copyright (C) 2016, <NAME>. <<EMAIL>>
//
#pragma once
#include <pebble.h>
#include "global.h"
#define CLOCK_DIAL_SIZE_W PBL_DISPLAY_WIDTH
#define CLOCK_DIAL_SIZE_H PBL_DISPLAY_HEIGHT
#define CLOCK_DIAL_POS_X 0
#define CLOCK_DIAL_POS_Y 0
#define CLOCK_DIAL_RECT ( GRect( CLOCK_DIAL_POS_X, CLOCK_DIAL_POS_Y, CLOCK_DIAL_SIZE_W, CLOCK_DIAL_SIZE_H ) )
#define CLOCK_TICK_EDGE_OFFSET 3 /* make it an odd number */
static GPathInfo PATH_TICK = {
2, (GPoint []) {
{ 0, - ( CLOCK_DIAL_SIZE_W > CLOCK_DIAL_SIZE_H ? CLOCK_DIAL_SIZE_W : CLOCK_DIAL_SIZE_H ) },
{ 0, ( CLOCK_DIAL_SIZE_W > CLOCK_DIAL_SIZE_H ? CLOCK_DIAL_SIZE_W : CLOCK_DIAL_SIZE_H ) }
}
};
#if PBL_DISPLAY_WIDTH == 200
static GPathInfo HOUR_HAND_SBGE001_POINTS = {
5, (GPoint []) {
{ -3, 20 },
{ -11, 0 },
{ 0, -48 },
{ 11, 0 },
{ 3, 20 }
}
};
static GPathInfo HOUR_HAND_SBGE001_POINTS_HIGHLIGHT = {
4, (GPoint []) {
{ 0, 20 },
{ 3, 20 },
{ 11, 0 },
{ 0, -48 },
}
};
static GPathInfo MINUTE_HAND_SBGE001_POINTS = {
5, (GPoint []) {
{ -3, 20 },
{ -9, 0 },
{ 0, -77 },
{ 9, 0 },
{ 3, 20 }
}
};
static GPathInfo MINUTE_HAND_SBGE001_POINTS_HIGHLIGHT = {
4, (GPoint []) {
{ 0, 20 },
{ -3, 20 },
{ -9, 0 },
{ 0, -77 },
}
};
#else
static GPathInfo HOUR_HAND_SBGE001_POINTS = {
5, (GPoint []) {
{ -3, 14 },
{ -9, 0 },
{ 0, -42 },
{ 9, 0 },
{ 3, 14 }
}
};
static GPathInfo HOUR_HAND_SBGE001_POINTS_HIGHLIGHT = {
4, (GPoint []) {
{ 0, 14 },
{ 3, 14 },
{ 9, 0 },
{ 0, -42 },
}
};
static GPathInfo MINUTE_HAND_SBGE001_POINTS = {
5, (GPoint []) {
{ -3, 14 },
{ -7, 0 },
{ 0, -61 },
{ 7, 0 },
{ 3, 14 }
}
};
static GPathInfo MINUTE_HAND_SBGE001_POINTS_HIGHLIGHT = {
4, (GPoint []) {
{ 0, 14 },
{ -3, 14 },
{ -7, 0 },
{ 0, -61 },
}
};
#endif
#if PBL_DISPLAY_WIDTH == 200
#define SEC_HAND_LENGTH 74
#define SEC_HAND_TAIL_LENGTH 28
#define SEC_HAND_TIP_LENGTH 16
#define SEC_HAND_WIDTH 1
#define SEC_CENTER_DOT_RADIUS 5
#else
#define SEC_HAND_LENGTH 61 /* 55 53 */
#define SEC_HAND_TAIL_LENGTH 23
#define SEC_HAND_TIP_LENGTH 12
#define SEC_HAND_WIDTH 1
#define SEC_CENTER_DOT_RADIUS 4
#endif
void clock_init( Window* window );
void clock_deinit( void );
|
import vaex
def ascii_to_vaex(path: str) -> vaex.dataframe.DataFrame:
return vaex.from_ascii(path) |
use tracing_subscriber::{EnvFilter, prelude::*, fmt::layer};
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let non_blocking = std::io::stdout();
let subscriber = layer()
.with_writer(non_blocking)
.json()
.flatten_event(true);
let subscriber = tracing_subscriber::registry()
.with(EnvFilter::from_default_env())
.with(subscriber);
tracing::subscriber::set_global_default(subscriber)?;
let APP = "YourApp";
let APP_VERSION = "1.0.0";
warn!("Launching {}, version: {}", APP, APP_VERSION);
let nats_key = env::var("NATS_KEY")?;
let authz_cache = redis::create_redis(); // Replace with actual Redis cache creation
app::run(nats_key, authz_cache).await?;
Ok(())
} |
import pandas as pd
from sklearn import linear_model
df = pd.read_csv('input.csv')
X = df[['sq_ft', 'bedrooms', 'neighborhood', 'year_built']]
y = df['price']
lm = linear_model.LinearRegression()
model = lm.fit(X, y)
predictions = lm.predict(X) |
package com.google.daq.mqtt.validator.validations;
public class SkipTest extends RuntimeException {
public SkipTest(String reason) {
super(reason);
}
}
|
<gh_stars>100-1000
module.exports = [{
url: 'http://localhost:3000/#/accordion',
label: 'Accordion',
selectors: [
'[data-backstop="accordion-default"]',
'[data-backstop="accordion-compact"]',
'[data-backstop="accordion-border-aligned"]',
],
}];
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.