text:
package eu.lunisolar.magma.func.function.conversion;

import eu.lunisolar.magma.func.*; // NOSONAR
import javax.annotation.Nonnull; // NOSONAR
import javax.annotation.Nullable; // NOSONAR
import java.util.Objects;// NOSONAR
import eu.lunisolar.magma.basics.meta.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR

import eu.lunisolar.magma.func.action.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR
import eu.lunisolar.magma.func.function.*; // NOSONAR
import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR
import eu.lunisolar.magma.func.function.from.*; // NOSONAR
import eu.lunisolar.magma.func.function.to.*; // NOSONAR
import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR
import eu.lunisolar.magma.func.predicate.*; // NOSONAR
import eu.lunisolar.magma.func.supplier.*; // NOSONAR

import org.testng.Assert;
import org.testng.annotations.*;      //NOSONAR
import java.util.regex.Pattern;          //NOSONAR
import java.text.ParseException;         //NOSONAR
import eu.lunisolar.magma.basics.*; //NOSONAR
import eu.lunisolar.magma.basics.exceptions.*; //NOSONAR
import java.util.concurrent.atomic.AtomicInteger; //NOSONAR
import eu.lunisolar.magma.func.tuple.*; // NOSONAR
import java.util.function.*; // NOSONAR

/** The test obviously concentrate on the interface methods the function it self is very simple.  */
public class LDblToSrtFunctionTest {
    private static final String ORIGINAL_MESSAGE = "Original message";
    private static final String EXCEPTION_WAS_WRAPPED = "Exception was wrapped.";
    private static final String NO_EXCEPTION_WERE_THROWN = "No exception were thrown.";

    private short testValue = (short)100;

    private LDblToSrtFunction sut = new LDblToSrtFunction(){
        public  short applyAsSrtX(double a)  {
            return testValue;
        }
    };

    private LDblToSrtFunction sutAlwaysThrowing = LDblToSrtFunction.dblToSrtFunc(a -> {
            throw new ParseException(ORIGINAL_MESSAGE, 0);
    });

    private LDblToSrtFunction sutAlwaysThrowingUnchecked = LDblToSrtFunction.dblToSrtFunc(a -> {
            throw new IndexOutOfBoundsException(ORIGINAL_MESSAGE);
    });

    @Test
    public void testTheResult() throws Throwable {
         Assert.assertEquals(sut.applyAsSrt(100d), testValue);
    }

    @Test
    public void testTupleCall() throws Throwable {

        LDblSingle domainObject = Tuple4U.dblSingle(100d);

        Object result = sut.tupleApplyAsSrt(domainObject);

            Assert.assertEquals(result, testValue);
    }

    @Test
    public void testNonNullApplyAsSrt() throws Throwable {
            Assert.assertEquals(sut.nonNullApplyAsSrt(100d), testValue);
    }

    @Test
    public void testNestingApplyAsSrtUnchecked() throws Throwable {

        // then
        try {
            sutAlwaysThrowingUnchecked.nestingApplyAsSrt(100d);
            Assert.fail(NO_EXCEPTION_WERE_THROWN);
        } catch (Exception e) {
            Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class);
            Assert.assertNull(e.getCause());
            Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE);
        }
    }

    @Test
    public void testShovingApplyAsSrtUnchecked() throws Throwable {

        // then
        try {
            sutAlwaysThrowingUnchecked.shovingApplyAsSrt(100d);
            Assert.fail(NO_EXCEPTION_WERE_THROWN);
        } catch (Exception e) {
            Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class);
            Assert.assertNull(e.getCause());
            Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE);
        }
    }

    @Test
    public void testFunctionalInterfaceDescription() throws Throwable {
        Assert.assertEquals(sut.functionalInterfaceDescription(), "LDblToSrtFunction: short applyAsSrt(double a)");
    }

    @Test
    public void testDblToSrtFuncMethod() throws Throwable {
        Assert.assertTrue(LDblToSrtFunction.dblToSrtFunc(a -> testValue ) instanceof LDblToSrtFunction);

    }

    // <editor-fold desc="compose (functional)">

    @Test
    public void testCompose() throws Throwable {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final AtomicInteger beforeCalls = new AtomicInteger(0);

        //given (+ some assertions)
        LDblToSrtFunction sutO = a -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a, (Object) 90d);
                return (short)100;
        };

        LDblUnaryOperator before = p0 -> {
            Assert.assertEquals(p0, (Object) 80d);
            beforeCalls.incrementAndGet();
            return 90d;
        };

        //when
        LDblToSrtFunction function = sutO.compose(before);
        function.applyAsSrt(80d);

        //then - finals
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertEquals(beforeCalls.get(), 1);
    }

    @Test
    public void testUnboxingCompose() throws Throwable {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final AtomicInteger beforeCalls = new AtomicInteger(0);

        //given (+ some assertions)
        LDblToSrtFunction sutO = a -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a, (Object) 90d);
                return (short)100;
        };

        LToDblFunction<Integer> before = p0 -> {
            Assert.assertEquals(p0, (Object) 80);
            beforeCalls.incrementAndGet();
            return 90d;
        };

        //when
        LToSrtFunction<Integer> function = sutO.unboxingCompose(before);
        function.applyAsSrt(80);

        //then - finals
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertEquals(beforeCalls.get(), 1);
    }

    // </editor-fold>

    // <editor-fold desc="then (functional)">

    @Test
    public void testThen0() throws Throwable  {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);

        //given (+ some assertions)
        LDblToSrtFunction sutO = a -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a, (Object) 80d);
                return (short)90;
        };

        LSrtFunction<Integer> thenFunction = p -> {
                thenFunctionCalled.set(true);
                // short
                Assert.assertEquals(p, (Object) (short)90);
                // Integer
                return 100;
        };

        //when
        LDblFunction<Integer> function = sutO.then(thenFunction);
        Integer finalValue = function.apply(80d);

        //then - finals
        Assert.assertEquals(finalValue, (Object) 100);
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertTrue(thenFunctionCalled.get());

    }

    @Test
    public void testThenToByte1() throws Throwable  {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);

        //given (+ some assertions)
        LDblToSrtFunction sutO = a -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a, (Object) 80d);
                return (short)90;
        };

        LSrtToByteFunction thenFunction = p -> {
                thenFunctionCalled.set(true);
                // short
                Assert.assertEquals(p, (Object) (short)90);
                // byte
                return (byte)100;
        };

        //when
        LDblToByteFunction function = sutO.thenToByte(thenFunction);
        byte finalValue = function.applyAsByte(80d);

        //then - finals
        Assert.assertEquals(finalValue, (Object) (byte)100);
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertTrue(thenFunctionCalled.get());

    }

    @Test
    public void testThenToSrt2() throws Throwable  {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);

        //given (+ some assertions)
        LDblToSrtFunction sutO = a -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a, (Object) 80d);
                return (short)90;
        };

        LSrtUnaryOperator thenFunction = p -> {
                thenFunctionCalled.set(true);
                // short
                Assert.assertEquals(p, (Object) (short)90);
                // short
                return (short)100;
        };

        //when
        LDblToSrtFunction function = sutO.thenToSrt(thenFunction);
        short finalValue = function.applyAsSrt(80d);

        //then - finals
        Assert.assertEquals(finalValue, (Object) (short)100);
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertTrue(thenFunctionCalled.get());

    }

    @Test
    public void testThenToInt3() throws Throwable  {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);

        //given (+ some assertions)
        LDblToSrtFunction sutO = a -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a, (Object) 80d);
                return (short)90;
        };

        LSrtToIntFunction thenFunction = p -> {
                thenFunctionCalled.set(true);
                // short
                Assert.assertEquals(p, (Object) (short)90);
                // int
                return 100;
        };

        //when
        LDblToIntFunction function = sutO.thenToInt(thenFunction);
        int finalValue = function.applyAsInt(80d);

        //then - finals
        Assert.assertEquals(finalValue, (Object) 100);
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertTrue(thenFunctionCalled.get());

    }

    @Test
    public void testThenToLong4() throws Throwable  {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);

        //given (+ some assertions)
        LDblToSrtFunction sutO = a -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a, (Object) 80d);
                return (short)90;
        };

        LSrtToLongFunction thenFunction = p -> {
                thenFunctionCalled.set(true);
                // short
                Assert.assertEquals(p, (Object) (short)90);
                // long
                return 100L;
        };

        //when
        LDblToLongFunction function = sutO.thenToLong(thenFunction);
        long finalValue = function.applyAsLong(80d);

        //then - finals
        Assert.assertEquals(finalValue, (Object) 100L);
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertTrue(thenFunctionCalled.get());

    }

    @Test
    public void testThenToFlt5() throws Throwable  {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);

        //given (+ some assertions)
        LDblToSrtFunction sutO = a -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a, (Object) 80d);
                return (short)90;
        };

        LSrtToFltFunction thenFunction = p -> {
                thenFunctionCalled.set(true);
                // short
                Assert.assertEquals(p, (Object) (short)90);
                // float
                return 100f;
        };

        //when
        LDblToFltFunction function = sutO.thenToFlt(thenFunction);
        float finalValue = function.applyAsFlt(80d);

        //then - finals
        Assert.assertEquals(finalValue, (Object) 100f);
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertTrue(thenFunctionCalled.get());

    }

    @Test
    public void testThenToDbl6() throws Throwable  {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);

        //given (+ some assertions)
        LDblToSrtFunction sutO = a -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a, (Object) 80d);
                return (short)90;
        };

        LSrtToDblFunction thenFunction = p -> {
                thenFunctionCalled.set(true);
                // short
                Assert.assertEquals(p, (Object) (short)90);
                // double
                return 100d;
        };

        //when
        LDblUnaryOperator function = sutO.thenToDbl(thenFunction);
        double finalValue = function.applyAsDbl(80d);

        //then - finals
        Assert.assertEquals(finalValue, (Object) 100d);
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertTrue(thenFunctionCalled.get());

    }

    @Test
    public void testThenToChar7() throws Throwable  {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);

        //given (+ some assertions)
        LDblToSrtFunction sutO = a -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a, (Object) 80d);
                return (short)90;
        };

        LSrtToCharFunction thenFunction = p -> {
                thenFunctionCalled.set(true);
                // short
                Assert.assertEquals(p, (Object) (short)90);
                // char
                return '\u0100';
        };

        //when
        LDblToCharFunction function = sutO.thenToChar(thenFunction);
        char finalValue = function.applyAsChar(80d);

        //then - finals
        Assert.assertEquals(finalValue, (Object) '\u0100');
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertTrue(thenFunctionCalled.get());

    }

    @Test
    public void testThenToBool8() throws Throwable  {

        final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
        final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);

        //given (+ some assertions)
        LDblToSrtFunction sutO = a -> {
                mainFunctionCalled.set(true);
                Assert.assertEquals(a, (Object) 80d);
                return (short)90;
        };

        LSrtPredicate thenFunction = p -> {
                thenFunctionCalled.set(true);
                // short
                Assert.assertEquals(p, (Object) (short)90);
                // boolean
                return true;
        };

        //when
        LDblPredicate function = sutO.thenToBool(thenFunction);
        boolean finalValue = function.test(80d);

        //then - finals
        Assert.assertEquals(finalValue, (Object) true);
        Assert.assertTrue(mainFunctionCalled.get());
        Assert.assertTrue(thenFunctionCalled.get());

    }

    // </editor-fold>

    @Test(expectedExceptions = RuntimeException.class)
    public void testShove() {

        // given
        LDblToSrtFunction sutThrowing = LDblToSrtFunction.dblToSrtFunc(a -> {
            throw new UnsupportedOperationException();
        });

        // when
        sutThrowing.shovingApplyAsSrt(100d);
    }

    @Test
    public void testToString() throws Throwable {

        Assert.assertTrue(sut.toString().startsWith(this.getClass().getName()+"$"));

        Assert.assertTrue(String.format("%s", sut).contains("LDblToSrtFunction: short applyAsSrt(double a)"));

    }

    @Test
    public void isThrowing() {

        Assert.assertFalse(sut.isThrowing());
    }

}


text:
/**
 * \file
 *
 * This file contains functions to enable named views that can hold local zone
 * authority service.
 */

#ifndef SERVICES_VIEW_H
#define SERVICES_VIEW_H
#include "util/rbtree.h"
#include "util/locks.h"
struct regional;
struct config_file;
struct config_view;

/**
 * Views storage, shared.
 */
struct views {
	/** lock on the view tree */
	lock_rw_t lock;
	/** rbtree of struct view */
	rbtree_t vtree;
};

/**
 * View. Named structure holding local authority zones.
 */
struct view {
	/** rbtree node, key is name */
	rbnode_t node;
	/** view name.
	 * Has to be right after rbnode_t due to pointer arithmatic in
	 * view_create's lock protect */
	char* name;
	/** view specific local authority zones */
	struct local_zones* local_zones;
	/** Fallback to global local_zones when there is no match in the view
	 * specific tree. 1 for yes, 0 for no */
	int isfirst;
	/** lock on the data in the structure
	 * For the node and name you
	 * need to also hold the views_tree lock to change them (or to
	 * delete this view) */
	lock_rw_t lock;
};

/**
 * Create views storage
 * @return new struct or NULL on error.
 */
struct views* views_create(void);

/**
 * Delete views storage
 * @param v: views to delete.
 */
void views_delete(struct views* v);

/**
 * Apply config settings;
 * Takes care of locking.
 * @param v: view is set up.
 * @param cfg: config data.
 * @return false on error.
 */
int views_apply_cfg(struct views* v, struct config_file* cfg);

/**
 * Compare two view entries in rbtree. Sort canonical.
 * @param v1: view 1
 * @param v2: view 2
 * @return: negative, positive or 0 comparison value.
 */
int view_cmp(const void* v1, const void* v2);

/**
 * Delete one view
 * @param v: view to delete.
 */
void view_delete(struct view* v);

/**
 * Debug helper. Print all views
 * Takes care of locking.
 * @param v: the views tree
 */
void views_print(struct views* v);

/* Find a view by name.
 * @param vs: views
 * @param name: name of the view we are looking for
 * @param write: 1 for obtaining write lock on found view, 0 for read lock
 * @return: locked view or NULL.
 */
struct view* views_find_view(struct views* vs, const char* name, int write);

#endif /* SERVICES_VIEW_H */

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.selection;

import org.chromium.base.Callback;
import org.chromium.base.lifetime.Destroyable;
import org.chromium.base.supplier.ObservableSupplier;
import org.chromium.base.supplier.ObservableSupplierImpl;
import org.chromium.chrome.browser.tab.EmptyTabObserver;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tabmodel.TabModelObserver;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.components.browser_ui.widget.gesture.BackPressHandler;
import org.chromium.content_public.browser.SelectionPopupController;

/**
 * {@link BackPressHandler} of {@link SelectionPopupController}. This listens to the change of tab
 * model and notifies whether the current selection popup controller is going to intercept the
 * back press.
 */
public class SelectionPopupBackPressHandler
        extends EmptyTabObserver implements BackPressHandler, TabModelObserver, Destroyable {
    private final ObservableSupplierImpl<Boolean> mBackPressChangedSupplier =
            new ObservableSupplierImpl<>();
    private final Callback<Boolean> mCallback = this::onActionBarShowingChanged;

    private SelectionPopupController mPopupController;
    private Tab mTab;

    /**
     * @param tabModelSelector A {@link TabModelSelector} which can provide
     * {@link org.chromium.chrome.browser.tabmodel.TabModelFilterProvider}.
     */
    public SelectionPopupBackPressHandler(TabModelSelector tabModelSelector) {
        tabModelSelector.getTabModelFilterProvider().addTabModelFilterObserver(this);
    }

    @Override
    public void handleBackPress() {
        assert mPopupController != null;
        mPopupController.clearSelection();
    }

    @Override
    public ObservableSupplier<Boolean> getHandleBackPressChangedSupplier() {
        return mBackPressChangedSupplier;
    }

    @Override
    public void didSelectTab(Tab tab, int type, int lastId) {
        mBackPressChangedSupplier.set(false);
        if (mPopupController != null) {
            mPopupController.isSelectActionBarShowingSupplier().removeObserver(mCallback);
        }
        if (tab.getWebContents() == null) return;
        if (mTab != null) tab.removeObserver(this);
        tab.addObserver(this);
        mTab = tab;
        mPopupController = SelectionPopupController.fromWebContents(tab.getWebContents());
        mPopupController.isSelectActionBarShowingSupplier().addObserver(mCallback);
    }

    @Override
    public void onWebContentsSwapped(Tab tab, boolean didStartLoad, boolean didFinishLoad) {
        mPopupController.isSelectActionBarShowingSupplier().removeObserver(mCallback);
        mPopupController = SelectionPopupController.fromWebContents(tab.getWebContents());
        mPopupController.isSelectActionBarShowingSupplier().addObserver(mCallback);
    }

    @Override
    public void destroy() {
        if (mTab != null) mTab.removeObserver(this);
        mTab = null;
        if (mPopupController != null) {
            mPopupController.isSelectActionBarShowingSupplier().removeObserver(mCallback);
            mPopupController = null;
        }
    }

    private void onActionBarShowingChanged(boolean isShowing) {
        mBackPressChangedSupplier.set(isShowing);
    }
}


text:
001
018
019    package org.apache.hadoop.fs.s3native;
020
021    import java.io.BufferedOutputStream;
022    import java.io.File;
023    import java.io.FileNotFoundException;
024    import java.io.FileOutputStream;
025    import java.io.IOException;
026    import java.io.InputStream;
027    import java.io.OutputStream;
028    import java.net.URI;
029    import java.security.DigestOutputStream;
030    import java.security.MessageDigest;
031    import java.security.NoSuchAlgorithmException;
032    import java.util.ArrayList;
033    import java.util.HashMap;
034    import java.util.List;
035    import java.util.Map;
036    import java.util.Set;
037    import java.util.TreeSet;
038    import java.util.concurrent.TimeUnit;
039
040    import org.apache.commons.logging.Log;
041    import org.apache.commons.logging.LogFactory;
042    import org.apache.hadoop.classification.InterfaceAudience;
043    import org.apache.hadoop.classification.InterfaceStability;
044    import org.apache.hadoop.conf.Configuration;
045    import org.apache.hadoop.fs.BufferedFSInputStream;
046    import org.apache.hadoop.fs.FSDataInputStream;
047    import org.apache.hadoop.fs.FSDataOutputStream;
048    import org.apache.hadoop.fs.FSInputStream;
049    import org.apache.hadoop.fs.FileStatus;
050    import org.apache.hadoop.fs.FileSystem;
051    import org.apache.hadoop.fs.Path;
052    import org.apache.hadoop.fs.permission.FsPermission;
053    import org.apache.hadoop.fs.s3.S3Exception;
054    import org.apache.hadoop.io.retry.RetryPolicies;
055    import org.apache.hadoop.io.retry.RetryPolicy;
056    import org.apache.hadoop.io.retry.RetryProxy;
057    import org.apache.hadoop.util.Progressable;
058
059    /**
060     * <p>
061     * A {@link FileSystem} for reading and writing files stored on
062     * <a href="http://aws.amazon.com/s3">Amazon S3</a>.
063     * Unlike {@link org.apache.hadoop.fs.s3.S3FileSystem} this implementation
064     * stores files on S3 in their
065     * native form so they can be read by other S3 tools.
066     *
067     * A note about directories. S3 of course has no "native" support for them.
068     * The idiom we choose then is: for any directory created by this class,
069     * we use an empty object "#{dirpath}_$folder$" as a marker.
070     * Further, to interoperate with other S3 tools, we also accept the following:
071     *  - an object "#{dirpath}/' denoting a directory marker
072     *  - if there exists any objects with the prefix "#{dirpath}/", then the
073     *    directory is said to exist
074     *  - if both a file with the name of a directory and a marker for that
075     *    directory exists, then the *file masks the directory*, and the directory
076     *    is never returned.
077     * </p>
078     * @see org.apache.hadoop.fs.s3.S3FileSystem
079     */
080    @InterfaceAudience.Public
081    @InterfaceStability.Stable
082    public class NativeS3FileSystem extends FileSystem {
083
084      public static final Log LOG =
085        LogFactory.getLog(NativeS3FileSystem.class);
086
087      private static final String FOLDER_SUFFIX = "_$folder$";
088      static final String PATH_DELIMITER = Path.SEPARATOR;
089      private static final int S3_MAX_LISTING_LENGTH = 1000;
090
091      static class NativeS3FsInputStream extends FSInputStream {
092
093        private NativeFileSystemStore store;
094        private Statistics statistics;
095        private InputStream in;
096        private final String key;
097        private long pos = 0;
098
099        public NativeS3FsInputStream(NativeFileSystemStore store, Statistics statistics, InputStream in, String key) {
100          this.store = store;
101          this.statistics = statistics;
102          this.in = in;
103          this.key = key;
104        }
105
106        @Override
107        public synchronized int read() throws IOException {
108          int result = -1;
109          try {
110            result = in.read();
111          } catch (IOException e) {
112            LOG.info("Received IOException while reading '" + key + "', attempting to reopen.");
113            seek(pos);
114            result = in.read();
115          }
116          if (result != -1) {
117            pos++;
118          }
119          if (statistics != null && result != -1) {
120            statistics.incrementBytesRead(1);
121          }
122          return result;
123        }
124        @Override
125        public synchronized int read(byte[] b, int off, int len)
126          throws IOException {
127
128          int result = -1;
129          try {
130            result = in.read(b, off, len);
131          } catch (IOException e) {
132            LOG.info("Received IOException while reading '" + key + "', attempting to reopen.");
133            seek(pos);
134            result = in.read(b, off, len);
135          }
136          if (result > 0) {
137            pos += result;
138          }
139          if (statistics != null && result > 0) {
140            statistics.incrementBytesRead(result);
141          }
142          return result;
143        }
144
145        @Override
146        public void close() throws IOException {
147          in.close();
148        }
149
150        @Override
151        public synchronized void seek(long pos) throws IOException {
152          in.close();
153          LOG.info("Opening key '" + key + "' for reading at position '" + pos + "'");
154          in = store.retrieve(key, pos);
155          this.pos = pos;
156        }
157        @Override
158        public synchronized long getPos() throws IOException {
159          return pos;
160        }
161        @Override
162        public boolean seekToNewSource(long targetPos) throws IOException {
163          return false;
164        }
165      }
166
167      private class NativeS3FsOutputStream extends OutputStream {
168
169        private Configuration conf;
170        private String key;
171        private File backupFile;
172        private OutputStream backupStream;
173        private MessageDigest digest;
174        private boolean closed;
175
176        public NativeS3FsOutputStream(Configuration conf,
177            NativeFileSystemStore store, String key, Progressable progress,
178            int bufferSize) throws IOException {
179          this.conf = conf;
180          this.key = key;
181          this.backupFile = newBackupFile();
182          LOG.info("OutputStream for key '" + key + "' writing to tempfile '" + this.backupFile + "'");
183          try {
184            this.digest = MessageDigest.getInstance("MD5");
185            this.backupStream = new BufferedOutputStream(new DigestOutputStream(
186                new FileOutputStream(backupFile), this.digest));
187          } catch (NoSuchAlgorithmException e) {
188            LOG.warn("Cannot load MD5 digest algorithm," +
189                "skipping message integrity check.", e);
190            this.backupStream = new BufferedOutputStream(
191                new FileOutputStream(backupFile));
192          }
193        }
194
195        private File newBackupFile() throws IOException {
196          File dir = new File(conf.get("fs.s3.buffer.dir"));
197          if (!dir.mkdirs() && !dir.exists()) {
198            throw new IOException("Cannot create S3 buffer directory: " + dir);
199          }
200          File result = File.createTempFile("output-", ".tmp", dir);
201          result.deleteOnExit();
202          return result;
203        }
204
205        @Override
206        public void flush() throws IOException {
207          backupStream.flush();
208        }
209
210        @Override
211        public synchronized void close() throws IOException {
212          if (closed) {
213            return;
214          }
215
216          backupStream.close();
217          LOG.info("OutputStream for key '" + key + "' closed. Now beginning upload");
218
219          try {
220            byte[] md5Hash = digest == null ? null : digest.digest();
221            store.storeFile(key, backupFile, md5Hash);
222          } finally {
223            if (!backupFile.delete()) {
224              LOG.warn("Could not delete temporary s3n file: " + backupFile);
225            }
226            super.close();
227            closed = true;
228          }
229          LOG.info("OutputStream for key '" + key + "' upload complete");
230        }
231
232        @Override
233        public void write(int b) throws IOException {
234          backupStream.write(b);
235        }
236
237        @Override
238        public void write(byte[] b, int off, int len) throws IOException {
239          backupStream.write(b, off, len);
240        }
241      }
242
243      private URI uri;
244      private NativeFileSystemStore store;
245      private Path workingDir;
246
247      public NativeS3FileSystem() {
248        // set store in initialize()
249      }
250
251      public NativeS3FileSystem(NativeFileSystemStore store) {
252        this.store = store;
253      }
254
255      /**
256       * Return the protocol scheme for the FileSystem.
257       * <p/>
258       *
259       * @return <code>s3n</code>
260       */
261      @Override
262      public String getScheme() {
263        return "s3n";
264      }
265
266      @Override
267      public void initialize(URI uri, Configuration conf) throws IOException {
268        super.initialize(uri, conf);
269        if (store == null) {
270          store = createDefaultStore(conf);
271        }
272        store.initialize(uri, conf);
273        setConf(conf);
274        this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());
275        this.workingDir =
276          new Path("/user", System.getProperty("user.name")).makeQualified(this.uri, this.getWorkingDirectory());
277      }
278
279      private static NativeFileSystemStore createDefaultStore(Configuration conf) {
280        NativeFileSystemStore store = new Jets3tNativeFileSystemStore();
281
282        RetryPolicy basePolicy = RetryPolicies.retryUpToMaximumCountWithFixedSleep(
283            conf.getInt("fs.s3.maxRetries", 4),
284            conf.getLong("fs.s3.sleepTimeSeconds", 10), TimeUnit.SECONDS);
285        Map<Class<? extends Exception>, RetryPolicy> exceptionToPolicyMap =
286          new HashMap<Class<? extends Exception>, RetryPolicy>();
287        exceptionToPolicyMap.put(IOException.class, basePolicy);
288        exceptionToPolicyMap.put(S3Exception.class, basePolicy);
289
290        RetryPolicy methodPolicy = RetryPolicies.retryByException(
291            RetryPolicies.TRY_ONCE_THEN_FAIL, exceptionToPolicyMap);
292        Map<String, RetryPolicy> methodNameToPolicyMap =
293          new HashMap<String, RetryPolicy>();
294        methodNameToPolicyMap.put("storeFile", methodPolicy);
295        methodNameToPolicyMap.put("rename", methodPolicy);
296
297        return (NativeFileSystemStore)
298          RetryProxy.create(NativeFileSystemStore.class, store,
299              methodNameToPolicyMap);
300      }
301
302      private static String pathToKey(Path path) {
303        if (path.toUri().getScheme() != null && path.toUri().getPath().isEmpty()) {
304          // allow uris without trailing slash after bucket to refer to root,
305          // like s3n://mybucket
306          return "";
307        }
308        if (!path.isAbsolute()) {
309          throw new IllegalArgumentException("Path must be absolute: " + path);
310        }
311        String ret = path.toUri().getPath().substring(1); // remove initial slash
312        if (ret.endsWith("/") && (ret.indexOf("/") != ret.length() - 1)) {
313          ret = ret.substring(0, ret.length() -1);
314      }
315        return ret;
316      }
317
318      private static Path keyToPath(String key) {
319        return new Path("/" + key);
320      }
321
322      private Path makeAbsolute(Path path) {
323        if (path.isAbsolute()) {
324          return path;
325        }
326        return new Path(workingDir, path);
327      }
328
329      /** This optional operation is not yet supported. */
330      @Override
331      public FSDataOutputStream append(Path f, int bufferSize,
332          Progressable progress) throws IOException {
333        throw new IOException("Not supported");
334      }
335
336      @Override
337      public FSDataOutputStream create(Path f, FsPermission permission,
338          boolean overwrite, int bufferSize, short replication, long blockSize,
339          Progressable progress) throws IOException {
340
341        if (exists(f) && !overwrite) {
342          throw new IOException("File already exists:"+f);
343        }
344
345        if(LOG.isDebugEnabled()) {
346          LOG.debug("Creating new file '" + f + "' in S3");
347        }
348        Path absolutePath = makeAbsolute(f);
349        String key = pathToKey(absolutePath);
350        return new FSDataOutputStream(new NativeS3FsOutputStream(getConf(), store,
351            key, progress, bufferSize), statistics);
352      }
353
354      @Override
355      public boolean delete(Path f, boolean recurse) throws IOException {
356        FileStatus status;
357        try {
358          status = getFileStatus(f);
359        } catch (FileNotFoundException e) {
360          if(LOG.isDebugEnabled()) {
361            LOG.debug("Delete called for '" + f +
362                "' but file does not exist, so returning false");
363          }
364          return false;
365        }
366        Path absolutePath = makeAbsolute(f);
367        String key = pathToKey(absolutePath);
368        if (status.isDirectory()) {
369          if (!recurse && listStatus(f).length > 0) {
370            throw new IOException("Can not delete " + f + " at is a not empty directory and recurse option is false");
371          }
372
373          createParent(f);
374
375          if(LOG.isDebugEnabled()) {
376            LOG.debug("Deleting directory '" + f  + "'");
377          }
378          String priorLastKey = null;
379          do {
380            PartialListing listing = store.list(key, S3_MAX_LISTING_LENGTH, priorLastKey, true);
381            for (FileMetadata file : listing.getFiles()) {
382              store.delete(file.getKey());
383            }
384            priorLastKey = listing.getPriorLastKey();
385          } while (priorLastKey != null);
386
387          try {
388            store.delete(key + FOLDER_SUFFIX);
389          } catch (FileNotFoundException e) {
390            //this is fine, we don't require a marker
391          }
392        } else {
393          if(LOG.isDebugEnabled()) {
394            LOG.debug("Deleting file '" + f + "'");
395          }
396          createParent(f);
397          store.delete(key);
398        }
399        return true;
400      }
401
402      @Override
403      public FileStatus getFileStatus(Path f) throws IOException {
404        Path absolutePath = makeAbsolute(f);
405        String key = pathToKey(absolutePath);
406
407        if (key.length() == 0) { // root always exists
408          return newDirectory(absolutePath);
409        }
410
411        if(LOG.isDebugEnabled()) {
412          LOG.debug("getFileStatus retrieving metadata for key '" + key + "'");
413        }
414        FileMetadata meta = store.retrieveMetadata(key);
415        if (meta != null) {
416          if(LOG.isDebugEnabled()) {
417            LOG.debug("getFileStatus returning 'file' for key '" + key + "'");
418          }
419          return newFile(meta, absolutePath);
420        }
421        if (store.retrieveMetadata(key + FOLDER_SUFFIX) != null) {
422          if(LOG.isDebugEnabled()) {
423            LOG.debug("getFileStatus returning 'directory' for key '" + key +
424                "' as '" + key + FOLDER_SUFFIX + "' exists");
425          }
426          return newDirectory(absolutePath);
427        }
428
429        if(LOG.isDebugEnabled()) {
430          LOG.debug("getFileStatus listing key '" + key + "'");
431        }
432        PartialListing listing = store.list(key, 1);
433        if (listing.getFiles().length > 0 ||
434            listing.getCommonPrefixes().length > 0) {
435          if(LOG.isDebugEnabled()) {
436            LOG.debug("getFileStatus returning 'directory' for key '" + key +
437                "' as it has contents");
438          }
439          return newDirectory(absolutePath);
440        }
441
442        if(LOG.isDebugEnabled()) {
443          LOG.debug("getFileStatus could not find key '" + key + "'");
444        }
445        throw new FileNotFoundException("No such file or directory '" + absolutePath + "'");
446      }
447
448      @Override
449      public URI getUri() {
450        return uri;
451      }
452
453      /**
454       * <p>
455       * If <code>f</code> is a file, this method will make a single call to S3.
456       * If <code>f</code> is a directory, this method will make a maximum of
457       * (<i>n</i> / 1000) + 2 calls to S3, where <i>n</i> is the total number of
458       * files and directories contained directly in <code>f</code>.
459       * </p>
460       */
461      @Override
462      public FileStatus[] listStatus(Path f) throws IOException {
463
464        Path absolutePath = makeAbsolute(f);
465        String key = pathToKey(absolutePath);
466
467        if (key.length() > 0) {
468          FileMetadata meta = store.retrieveMetadata(key);
469          if (meta != null) {
470            return new FileStatus[] { newFile(meta, absolutePath) };
471          }
472        }
473
474        URI pathUri = absolutePath.toUri();
475        Set<FileStatus> status = new TreeSet<FileStatus>();
476        String priorLastKey = null;
477        do {
478          PartialListing listing = store.list(key, S3_MAX_LISTING_LENGTH, priorLastKey, false);
479          for (FileMetadata fileMetadata : listing.getFiles()) {
480            Path subpath = keyToPath(fileMetadata.getKey());
481            String relativePath = pathUri.relativize(subpath.toUri()).getPath();
482
483            if (fileMetadata.getKey().equals(key + "/")) {
484              // this is just the directory we have been asked to list
485            }
486            else if (relativePath.endsWith(FOLDER_SUFFIX)) {
487              status.add(newDirectory(new Path(
488                  absolutePath,
489                  relativePath.substring(0, relativePath.indexOf(FOLDER_SUFFIX)))));
490            }
491            else {
492              status.add(newFile(fileMetadata, subpath));
493            }
494          }
495          for (String commonPrefix : listing.getCommonPrefixes()) {
496            Path subpath = keyToPath(commonPrefix);
497            String relativePath = pathUri.relativize(subpath.toUri()).getPath();
498            status.add(newDirectory(new Path(absolutePath, relativePath)));
499          }
500          priorLastKey = listing.getPriorLastKey();
501        } while (priorLastKey != null);
502
503        if (status.isEmpty() &&
504            key.length() > 0 &&
505            store.retrieveMetadata(key + FOLDER_SUFFIX) == null) {
506          throw new FileNotFoundException("File " + f + " does not exist.");
507        }
508
509        return status.toArray(new FileStatus[status.size()]);
510      }
511
512      private FileStatus newFile(FileMetadata meta, Path path) {
513        return new FileStatus(meta.getLength(), false, 1, getDefaultBlockSize(),
514            meta.getLastModified(), path.makeQualified(this.getUri(), this.getWorkingDirectory()));
515      }
516
517      private FileStatus newDirectory(Path path) {
518        return new FileStatus(0, true, 1, 0, 0, path.makeQualified(this.getUri(), this.getWorkingDirectory()));
519      }
520
521      @Override
522      public boolean mkdirs(Path f, FsPermission permission) throws IOException {
523        Path absolutePath = makeAbsolute(f);
524        List<Path> paths = new ArrayList<Path>();
525        do {
526          paths.add(0, absolutePath);
527          absolutePath = absolutePath.getParent();
528        } while (absolutePath != null);
529
530        boolean result = true;
531        for (Path path : paths) {
532          result &= mkdir(path);
533        }
534        return result;
535      }
536
537      private boolean mkdir(Path f) throws IOException {
538        try {
539          FileStatus fileStatus = getFileStatus(f);
540          if (fileStatus.isFile()) {
541            throw new IOException(String.format(
542                "Can't make directory for path '%s' since it is a file.", f));
543
544          }
545        } catch (FileNotFoundException e) {
546          if(LOG.isDebugEnabled()) {
547            LOG.debug("Making dir '" + f + "' in S3");
548          }
549          String key = pathToKey(f) + FOLDER_SUFFIX;
550          store.storeEmptyFile(key);
551        }
552        return true;
553      }
554
555      @Override
556      public FSDataInputStream open(Path f, int bufferSize) throws IOException {
557        FileStatus fs = getFileStatus(f); // will throw if the file doesn't exist
558        if (fs.isDirectory()) {
559          throw new IOException("'" + f + "' is a directory");
560        }
561        LOG.info("Opening '" + f + "' for reading");
562        Path absolutePath = makeAbsolute(f);
563        String key = pathToKey(absolutePath);
564        return new FSDataInputStream(new BufferedFSInputStream(
565            new NativeS3FsInputStream(store, statistics, store.retrieve(key), key), bufferSize));
566      }
567
568      // rename() and delete() use this method to ensure that the parent directory
569      // of the source does not vanish.
570      private void createParent(Path path) throws IOException {
571        Path parent = path.getParent();
572        if (parent != null) {
573          String key = pathToKey(makeAbsolute(parent));
574          if (key.length() > 0) {
575              store.storeEmptyFile(key + FOLDER_SUFFIX);
576          }
577        }
578      }
579
580
581      @Override
582      public boolean rename(Path src, Path dst) throws IOException {
583
584        String srcKey = pathToKey(makeAbsolute(src));
585
586        if (srcKey.length() == 0) {
587          // Cannot rename root of file system
588          return false;
589        }
590
591        final String debugPreamble = "Renaming '" + src + "' to '" + dst + "' - ";
592
593        // Figure out the final destination
594        String dstKey;
595        try {
596          boolean dstIsFile = getFileStatus(dst).isFile();
597          if (dstIsFile) {
598            if(LOG.isDebugEnabled()) {
599              LOG.debug(debugPreamble +
600                  "returning false as dst is an already existing file");
601            }
602            return false;
603          } else {
604            if(LOG.isDebugEnabled()) {
605              LOG.debug(debugPreamble + "using dst as output directory");
606            }
607            dstKey = pathToKey(makeAbsolute(new Path(dst, src.getName())));
608          }
609        } catch (FileNotFoundException e) {
610          if(LOG.isDebugEnabled()) {
611            LOG.debug(debugPreamble + "using dst as output destination");
612          }
613          dstKey = pathToKey(makeAbsolute(dst));
614          try {
615            if (getFileStatus(dst.getParent()).isFile()) {
616              if(LOG.isDebugEnabled()) {
617                LOG.debug(debugPreamble +
618                    "returning false as dst parent exists and is a file");
619              }
620              return false;
621            }
622          } catch (FileNotFoundException ex) {
623            if(LOG.isDebugEnabled()) {
624              LOG.debug(debugPreamble +
625                  "returning false as dst parent does not exist");
626            }
627            return false;
628          }
629        }
630
631        boolean srcIsFile;
632        try {
633          srcIsFile = getFileStatus(src).isFile();
634        } catch (FileNotFoundException e) {
635          if(LOG.isDebugEnabled()) {
636            LOG.debug(debugPreamble + "returning false as src does not exist");
637          }
638          return false;
639        }
640        if (srcIsFile) {
641          if(LOG.isDebugEnabled()) {
642            LOG.debug(debugPreamble +
643                "src is file, so doing copy then delete in S3");
644          }
645          store.copy(srcKey, dstKey);
646          store.delete(srcKey);
647        } else {
648          if(LOG.isDebugEnabled()) {
649            LOG.debug(debugPreamble + "src is directory, so copying contents");
650          }
651          store.storeEmptyFile(dstKey + FOLDER_SUFFIX);
652
653          List<String> keysToDelete = new ArrayList<String>();
654          String priorLastKey = null;
655          do {
656            PartialListing listing = store.list(srcKey, S3_MAX_LISTING_LENGTH, priorLastKey, true);
657            for (FileMetadata file : listing.getFiles()) {
658              keysToDelete.add(file.getKey());
659              store.copy(file.getKey(), dstKey + file.getKey().substring(srcKey.length()));
660            }
661            priorLastKey = listing.getPriorLastKey();
662          } while (priorLastKey != null);
663
664          if(LOG.isDebugEnabled()) {
665            LOG.debug(debugPreamble +
666                "all files in src copied, now removing src files");
667          }
668          for (String key: keysToDelete) {
669            store.delete(key);
670          }
671
672          try {
673            store.delete(srcKey + FOLDER_SUFFIX);
674          } catch (FileNotFoundException e) {
675            //this is fine, we don't require a marker
676          }
677          if(LOG.isDebugEnabled()) {
678            LOG.debug(debugPreamble + "done");
679          }
680        }
681
682        return true;
683      }
684
685      @Override
686      public long getDefaultBlockSize() {
687        return getConf().getLong("fs.s3n.block.size", 64 * 1024 * 1024);
688      }
689
690      /**
691       * Set the working directory to the given directory.
692       */
693      @Override
694      public void setWorkingDirectory(Path newDir) {
695        workingDir = newDir;
696      }
697
698      @Override
699      public Path getWorkingDirectory() {
700        return workingDir;
701      }
702
703      @Override
704      public String getCanonicalServiceName() {
705        // Does not support Token
706        return null;
707      }
708    }


text:
require 'json'

module Outstream
  # Produce a stream of JSON tokens.
  class Json
    # Define an output JSON object, given a block. The block
    # is executed in a context which provides the add method,
    # for adding key-value pairs to the object.
    #
    # Example:
    #   Outstream::Json.create do
    #     add string: "hello", number: 42
    #     add array: [1,2,3]
    #     add "nested_object" {
    #       add "foo" => "bar"
    #     }
    #   end
    def self.create(&body_block)
      new body_block
    end

    # Iterate the output tokens. The block will receive JSON delimeters individually as strings,
    # and string values as quoted strings. If called without a block, returns an enumerator.
    #
    # Example:
    #   json.each {|token| puts token} => nil
    #   json.each => an_enumerator
    def each(&out_block)
      e = Enumerator.new {|yielder|
        Collector.new(yielder).collect &@body_block
      }

      if out_block
        e.each(&out_block)
        nil
      else
        e
      end
    end

    # Produce a compact string of the JSON. The entire string is produced at once; this is not
    # suitable for very large JSON output.
    def to_s
      "".tap {|s| each {|str| s.concat str } }
    end

    private

    def initialize(body_block)
      @body_block = body_block
    end

    class Receiver
      def initialize(collector)
        @_collector = collector
      end
      def add(objs, &block)
        @_collector.add objs, &block
      end
    end

    class Collector
      def initialize(yielder)
        @yielder = yielder
        @count = [0]
      end
      def collect(&block)
        add_object {
          receiver = Receiver.new self
          if block.arity == 1
            block[receiver]
          else
            (class << receiver; self; end).send(:define_method, :__call_block, &block)
            receiver.__call_block
          end
        }
      end
      def write(str)
        @yielder << str
      end
      def add(objs, &block)
        if block
          add_key objs
          add_object &block
        else
          add_to_object objs
        end
      end
      def add_to_object(objs)
        objs.each_pair {|key,val|
          add_key key
          add_value val
        }
      end
      def add_key(key)
        write "," if @count.last > 0
        write key.to_json
        write ":"
        @count[@count.size-1] += 1
      end
      def add_object
        begin
          write "{"
          @count.push 0
          return yield
        rescue
          raise
        ensure
          @count.pop
          write "}"
        end
      end
      def add_array(a)
        begin
          write "["
          a.enum_for(:each).each_with_index {|v,i|
            write "," if i > 0
            add_value v
          }
        rescue
          raise
        ensure
          write "]"
        end
      end
      def add_value(value)
        if value.respond_to?:each_pair
          add_object { add_to_object value }
        elsif value.respond_to?:each
          add_array value
        elsif value.respond_to?:call
          begin
            add_value value.call
          rescue
            add_value nil
            raise
          end
        else
          write value.to_json
        end
      end
    end
  end
end


text:
import pytest

from kore import config_factory
from kore.configs.exceptions import ConfigPluginNotFoundError

class TestConfigFactory(object):

    def test_undefined_config_type(self):
        config_type = 'undefined'

        with pytest.raises(ConfigPluginNotFoundError):
            config_factory.create(config_type)

    def test_dict_config_type(self):
        config_type = 'dict'
        config_dict = {
            'foo': 'bar',
            'bar': 'baz',
        }

        config = config_factory.create(config_type, **config_dict)

        assert config == config_dict


text:
package com.peppe.amanbhardwaj.peppe.landingpagemodels;

import com.peppe.amanbhardwaj.peppe.bizobj.Services;

/**
 * Created by amanbhardwaj on 9/23/17.
 */

public class ServiceItemObj {

    private String subcategory;
    private String title;
    private String charges;
    private String url;
    private int rating;
    private int reviewCount;

    public ServiceItemObj() {
    }

    public String getSubcategory() {
        return subcategory;
    }

    public void setSubcategory(String subcategory) {
        this.subcategory = subcategory;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getCharges() {
        return charges;
    }

    public void setCharges(String charges) {
        this.charges = charges;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getRating() {
        return rating;
    }

    public void setRating(int rating) {
        this.rating = rating;
    }

    public int getReviewCount() {
        return reviewCount;
    }

    public void setReviewCount(int reviewCount) {
        this.reviewCount = reviewCount;
    }

}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	FabricGroup = mongoose.model('FabricGroup'),
	_ = require('lodash');

/**
 * Create a Fabric group
 */
exports.create = function(req, res) {
	var fabricGroup = new FabricGroup(req.body);
	fabricGroup.user = req.user;

	fabricGroup.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(fabricGroup);
		}
	});
};

/**
 * Show the current Fabric group
 */
exports.read = function(req, res) {
	res.jsonp(req.fabricGroup);
};

/**
 * Update a Fabric group
 */
exports.update = function(req, res) {
	var fabricGroup = req.fabricGroup ;

	fabricGroup = _.extend(fabricGroup , req.body);

	fabricGroup.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(fabricGroup);
		}
	});
};

/**
 * Delete an Fabric group
 */
exports.delete = function(req, res) {
	var fabricGroup = req.fabricGroup ;

	fabricGroup.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(fabricGroup);
		}
	});
};

/**
 * List of Fabric groups
 */
exports.list = function(req, res) {
	FabricGroup.find().sort('-created').populate('user', 'displayName').exec(function(err, fabricGroups) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(fabricGroups);
		}
	});
};

/**
 * Fabric group middleware
 */
exports.fabricGroupByID = function(req, res, next, id) {
	FabricGroup.findById(id).populate('user', 'displayName').exec(function(err, fabricGroup) {
		if (err) return next(err);
		if (! fabricGroup) return next(new Error('Failed to load Fabric group ' + id));
		req.fabricGroup = fabricGroup ;
		next();
	});
};

/**
 * Fabric group authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.fabricGroup.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};


text:
layout: post
title:  "the money tool"
date:   2018-09-19 14:34:25
categories: blog feature
tags: featured
image: /assets/article_images/2018-09-19-the-money-tool/two-dollar-bill.jpg
---

## Many of us including myself have been confused lately. So allow me to clear that up.
<br />
Politics are a mess — like they have always been, avocados are edible bowls if you take out the seed and money is a tool. A straight up tool. Like an extra wrench in a tool bucket that you periodically use to solve problems that matter today or very soon in the future. Problems like, fix your brand new toilet that's now leaking all over your house. That wrench wasn't really important until now. It's great if you have it handy and if you don't then you're up shit creek.

The point is we need to stop thinking of money as something more than a tool. It just isn't. And if you do then it's exactly like if you had some weird fetish for owning a bunch of wrenches that you don't need right now. Instead maybe you should give them away to people that actually need a wrench or two.


text:
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import Pager from './Pager'

const {
    Simulate,
    renderIntoDocument,
    findAllInRenderedTree,
} = TestUtils

describe('Pager', () => {
    context("Given a pager with a lower bound of 1", () => {
        let onDown = newSpyHandler()
        let onUp = newSpyHandler()
        let component = renderIntoDocument(
            <Pager
                onClickUp={onUp.handler}
                onClickDown={onDown.handler}
                lower={1}
                upper={10}
                max={20}
                title='Pager'
            />
        )

        it("it should not trigger any event when up is clicked", () => {
            let controlUp = findAllInRenderedTree(component, x => /angle-up/.test(x.className))
            expect(controlUp).to.be.ok()
            expect(controlUp.length).to.equal(1)
            Simulate.click(controlUp[0])
            expect(onUp.hasBeenCalled()).not.to.be.ok()
        })

        it("it should trigger an event when down is clicked", () => {
            let controlDown = findAllInRenderedTree(component, x => /angle-down/.test(x.className))
            expect(controlDown).to.be.ok()
            expect(controlDown.length).to.equal(1)
            Simulate.click(controlDown[0])
            expect(onDown.hasBeenCalled()).to.be.ok()
        })

    })
    context("Given a pager with an upper bound = max", () => {
        let onDown = newSpyHandler()
        let onUp = newSpyHandler()
        let component = renderIntoDocument(
            <Pager
                onClickUp={onUp.handler}
                onClickDown={onDown.handler}
                lower={10}
                upper={20}
                max={20}
                title='Pager'
            />
        )

        it("it should not trigger any event when down is clicked", () => {
            let controlDown = findAllInRenderedTree(component, x => /angle-down/.test(x.className))
            expect(controlDown).to.be.ok()
            expect(controlDown.length).to.equal(1)
            Simulate.click(controlDown[0])
            expect(onDown.hasBeenCalled()).not.to.be.ok()
        })

        it("it should trigger an event when up is clicked", () => {
            let controlUp = findAllInRenderedTree(component, x => /angle-up/.test(x.className))
            expect(controlUp).to.be.ok()
            expect(controlUp.length).to.equal(1)
            Simulate.click(controlUp[0])
            expect(onUp.hasBeenCalled()).to.be.ok()
        })
    })
})


text:
package com.zeus.persist.model;

public interface IdModel<T> {

	public T getId();

	public void setId(T id);

	public String getOrder();

	public void setOrder(String order);
}


text:
package com.kansche.entity;

import java.io.Serializable;
import java.sql.Timestamp;
import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * T06WeeklyWorkエンティティクラス
 *
 */
@Entity
@Table(name = "t06_weekly_work")
@Generated(value = {"S2JDBC-Gen 2.4.45", "org.seasar.extension.jdbc.gen.internal.model.EntityModelFactoryImpl"}, date = "2012/12/23 16:50:29")
public class T06WeeklyWork implements Serializable {

    private static final long serialVersionUID = 1L;

    /** userIdプロパティ */
    @Id
    @Column(name = "user_id", precision = 10, nullable = false, unique = false)
    public Integer userId;

    /** mondayDateプロパティ */
    @Id
    @Column(name = "monday_date", length = 8, nullable = false, unique = false)
    public String mondayDate;

    /** scheduleプロパティ */
    @Column(name = "schedule", length = 1024, nullable = true, unique = false)
    public String schedule;

    /** resultsプロパティ */
    @Column(name = "results", length = 1024, nullable = true, unique = false)
    public String results;

    /** keepPointプロパティ */
    @Column(name = "keep_point", length = 1024, nullable = true, unique = false)
    public String keepPoint;

    /** problemPointプロパティ */
    @Column(name = "problem_point", length = 1024, nullable = true, unique = false)
    public String problemPoint;

    /** tryPointプロパティ */
    @Column(name = "try_point", length = 1024, nullable = true, unique = false)
    public String tryPoint;

    /** createdAtプロパティ */
    @Column(name = "created_at", nullable = true, unique = false)
    public Timestamp createdAt;

    /** updatedAtプロパティ */
    @Column(name = "updated_at", nullable = true, unique = false)
    public Timestamp updatedAt;

    /** deleteFlgプロパティ */
    @Column(name = "delete_flg", precision = 10, nullable = false, unique = false)
    public Integer deleteFlg;
}


text:
![Logo](admin/nut.png)
# ioBroker.nut

![Number of Installations](http://iobroker.live/badges/nut-installed.svg)
![Number of Installations](http://iobroker.live/badges/nut-stable.svg)
[![NPM version](http://img.shields.io/npm/v/iobroker.nut.svg)](https://www.npmjs.com/package/iobroker.nut)

![Test and Release](https://github.com/Apollon77/iobroker.nut/workflows/Test%20and%20Release/badge.svg)
[![Translation status](https://weblate.iobroker.net/widgets/adapters/-/nut/svg-badge.svg)](https://weblate.iobroker.net/engage/adapters/?utm_source=widget)
[![Downloads](https://img.shields.io/npm/dm/iobroker.nut.svg)](https://www.npmjs.com/package/iobroker.nut)

This adapter for ioBroker connects to a defined NUT server to provide the status and details of a connected UPS/USV as ioBroker states, so that it can be used there.

**This adapter uses Sentry libraries to automatically report exceptions and code errors to the developers.** For more details and for information how to disable the error reporting see [Sentry-Plugin Documentation](https://github.com/ioBroker/plugin-sentry#plugin-sentry)! Sentry reporting is used starting with js-controller 3.0.

## Description of parameters
### host_ip
IP address of the NUT server. NUT needs to run in server mode and needs to be accessible by the computer the
iobroker NUT adapter runs on. So check firewall settings if you have problems and allow the access. If the UPS
is connected locally you can also use 127.0.0.1 or localhost.

### host_port
Port of NUT. The default port is 3493

### ups_name
Name of the UPS as defined in the NUT configuration of the NUT server.

Hints:
- If you want to connect to an UPS connected to a Synology diskstation the name is simply "ups".
- If you want to connect to an UPS connected to a QNAP NAS the name is simply "qnapups".

### update_interval
Interval in Seconds to update the data. Default is 300s

## UPS-Monitor Notifies
Included is a small linux shell-script at scripts/nut-notify.sh which can be configured in upsmon.

The script needs execute rights (chmod +x nut-notify.sh).

It should be added to /etc/nut/upsmon.conf like:

```
NOTIFYCMD "cd /opt/iobroker/;./nut-notify.sh"
```

Additionally configure all relevant notify messages like:

```
NOTIFYFLAG ONLINE       SYSLOG+WALL+EXEC
NOTIFYFLAG ONBATT       SYSLOG+WALL+EXEC
NOTIFYFLAG LOWBATT      SYSLOG+WALL+EXEC
NOTIFYFLAG FSD          SYSLOG+WALL+EXEC
NOTIFYFLAG COMMOK       SYSLOG+WALL+EXEC
NOTIFYFLAG COMMBAD      SYSLOG+WALL+EXEC
NOTIFYFLAG SHUTDOWN     SYSLOG+WALL+EXEC
NOTIFYFLAG REPLBATT     SYSLOG+WALL+EXEC
NOTIFYFLAG NOCOMM       SYSLOG+WALL+EXEC
NOTIFYFLAG NOPARENT     SYSLOG+WALL+EXEC
```
Important is the added "EXEC" flag.

One simple example for a nut-notify.sh script is:
```
#! /bin/sh
# NUT adapter notify script.

logger -t nut-notify "Notify iobroker $UPSNAME -> $NOTIFYTYPE"
/opt/iobroker/iobroker message nut notify "{\"upsname\":\"$UPSNAME\",\"notifytype\":\"$NOTIFYTYPE\"}"

```

## Troubleshooting
If you have problems and the adapter do not deliver the data you can use the two scripts in directory "test"
of the adapter installation (so normally in node_modules/iobroker.nut/test relative to your iobroker installation
directory) to try it out on the commandline. Call the scripts using "node filename.js" to see the awaited parameters.

* **test_upslist.js**: Connects to the NUT server and returns a list of available UPS names
* **test_upsvars.js**: Connects to the NUT server for a defined UPS and returns a list of available UPS variables

## Todo
* docs for webpage

## Changelog

### 1.5.1 (2022-02-19)
* (simatec) jsonConfig added
* (simatec) test and release updated

### 1.5.0 (2021-05-08)
* (Apollon77) Add connection states
* (Apollon77) Optimize for js-controller 3.3
* (foxriver76) we fixed the state value type set to `battery.charge`

### 1.4.3 (2021-02-04)
* (Apollon77) Enhance the port check

### 1.4.2 (2021-01-23)
* (Apollon77) Check configured port before using it (Sentry IOBROKER-NUT-3)

### 1.4.1 (2021-01-21)
* (Apollon77) Optimize stop handling (Sentry IOBROKER-NUT-1)

### 1.4.0 (2021-01-14)
* (Apollon77) Prevent warnings in js-controller 3.2
* (Apollon77) Require at least js-controller 2.0

### 1.3.0 (2020-12-27)
* (Apollon77) adjust connection close handling
* (Apollon77) add compact mode

### 1.2.0 (2020-12-26)
* (Apollon77) update dependencies
* (Apollon77) Add Sentry error reporting

### 1.1.3 (2018-04-13)
* Fix Admin

### 1.1.2 (2018-03-28)
* Fix status parsing

### 1.1.1
* Enhance error handling

### 1.1.0
* Add possibility to call commands on the UPS

### 1.0.0
* change mode from schedule to deamon
* implement message support to receive messages from upsmon
* add status.severity to get one status about the USV with values idle, operating, operating_critical, action_needed, unknown

### 0.3.0
* add better usable status states under "status" channel

### 0.2.1
* finalizied initial version

### 0.1.0
* initial release for testing

## License

The MIT License (MIT)

Copyright (c) 2016-2022 Apollon77 <ingo@fischer-ka.de>

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.


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("TestFramework")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestFramework")]
[assembly: AssemblyCopyright("Copyright ©  2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

[assembly: Guid("b311157f-6ed1-4260-b236-422f50d93048")]

// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.15.0.0")]
[assembly: AssemblyFileVersion("0.15.0.0")]


text:
module RPH
  module EasySearch
    class Error < RuntimeError
      def self.message(msg=nil); msg.nil? ? @message : self.message = msg; end
      def self.message=(msg); @message = msg; end
    end

    # raised when a model is attempted to be configured, but doesn't exist
    class NoModelError < Error
      message "you've specified a model that doesn't exist"; end

    # raised when any model (consant) is derived from the `Setup.config' block
    # and is not a subclass of ActiveRecord::Base
    class InvalidActiveRecordModel < Error
      message "all models specified in `Setup.config' must descend from ActiveRecord"; end

    # raised when a model has not been configured, but is attempted to be searched
    # (each model used with EasySearch has to be configured, meaning, the columns
    #  to be searched for that model must be set)
    class InvalidSettings < Error
      message "you must specify all Models and the fields to search for each Model in the `Setup.config' block"; end

    # raised when block passed to `Setup.strip_keywords' does not evaluate as an instance of Array
    class InvalidDullKeywordsType < Error
      message "specified keywords must be of type Array in the `Setup.strip_keywords' block"; end
  end
end


text:
#ifndef QMEMORYVIDEOBUFFER_P_H
#define QMEMORYVIDEOBUFFER_P_H

#include <qabstractvideobuffer.h>

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

QT_BEGIN_NAMESPACE

class QMemoryVideoBufferPrivate;

class Q_MULTIMEDIA_EXPORT QMemoryVideoBuffer : public QAbstractVideoBuffer
{
    Q_DECLARE_PRIVATE(QMemoryVideoBuffer)
public:
    QMemoryVideoBuffer(const QByteArray &data, int bytesPerLine);
    ~QMemoryVideoBuffer();

    MapMode mapMode() const;

    uchar *map(MapMode mode, int *numBytes, int *bytesPerLine);
    void unmap();
};

QT_END_NAMESPACE

#endif


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <sys/types.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <debug.h>

#include <nuttx/input/touchscreen.h>

#include "tc.h"

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/****************************************************************************
 * Private Types
 ****************************************************************************/

/****************************************************************************
 * Private Function Prototypes
 ****************************************************************************/

/****************************************************************************
 * Private Data
 ****************************************************************************/

/****************************************************************************
 * Public Data
 ****************************************************************************/

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: tc_main
 ****************************************************************************/

int tc_main(int argc, char *argv[])
{
  struct touch_sample_s sample;
  ssize_t nbytes;
#if defined(CONFIG_NSH_BUILTIN_APPS) || CONFIG_EXAMPLES_TOUCHSCREEN_NSAMPLES > 0
  long nsamples;
#endif
  int fd;
  int errval = 0;
  int ret;

  /* If this example is configured as an NX add-on, then limit the number of
   * samples that we collect before returning.  Otherwise, we never return
   */

#if defined(CONFIG_NSH_BUILTIN_APPS)
  nsamples = 1;
  if (argc > 1)
    {
      nsamples = strtol(argv[1], NULL, 10);
    }
  message("tc_main: nsamples: %d\n", nsamples);
#elif CONFIG_EXAMPLES_TOUCHSCREEN_NSAMPLES > 0
  message("tc_main: nsamples: %d\n", CONFIG_EXAMPLES_TOUCHSCREEN_NSAMPLES);
#endif

  /* Initialization of the touchscreen hardware is performed by logic
   * external to this test.
   */

  message("tc_main: Initializing external touchscreen device\n");
  ret = arch_tcinitialize(CONFIG_EXAMPLES_TOUCHSCREEN_MINOR);
  if (ret != OK)
    {
      message("tc_main: arch_tcinitialize failed: %d\n", ret);
      errval = 1;
      goto errout;
    }

  /* Open the touchscreen device for reading */

  message("tc_main: Opening %s\n", CONFIG_EXAMPLES_TOUCHSCREEN_DEVPATH);
  fd = open(CONFIG_EXAMPLES_TOUCHSCREEN_DEVPATH, O_RDONLY);
  if (fd < 0)
    {
      message("tc_main: open %s failed: %d\n",
              CONFIG_EXAMPLES_TOUCHSCREEN_DEVPATH, errno);
      errval = 2;
      goto errout_with_tc;
    }

  /* Now loop the appropriate number of times, displaying the collected
   * touchscreen samples.
   */

#if defined(CONFIG_NSH_BUILTIN_APPS)
  for (; nsamples > 0; nsamples--)
#elif CONFIG_EXAMPLES_TOUCHSCREEN_NSAMPLES > 0
  for (nsamples = 0; nsamples < CONFIG_EXAMPLES_TOUCHSCREEN_NSAMPLES; nsamples++)
#else
  for (;;)
#endif
  {
    /* Flush any output before the loop entered or from the previous pass
     * through the loop.
     */

    msgflush();

    /* Read one sample */

    ivdbg("Reading...\n");
    nbytes = read(fd, &sample, sizeof(struct touch_sample_s));
    ivdbg("Bytes read: %d\n", nbytes);

    /* Handle unexpected return values */

    if (nbytes < 0)
      {
        errval = errno;
        if (errval != EINTR)
          {
            message("tc_main: read %s failed: %d\n",
                    CONFIG_EXAMPLES_TOUCHSCREEN_DEVPATH, errval);
            errval = 3;
            goto errout_with_dev;
          }

        message("tc_main: Interrupted read...\n");
      }
    else if (nbytes != sizeof(struct touch_sample_s))
      {
        message("tc_main: Unexpected read size=%d, expected=%d, Ignoring\n",
                nbytes, sizeof(struct touch_sample_s));
      }

    /* Print the sample data on successful return */

    else
      {
        message("Sample     :\n");
        message("   npoints : %d\n",   sample.npoints);
        message("Point 1    :\n");
        message("        id : %d\n",   sample.point[0].id);
        message("     flags : %02x\n", sample.point[0].flags);
        message("         x : %d\n",   sample.point[0].x);
        message("         y : %d\n",   sample.point[0].y);
        message("         h : %d\n",   sample.point[0].h);
        message("         w : %d\n",   sample.point[0].w);
        message("  pressure : %d\n",   sample.point[0].pressure);
      }
  }

errout_with_dev:
  close(fd);
errout_with_tc:
  arch_tcuninitialize();
errout:
  message("Terminating!\n");
  msgflush();
  return errval;
}


text:
layout: post
title: Over soon
date: 2008-06-18T06:15:00.003Z
author: Marcus Hammarberg
tags:
  - Marcus private
  - Life of a consultant
modified_time: 2008-06-18T06:22:16.339Z
blogger_id: tag:blogger.com,1999:blog-36533086.post-304044174706962406
blogger_orig_url: http://www.marcusoft.net/2008/06/over-soon.html
---

As
you might have notices the activity on the blog has been quite low for a
couple of weeks. This has to do with loads of stuff piling up at work
and a fully booked private calender.

The new project, that I am involved in at work, is really fun but also
one of the most dazed I've been in. We are throwing ideas out the window
every other hour. Last week I was in a design meeting from Monday
morning at nine to Thursday afternoon at three.
Also - as always in between these hectic meetings it's quite hard
to have thing to be busy with all the time. Confusing but very true - it
will be a great project when we get the form for it (and we are well
under way...)

Private - there have been things to do almost every day for the last
three weeks now, since the
[marathon](http://www.marcusoft.net/2008/05/commenting-stockholm-marathon.html).
This weekend is the last of these. When it gets like this I can't find
peace to rest even when I am free. Sad but true. It just feels like
another "item to be checked off in the calender".

Well - as I was saying; I can see the light in the tunnel. That must be
a good thing... don't you think? ;)


text:
Configs, Loading & usage

If the config exists in the core copy it to the app and edit it.

				//LOADING AND USAGE
		   Config::load('configfile');
		   Config::get('part');

Dummy data

			It's good that you can call in a task that runs a truncate on all your tables and refils it with dummy data.

oil r data:add_all

oil r data:add_banners

oil r data:...


text:
  Number: {{number}}
  Network:<select ng-model="network" ng-options="net for net in networks"></select>

<input type="text" ng-model="value">
<button  ng-click="makeCall({message: value, number: number})">
  Call Home!
</button>


text:
package org.usfirst.frc3360.Hyperion_3360_2013.subsystems;
import edu.wpi.first.wpilibj.SpeedController;
import org.usfirst.frc3360.Hyperion_3360_2013.RobotMap;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

public class Ascent_Angle extends Subsystem {

    SpeedController ascent_SetAngle = RobotMap.ascentAscent_SetAngle;
    int m_currentCommand;

    public Ascent_Angle()
    {
        SmartDashboard.putNumber("Ascent angle", 0);
        SmartDashboard.putString("Ascent angle status", "Standing Still");
        m_currentCommand = 0;
        ascent_SetAngle.set(m_currentCommand);
    }

    public void initDefaultCommand() {
    }

    public void AngleGoFront(){
        if (m_currentCommand != 1)
        {
            SmartDashboard.putNumber("Ascent angle", 1);
            SmartDashboard.putString("Ascent angle status", "Tilting Forward");
            m_currentCommand = 1;
            ascent_SetAngle.set(m_currentCommand);
        }
    }

    public void AngleGoRear(){
        if (m_currentCommand != -1)
        {
            SmartDashboard.putNumber("Ascent angle", -1);
            SmartDashboard.putString("Ascent angle status", "Tilting Backward");
            m_currentCommand = -1;
            ascent_SetAngle.set(m_currentCommand);
        }
    }

    public void AngleDoNothing(){
        if (m_currentCommand != 0)
        {
            SmartDashboard.putNumber("Ascent angle", 0);
            SmartDashboard.putString("Ascent angle status", "Standing Still");
            m_currentCommand = 0;
            ascent_SetAngle.set(m_currentCommand);
        }
    }
}