问:
Buffer filling last empty spaces in char array with unwanted data
```<code>FILE* file_;
        char buffer[5];
                file_ = fopen("Data.txt", "a+");
        while (!feof(file_))
        {
            fread(buffer, sizeof(buffer), 1, file_);
            cout << buffer<<" ";
            BM(buffer, pat);
        }
</code>```

Data.txt="ABCC1ABCC2XXX"

Output:

ABCC1m

ABCC2m

XXXC2m

How can I make buffer stop before it starts generating chars from previous buffer?(bolded font part)

Wanted output:

ABCC1

ABCC2

XXX

答:
OK, I can't find a decent duplicate - maybe someone else will.

The line

```<code>fread(buffer, sizeof(buffer), 1, file_);
</code>```

potentially fills your buffer completely. You need to keep the return value to know how many bytes were actually written, but assuming your file contained at least five bytes, all five bytes of your buffer array are now initialized.

However, to print buffer as a regular C string, it needs a sixth byte, containing the null terminator.

For example, the C string "12345" is actually represented as the char array {'1', '2', '3', '4', '5', 0}.

You don't have room for a terminator in your buffer, and don't write one, so you can't treat it as a simple C string.

Your options are:

add a terminator manually, as in Martin Bonner's answer

don't add a terminator, but track the size - you can use the C++17

```<code>std::string_view bufstr(buffer, nchars);
</code>```

to keep the pointer and size together (and you can print this normally)

stop using the old C I/O library entirely. The C++ I/O library admittedly doesn't have a much better way to read groups of five characters, but reading whole lines, for example, is much easier to do correctly.

Body:
FILE* file_;
        char buffer[5];
                file_ = fopen("Data.txt", "a+");
        while (!feof(file_))
        {
            fread(buffer, sizeof(buffer), 1, file_);
            cout << buffer<<" ";
            BM(buffer, pat);
        }

Data.txt="ABCC1ABCC2XXX"

Output:

ABCC1m

ABCC2m

XXXC2m

How can I make buffer stop before it starts generating chars from previous buffer?(bolded font part)

Wanted output:

ABCC1

ABCC2

XXX

Body:
OK, I can't find a decent duplicate - maybe someone else will.

The line

fread(buffer, sizeof(buffer), 1, file_);

potentially fills your buffer completely. You need to keep the return value to know how many bytes were actually written, but assuming your file contained at least five bytes, all five bytes of your buffer array are now initialized.

However, to print buffer as a regular C string, it needs a sixth byte, containing the null terminator.

For example, the C string "12345" is actually represented as the char array {'1', '2', '3', '4', '5', 0}.

You don't have room for a terminator in your buffer, and don't write one, so you can't treat it as a simple C string.

Your options are:

add a terminator manually, as in Martin Bonner's answer

don't add a terminator, but track the size - you can use the C++17

std::string_view bufstr(buffer, nchars);

to keep the pointer and size together (and you can print this normally)

stop using the old C I/O library entirely. The C++ I/O library admittedly doesn't have a much better way to read groups of five characters, but reading whole lines, for example, is much easier to do correctly.


来源: stackexchange

问:
How to manually call TreeCell#updateItem for a CheckBoxTreeItem so we can apply CSS?
I am having a standard TreeView in JavaFX with CheckBoxTreeItem in it. I've installed a listener to see when someone checks/ unchecks a checkbox. But I want that when someone check/unchecks a checkbox I trigger that checkboxitem's parent updateItem method and change his CSS ( for example if 3 or more childs are selected for a parent then change his color to red, otherwise green).

How can I do that?

```<code>rootItem.addEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(), e -> {
        if (e.getTreeItem().isLeaf()) {
            TreeItem<String> treeItem = (TreeItem) e.getTreeItem();
            CheckBoxTreeItem<String> parentItem = (CheckBoxTreeItem<String>) treeItem.getParent();
            // how to call repaint for the parentItem????
        }
    });

treeView.setCellFactory(p -> new CheckBoxTreeCell<>() {
    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        // toggle the parent's CSS here
    }
});
</code>```

答:
I agree with the answer by M. S. regarding the use of PseudoClass. However, you should not be trying to manually invoke updateItem. Instead, just add an EventHandler to listen for "check box selection changed" events. When an event occurs in a direct child, the parent should update the pseudo-class based on (using your example) whether or not 3+ children are selected.

Here's an example which also includes a "branch" PseudoClass so you can distinguish between a branch and a leaf in the CSS file:

```<code>import javafx.beans.InvalidationListener;
import javafx.beans.WeakInvalidationListener;
import javafx.css.PseudoClass;
import javafx.event.EventHandler;
import javafx.event.WeakEventHandler;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.CheckBoxTreeItem.TreeModificationEvent;
import javafx.scene.control.cell.CheckBoxTreeCell;

public class MyCheckBoxTreeCell<T> extends CheckBoxTreeCell<T> {

    private static final PseudoClass BRANCH = PseudoClass.getPseudoClass("branch");
    private static final PseudoClass THREE_CHILDREN_SELECTED = PseudoClass.getPseudoClass("three-children-selected");

    // event handler to listen for selection changes in direct children
    private final EventHandler<TreeModificationEvent<T>> handler = event -> {
        /*
         * Event starts from the source TreeItem and bubbles up the to the root. This means
         * the first time getTreeItem() != event.getTreeItem() will be the source TreeItem's
         * parent. We then consume the event to stop it propagating to the next parent.
         */
        if (getTreeItem() != event.getTreeItem()) {
            event.consume();
            updatePseudoClasses();
        }
    };
    private final WeakEventHandler<TreeModificationEvent<T>> weakHandler = new WeakEventHandler<>(handler);

    // Used to listen for the "leaf" property of the TreeItem and update the BRANCH pseudo-class
    private final InvalidationListener leafListener = observable -> updatePseudoClasses();
    private final WeakInvalidationListener weakLeafListener = new WeakInvalidationListener(leafListener);

    public MyCheckBoxTreeCell() {
        getStyleClass().add("my-check-box-tree-cell");

        // add listener to "treeItem" property to properly register and unregister
        // the "leafListener" and "handler" instances.
        treeItemProperty().addListener((observable, oldValue, newValue) -> {
            if (oldValue != null) {
                oldValue.leafProperty().removeListener(weakLeafListener);
                oldValue.removeEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(), weakHandler);
            }
            if (newValue != null) {
                newValue.leafProperty().addListener(weakLeafListener);
                newValue.addEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(), weakHandler);
            }
            updatePseudoClasses();
        });
    }

    private void updatePseudoClasses() {
        /*
         * Assumes the use of CheckBoxTreeItem for each TreeItem in the TreeView.
         *
         * This code is not the most efficient as it will recalculate both the BRANCH and
         * THREE_CHILDREN_SELECTED pseudo-classes each time either possibly changes.
         */
        var item = (CheckBoxTreeItem<T>) getTreeItem();
        if (item == null) {
            pseudoClassStateChanged(BRANCH, false);
            pseudoClassStateChanged(THREE_CHILDREN_SELECTED, false);
        } else {
            pseudoClassStateChanged(BRANCH, !item.isLeaf());

            int selected = 0;
            for (var child : item.getChildren()) {
                // only need to know if *at least* 3 children are selected
                if (((CheckBoxTreeItem<T>) child).isSelected() && ++selected >= 3) {
                    break;
                }
            }
            pseudoClassStateChanged(THREE_CHILDREN_SELECTED, selected >= 3);
        }
    }

    // No need to override "updateItem(T,boolean)" as CheckBoxTreeCell provides
    // the necessary implementation which can be customized via the StringConverter
    // property.

}
</code>```

And then your CSS file could look like:

.my-check-box-tree-cell:branch {
    -fx-background-color: green;
    -fx-text-fill: white;
}

.my-check-box-tree-cell:branch:three-children-selected {
    -fx-background-color: red;
    -fx-text-fill: white;
}
```

Addressing questions in comments:

Why wrapping every listener inside a weak one if we take care to unsubscribe it?

To decrease the chance of memory leaks. For instance, if you throw away the TreeView (without having cleared the root property) but maintain references to the TreeItems somewhere, then a non-weak handler/listener would hold the TreeCells and the TreeView in memory.

Why are you listening for leaf changes and when does it gets called?

To handle the case where TreeItems are dynamically added and/or removed. A TreeItem is a leaf if and only if its children list is empty. If an item is added, and the leaf now becomes a branch, we need to update the BRANCH pseudo-class in order to have the proper CSS applied. Same if an item is removed and a branch becomes a leaf.

This may or may not be relevant to your use case. If not, then feel free to remove this part of the implementation.

You check getTreeItem() != event.getTreeItem()) in the checkbox checked handler. Why? This will be called when a checkbox gets checked/ unchecked.

When you (un)check a CheckBoxTreeItem it fires an event. This event begins its journey at the CheckBoxTreeItem that was (un)checked. From there, it travels up (i.e. bubbles) the item hierarchy all the way to the root. At each item, any registered handlers will be invoked. Though if the event is consumed it does not proceed to the next parent item.

The reason we're adding the handler is to listen for any children being (un)checked—but only direct children. We don't care about changes in arbitrarily deep descendants nor the item the handler was registered to.

Since we only care about changes in direct children, we need to make sure we only react to events fired by said children. As the event is processed first by the item that was (un)checked, we need to not do anything in that first handler. We can do this by testing if the TreeItem of the containing TreeCell is the same one that fired the event, and the TreeModificationEvent#getTreeItem() method returns the item that caused the event to be fired (i.e. the item that was (un)checked). If they are the same instance, do nothing and let the event bubble up to the parent.

Now the parent item's handler is processing the event. This means getTreeItem() != event.getTreeItem() will return true and we enter the if block. This causes the update, if necessary, of the pseudo-classes' state. We then consume the event so it doesn't bubble up to the next parent; this effectively makes the handler only listen to events from direct children.

Note that if the parent item is not currently being displayed in the tree, then it will not be part of a cell. If its not part of a cell, it won't have had the handler added to it. Thus any non-displaying items won't be affected by any of this. This is okay since everything we're updating is purely visual; if an item isn't being displayed then there's no visuals to update.

ContentLicense: CC BY-SA 4.0

Body:
I am having a standard TreeView in JavaFX with CheckBoxTreeItem in it. I've installed a listener to see when someone checks/ unchecks a checkbox. But I want that when someone check/unchecks a checkbox I trigger that checkboxitem's parent updateItem method and change his CSS ( for example if 3 or more childs are selected for a parent then change his color to red, otherwise green).

How can I do that?

rootItem.addEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(), e -> {
        if (e.getTreeItem().isLeaf()) {
            TreeItem<String> treeItem = (TreeItem) e.getTreeItem();
            CheckBoxTreeItem<String> parentItem = (CheckBoxTreeItem<String>) treeItem.getParent();
            // how to call repaint for the parentItem????
        }
    });

treeView.setCellFactory(p -> new CheckBoxTreeCell<>() {
    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        // toggle the parent's CSS here
    }
});

Body:
I agree with the answer by M. S. regarding the use of PseudoClass. However, you should not be trying to manually invoke updateItem. Instead, just add an EventHandler to listen for "check box selection changed" events. When an event occurs in a direct child, the parent should update the pseudo-class based on (using your example) whether or not 3+ children are selected.

Here's an example which also includes a "branch" PseudoClass so you can distinguish between a branch and a leaf in the CSS file:

import javafx.beans.InvalidationListener;
import javafx.beans.WeakInvalidationListener;
import javafx.css.PseudoClass;
import javafx.event.EventHandler;
import javafx.event.WeakEventHandler;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.CheckBoxTreeItem.TreeModificationEvent;
import javafx.scene.control.cell.CheckBoxTreeCell;

public class MyCheckBoxTreeCell<T> extends CheckBoxTreeCell<T> {

    private static final PseudoClass BRANCH = PseudoClass.getPseudoClass("branch");
    private static final PseudoClass THREE_CHILDREN_SELECTED = PseudoClass.getPseudoClass("three-children-selected");

    // event handler to listen for selection changes in direct children
    private final EventHandler<TreeModificationEvent<T>> handler = event -> {
        /*
         * Event starts from the source TreeItem and bubbles up the to the root. This means
         * the first time getTreeItem() != event.getTreeItem() will be the source TreeItem's
         * parent. We then consume the event to stop it propagating to the next parent.
         */
        if (getTreeItem() != event.getTreeItem()) {
            event.consume();
            updatePseudoClasses();
        }
    };
    private final WeakEventHandler<TreeModificationEvent<T>> weakHandler = new WeakEventHandler<>(handler);

    // Used to listen for the "leaf" property of the TreeItem and update the BRANCH pseudo-class
    private final InvalidationListener leafListener = observable -> updatePseudoClasses();
    private final WeakInvalidationListener weakLeafListener = new WeakInvalidationListener(leafListener);

    public MyCheckBoxTreeCell() {
        getStyleClass().add("my-check-box-tree-cell");

        // add listener to "treeItem" property to properly register and unregister
        // the "leafListener" and "handler" instances.
        treeItemProperty().addListener((observable, oldValue, newValue) -> {
            if (oldValue != null) {
                oldValue.leafProperty().removeListener(weakLeafListener);
                oldValue.removeEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(), weakHandler);
            }
            if (newValue != null) {
                newValue.leafProperty().addListener(weakLeafListener);
                newValue.addEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(), weakHandler);
            }
            updatePseudoClasses();
        });
    }

    private void updatePseudoClasses() {
        /*
         * Assumes the use of CheckBoxTreeItem for each TreeItem in the TreeView.
         *
         * This code is not the most efficient as it will recalculate both the BRANCH and
         * THREE_CHILDREN_SELECTED pseudo-classes each time either possibly changes.
         */
        var item = (CheckBoxTreeItem<T>) getTreeItem();
        if (item == null) {
            pseudoClassStateChanged(BRANCH, false);
            pseudoClassStateChanged(THREE_CHILDREN_SELECTED, false);
        } else {
            pseudoClassStateChanged(BRANCH, !item.isLeaf());

            int selected = 0;
            for (var child : item.getChildren()) {
                // only need to know if *at least* 3 children are selected
                if (((CheckBoxTreeItem<T>) child).isSelected() && ++selected >= 3) {
                    break;
                }
            }
            pseudoClassStateChanged(THREE_CHILDREN_SELECTED, selected >= 3);
        }
    }

    // No need to override "updateItem(T,boolean)" as CheckBoxTreeCell provides
    // the necessary implementation which can be customized via the StringConverter
    // property.

}

And then your CSS file could look like:

.my-check-box-tree-cell:branch {
    -fx-background-color: green;
    -fx-text-fill: white;
}

.my-check-box-tree-cell:branch:three-children-selected {
    -fx-background-color: red;
    -fx-text-fill: white;
}

Addressing questions in comments:

Why wrapping every listener inside a weak one if we take care to unsubscribe it?

To decrease the chance of memory leaks. For instance, if you throw away the TreeView (without having cleared the root property) but maintain references to the TreeItems somewhere, then a non-weak handler/listener would hold the TreeCells and the TreeView in memory.

Why are you listening for leaf changes and when does it gets called?

To handle the case where TreeItems are dynamically added and/or removed. A TreeItem is a leaf if and only if its children list is empty. If an item is added, and the leaf now becomes a branch, we need to update the BRANCH pseudo-class in order to have the proper CSS applied. Same if an item is removed and a branch becomes a leaf.

This may or may not be relevant to your use case. If not, then feel free to remove this part of the implementation.

You check getTreeItem() != event.getTreeItem()) in the checkbox checked handler. Why? This will be called when a checkbox gets checked/ unchecked.

When you (un)check a CheckBoxTreeItem it fires an event. This event begins its journey at the CheckBoxTreeItem that was (un)checked. From there, it travels up (i.e. bubbles) the item hierarchy all the way to the root. At each item, any registered handlers will be invoked. Though if the event is consumed it does not proceed to the next parent item.

The reason we're adding the handler is to listen for any children being (un)checked—but only direct children. We don't care about changes in arbitrarily deep descendants nor the item the handler was registered to.

Since we only care about changes in direct children, we need to make sure we only react to events fired by said children. As the event is processed first by the item that was (un)checked, we need to not do anything in that first handler. We can do this by testing if the TreeItem of the containing TreeCell is the same one that fired the event, and the TreeModificationEvent#getTreeItem() method returns the item that caused the event to be fired (i.e. the item that was (un)checked). If they are the same instance, do nothing and let the event bubble up to the parent.

Now the parent item's handler is processing the event. This means getTreeItem() != event.getTreeItem() will return true and we enter the if block. This causes the update, if necessary, of the pseudo-classes' state. We then consume the event so it doesn't bubble up to the next parent; this effectively makes the handler only listen to events from direct children.

Note that if the parent item is not currently being displayed in the tree, then it will not be part of a cell. If its not part of a cell, it won't have had the handler added to it. Thus any non-displaying items won't be affected by any of this. This is okay since everything we're updating is purely visual; if an item isn't being displayed then there's no visuals to update.


问:
Convert an array of hash with symbols
I have an array of hashes:

```<code>[{'object' => 'ob1', 'quantity' => '2'}, {'object' => 'ob2', 'quantity' => '3'}, .....]
</code>```

I want to convert it to symbolized form:

```<code>[{:object => 'ob1', :quantity => '2'}, {:object => 'ob2', :quantity => '3'}, .....]
</code>```

tried with:

```<code>symbolized_array = array.each => { |c| c.to_options }
</code>```

but i didn't obtained any conversion, the symbolized_array is same as array

why?

答:
Use below code. Then you will get expected output

```<code>array.map! {|my_hash| my_hash.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}}
</code>```

Or simply you can use array.map(&:symbolize_keys). This code will be work on rails environment

Title: Convert an array of hash with symbols

Body:
I have an array of hashes:

[{'object' => 'ob1', 'quantity' => '2'}, {'object' => 'ob2', 'quantity' => '3'}, .....]

I want to convert it to symbolized form:

[{:object => 'ob1', :quantity => '2'}, {:object => 'ob2', :quantity => '3'}, .....]

tried with:

symbolized_array = array.each => { |c| c.to_options }

but i didn't obtained any conversion, the symbolized_array is same as array

why?

Body:
Use below code. Then you will get expected output

array.map! {|my_hash| my_hash.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}}

Or simply you can use array.map(&:symbolize_keys). This code will be work on rails environment


问:
How to order a matrix of object
I'm working on an application that read a file Excel with Apache POI. I put the cells value inside a matrix of String object.

```<code>[title 1][title 2][title 3]
[mark]   [smith]  [34]
[simon]  [black]  [24]
</code>```

I've been ask to allow to order the matrix according to the selected column.
How can I order a matrix of String object?

Thank you

答:
First of all thank you for this question, it proved to be quite a mental challenge to visualize and implement this solution. I hope the following solution is what you wanted.

I've written a method that will sort the matrix for you. The method takes a String matrix as an argument and returns a new String matrix with each column sorted by alphabetic older. The sorting is done independent of other columns so each column is sorted without external context.

Unfortunately it doesn't exclude the titles from the sorting process so if you need that to happen please let me know and I will do my best to implement that.

```<code>public static boolean isNumeric(String str) {
    return str.matches("^[0-9]+$");
}

public static String[][] sortMatrix(String[][] matrix)
{
    int matrixLength = matrix[0].length;

    String[][] sortedMatrix = new String[matrixLength][];
    java.util.List<String[]> columns = new java.util.ArrayList<>();

    for (int i1 = 0; i1 < matrixLength; i1++)
    {
        String[] column = new String[matrixLength];
        for (int i2 = 0; i2 < matrixLength; i2++) {
            column[i2] = matrix[i2][i1];
        }
        columns.add(column);
    }

    // First sort the column before proceeding
    columns.forEach(column -> Arrays.sort(column, new Comparator<String>()
    {
        public int compare(String s1, String s2)
        {
            boolean i1 = isNumeric(s1);
            boolean i2 = isNumeric(s2);

            if (i1 && i2) {
                return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
            }
            else if (!i1) {
                return 1;
            }
            else return -1;
        }
    }));

    for (int i1 = 0; i1 < columns.size(); i1++)
    {
        String[] row = new String[matrixLength];
        for (int i2 = 0; i2 < matrixLength; i2++) {
            row[i2] = columns.get(i2)[i1];
        }
        sortedMatrix[i1] = row;
    }
    return sortedMatrix;
}

public static void main(String[] args) throws IOException {

    String[][] matrix = new String[3][] ;
    matrix[0] = new String[] { "title 1", "title 2", "title 3" };
    matrix[1] = new String[] { "simon", "1", "10" };
    matrix[2] = new String[] { "mark", "35", "2" };

    matrix = sortMatrix(matrix);
    for (String[] row : matrix) {
        System.out.println(Arrays.toString(row));
    }
}
</code>```

EDIT: Implemented a custom comparator that takes number into account.

Title: How to order a matrix of object

Body:
I'm working on an application that read a file Excel with Apache POI. I put the cells value inside a matrix of String object.

[title 1][title 2][title 3]
[mark]   [smith]  [34]
[simon]  [black]  [24]

I've been ask to allow to order the matrix according to the selected column.
How can I order a matrix of String object?

Thank you

Body:
First of all thank you for this question, it proved to be quite a mental challenge to visualize and implement this solution. I hope the following solution is what you wanted.

I've written a method that will sort the matrix for you. The method takes a String matrix as an argument and returns a new String matrix with each column sorted by alphabetic older. The sorting is done independent of other columns so each column is sorted without external context.

Unfortunately it doesn't exclude the titles from the sorting process so if you need that to happen please let me know and I will do my best to implement that.

public static boolean isNumeric(String str) {
    return str.matches("^[0-9]+$");
}

public static String[][] sortMatrix(String[][] matrix)
{
    int matrixLength = matrix[0].length;

    String[][] sortedMatrix = new String[matrixLength][];
    java.util.List<String[]> columns = new java.util.ArrayList<>();

    for (int i1 = 0; i1 < matrixLength; i1++)
    {
        String[] column = new String[matrixLength];
        for (int i2 = 0; i2 < matrixLength; i2++) {
            column[i2] = matrix[i2][i1];
        }
        columns.add(column);
    }

    // First sort the column before proceeding
    columns.forEach(column -> Arrays.sort(column, new Comparator<String>()
    {
        public int compare(String s1, String s2)
        {
            boolean i1 = isNumeric(s1);
            boolean i2 = isNumeric(s2);

            if (i1 && i2) {
                return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
            }
            else if (!i1) {
                return 1;
            }
            else return -1;
        }
    }));

    for (int i1 = 0; i1 < columns.size(); i1++)
    {
        String[] row = new String[matrixLength];
        for (int i2 = 0; i2 < matrixLength; i2++) {
            row[i2] = columns.get(i2)[i1];
        }
        sortedMatrix[i1] = row;
    }
    return sortedMatrix;
}

public static void main(String[] args) throws IOException {

    String[][] matrix = new String[3][] ;
    matrix[0] = new String[] { "title 1", "title 2", "title 3" };
    matrix[1] = new String[] { "simon", "1", "10" };
    matrix[2] = new String[] { "mark", "35", "2" };

    matrix = sortMatrix(matrix);
    for (String[] row : matrix) {
        System.out.println(Arrays.toString(row));
    }
}

EDIT: Implemented a custom comparator that takes number into account.


问:
fetch record from cursor in SQL
i have list of records and have created cursor to loop through each record and check certain condition and return record if it satisfies my cursor is as follows :

```<code>DECLARE @ID int
DECLARE @FromDate datetime, @ToDate datetime
DEClare @expid as int
set @expid = 839
DECLARE IDs CURSOR FOR
select patpid,fromdate,todate from tdp_ProviderAccomodationTariffPlan where fk_patid =    162 and fk_pacid = 36

 OPEN IDs
 FETCH NEXT FROM IDs into @ID,@FromDate,@ToDate
 WHILE @@FETCH_STATUS = 0
 BEGIN
print @ID
print @FromDate
print @ToDate

--SELECT patpid,rate,SType FROM tdp_ProviderAccomodationTariffPlan
--WHERE ('2012-12-27' BETWEEN @FromDate AND @ToDate) and fk_patid = 162 and fk_pacid = 36

FETCH NEXT FROM IDs into @ID,@FromDate,@ToDate

END
CLOSE IDs
DEALLOCATE IDs
</code>```

in loop cursor fetch record whose id is '839' , Please help me solve the problem.

答:
```<code>ALTER PROCEDURE [dbo].[SP_UpdateEmpStatus_IfLastAttDateMoreThan50]
(
@Msg NVARCHAR(MAX)=null OUTPUT
)
AS
BEGIN

/**Declare Cursor**/
DECLARE @TCursor CURSOR

/**Declare Cursor**/

DECLARE @EmpCode bigint=null,@maxAttDate DATE=null,@totDays INT=null

/**Creating TempDetails Table**/
CREATE TABLE #TempDetails
(EmpCode BIGINT,maxAttDate DATE,totDays int)
/**Creating TempDetails Table**/

INSERT INTO #TempDetails(EmpCode,maxAttDate,totDays)
(
SELECT  EmpCode,MAX( LastAttDate) AS maxAttDate,(DATEDIFF(DAY,MAX( LastAttDate),GETDATE())) As totDays FROM tbl_EmpdutyDays
WHERE EmpCode IN (SELECT DISTINCT EmpCode FROM tbl_Set_EmpWiseValidations WHERE Status=1)
GROUP BY EmpCode
)

SET @TCursor =CURSOR FOR SELECT EmpCode,maxAttDate,totDays FROM #TempDetails
OPEN @TCursor
FETCH NEXT FROM @TCursor INTO @EmpCode,@maxAttDate,@totDays
WHILE @@FETCH_STATUS=0
BEGIN
        IF(@totDays IS NOT NULL)
        BEGIN
                IF (@totDays>=50)
                BEGIN
                    UPDATE tbl_Set_EmpRestric
                    SET [Status]=0
                    WHERE EmpCode=@EmpCode

                    UPDATE tbl_Employees
                    SET [Status]=0
                    WHERE EmpCode=@EmpCode
                END

        END

        FETCH NEXT FROM @TCursor INTO @EmpCode,@maxAttDate,@totDays
END
SET @Msg='more Than 50 days Deactived Successfully.'
DEALLOCATE @TCursor
SELECT * FROM #TempDetails
DROP TABLE #TempDetails
END
</code>```

ContentLicense: CC BY-SA 3.0

Title: fetch record from cursor in SQL

Body:
i have list of records and have created cursor to loop through each record and check certain condition and return record if it satisfies my cursor is as follows :

DECLARE @ID int
DECLARE @FromDate datetime, @ToDate datetime
DEClare @expid as int
set @expid = 839
DECLARE IDs CURSOR FOR
select patpid,fromdate,todate from tdp_ProviderAccomodationTariffPlan where fk_patid =    162 and fk_pacid = 36

 OPEN IDs
 FETCH NEXT FROM IDs into @ID,@FromDate,@ToDate
 WHILE @@FETCH_STATUS = 0
 BEGIN
print @ID
print @FromDate
print @ToDate

--SELECT patpid,rate,SType FROM tdp_ProviderAccomodationTariffPlan
--WHERE ('2012-12-27' BETWEEN @FromDate AND @ToDate) and fk_patid = 162 and fk_pacid = 36

FETCH NEXT FROM IDs into @ID,@FromDate,@ToDate

END
CLOSE IDs
DEALLOCATE IDs

in loop cursor fetch record whose id is '839' , Please help me solve the problem.


问:
How to make CSS hover tooltip display auto position(Top,Right,Bottom,Left) inside of a table
I am using bootstrap4 and custom CSS,I want to display a tooltip on td element and position it top or right or bottom or left up to the positon of td element  ? Here you can find my classes with a HTML file and a CSS file that make it's position always on top.

Here I enclose my code link to you:
Here is my Codepen.

Below you will find my code which does not provide the right solution.

This is some HTML code:

```<code><div class="container">
    <div class="col-6">
        <table class="table table-responsive">
            <tr>
                <td class="CellWithComment">
                    S
                    <span class="CellComment">
                        010620190528113002
                        <br>
                            55555
                        <br>
                        2019-05-2804:25:37
                    </span>
                <td>
                <td class="CellWithComment">
                    S
                    <span class="CellComment">
                        010620190528113002
                        <br>
                            55555
                        </br>
                        2019-05-2804:25:37
                    </span>
                <td>
            </tr>
        </table>
    </div>
</div>
</code>```

This is my CSS:

```<code>.CellWithComment {
 position: relative;
 }

.CellComment {
visibility: hidden;
background-color: black;
color: #fff;
text-align: left;
border-radius: 6px;
padding: 3px 7px;
position: absolute;
z-index: 1908;
bottom: 100%;
margin-left: -92px;
}
.CellComment::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: black transparent transparent transparent;
}

.CellWithComment:hover span.CellComment {
 visibility: visible;
 }
</code>```

答:
Try this I think it's usefull for you.</p>

```<code>.CellComment:after {
  content: '';
  position: absolute;
  top: -8px;
  left: 50%;
  margin-left: -8px;
  width: 0; height: 0;
  border-bottom: 8px solid #000000;
  border-right: 8px solid transparent;
  border-left: 8px solid transparent;
}

.CellComment {
  visibility: hidden;
  background-color: black;
  color: #fff;
 text-align: left;
 border-radius: 6px;
 padding: 3px 7px;
 position: absolute;
 z-index: 1908;
 top: 100%;
}
</code>```

Body:
I am using bootstrap4 and custom CSS,I want to display a tooltip on td element and position it top or right or bottom or left up to the positon of td element  ? Here you can find my classes with a HTML file and a CSS file that make it's position always on top.

Here I enclose my code link to you:
Here is my Codepen.

Below you will find my code which does not provide the right solution.

This is some HTML code:

                    S

                        010620190528113002

                            55555

                        2019-05-2804:25:37

                    S

                        010620190528113002

                            55555

                        2019-05-2804:25:37

This is my CSS:

.CellWithComment {
 position: relative;
 }

.CellComment {
visibility: hidden;
background-color: black;
color: #fff;
text-align: left;
border-radius: 6px;
padding: 3px 7px;
position: absolute;
z-index: 1908;
bottom: 100%;
margin-left: -92px;
}
.CellComment::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: black transparent transparent transparent;
}

.CellWithComment:hover span.CellComment {
 visibility: visible;
 }

Body:
Try this I think it's usefull for you.

.CellComment:after {
  content: '';
  position: absolute;
  top: -8px;
  left: 50%;
  margin-left: -8px;
  width: 0; height: 0;
  border-bottom: 8px solid #000000;
  border-right: 8px solid transparent;
  border-left: 8px solid transparent;
}

.CellComment {
  visibility: hidden;
  background-color: black;
  color: #fff;
 text-align: left;
 border-radius: 6px;
 padding: 3px 7px;
 position: absolute;
 z-index: 1908;
 top: 100%;
}


问:
api call is getting failed after 4 minutes of waiting
I am making an API call from client side but it is getting failed after 4 mins of waiting.

But when I run the same query in Oracle SQL Developer it is taking the same time but is showing the data there.

I am using the ReactJS for the frontend and nodeJS for the backend.

So can anyone tell me what should I change in frontend so that API call should not get failed and can render the data.

In Postman also, it is throwing the error - could not get response after waiting a long time.

```<code> componentDidMount() {
    // debugger;
    // event.preventDefault();
    axios.get(`http://localhost:4000/api/AMS/country`)
    .then(response => {
      // console.log(response);
      const country_Claim_Type = response.data;
      this.setState({ country_Claim_Type

      });
        console.log('data fetched');
        return axios.get(`http://localhost:4000/api/AMS/countryDollar`)
    }).then(response => {
      // console.log(response);
      const country_Claim_Dollar = response.data;
      this.setState({ country_Claim_Dollar

      });
        console.log('data fetched');
</code>```

```<code>            return axios.get(`http://localhost:4000/api/AMS/claimQuarter`)
        }).then(res => {
              const claims = res.data;
              let claim = [];
              let puru = [];
              claims.forEach(element => {
                claim.push(element.COUNT);
                puru.push(element.USD);
              });
              this.setState({
                Data: {
                  labels: ['FY19 Q1[NOV-JAN]','FY19 Q2[FEB-APR]','FY18[SEP-NOV]'],
                  datasets:[
                     {
                        label:'',
                        data: claim ,puru,
                        backgroundColor:[
                         'rgba(255,105,145,0.6)',
                         'rgba(155,100,210,0.6)',
                         'rgb(63, 191, 191)'

                      ]
                     }
                  ]
               }
               });
</code>```

```<code>           return axios.get(`http://localhost:4000/api/AMS/claimType`)
        }) .then(barGraph => {
          const claims = barGraph.data;
           let claimcount = [];
          let claimtype = [];
          claims.forEach(element => {
             claimcount.push(element.COUNT);
            claimtype.push(element.CLT_NAME);
          });
          this.setState({
            Claim_Type: {
               labels: claimtype,
              datasets:[
                 {
                    label:'',
                    data: claimcount ,
                    backgroundColor:[

                     'rgba(255,105,145,0.6)',
                     'rgba(155,100,210,0.6)',
                     'rgb(255, 0, 64)',
                     'rgb(191, 255, 0)',
                     'rgb(0, 255, 255)',
                     'rgb(128, 0, 255)'
                  ]
                 }
              ]
           }
           });
           return axios.get(`http://localhost:4000/api/AMS/claimCountry`)
        }).then(countryList => {
          const claims = countryList.data;
          let claimcount = [];
          let country = [];
          var coloR = [];
          const percent = "%";
          // let claimvalue = [];
          let claimTotal = 0;
          var dynamicColors = function() {
            var r = Math.floor(Math.random() * 255);
            var g = Math.floor(Math.random() * 255);
            var b = Math.floor(Math.random() * 255);
            return "rgb(" + r + "," + g + "," + b + ")";
         };
          claims.forEach(element => {
           claimTotal+=element.COUNT;
         });
          claims.forEach(element => {
            claimcount.push(parseFloat((element.COUNT/claimTotal)*100).toFixed(2));
            //  claimvalue.push(element.USD);
            country.push(element.COUNTRY);
            coloR.push(dynamicColors());
          });
          this.setState({
            country_claim: {
               labels: country,
               datasets:[
                 {
                    label:'ClaimCounts',
                    data: claimcount,
                    backgroundColor: coloR
                 }
              ]
           }
           });
           return axios.get(`http://localhost:4000/api/AMS/claimDollar`)
          }).then(res => {
            const claims = res.data;
            let dollar = [];
            claims.forEach(element => {
              dollar.push(element.USD);
            });
            this.setState({
              dollar_value: {
                labels: ['Q1','Q2','FY18'],
                datasets:[
                   {
                      label:'',
                      data: dollar ,
                      backgroundColor:[
                       'rgba(255,105,145,0.6)',
                       'rgba(155,100,210,0.6)',
                       'rgb(63, 191, 191)'

                    ]
                   }
                ]
             }
             });
            })

  }
</code>```

答:
If your database connection is right, and It's just take a long time to get data then cause timeout error. You only need to increase you request timeout, in express is like this:</p>

```<code>req.setTimeout(5 * 60 * 1000);
</code>```

Body:
I am making an API call from client side but it is getting failed after 4 mins of waiting.

But when I run the same query in Oracle SQL Developer it is taking the same time but is showing the data there.

I am using the ReactJS for the frontend and nodeJS for the backend.

So can anyone tell me what should I change in frontend so that API call should not get failed and can render the data.

In Postman also, it is throwing the error - could not get response after waiting a long time.

 componentDidMount() {
    // debugger;
    // event.preventDefault();
    axios.get(`http://localhost:4000/api/AMS/country`)
    .then(response => {
      // console.log(response);
      const country_Claim_Type = response.data;
      this.setState({ country_Claim_Type

      });
        console.log('data fetched');
        return axios.get(`http://localhost:4000/api/AMS/countryDollar`)
    }).then(response => {
      // console.log(response);
      const country_Claim_Dollar = response.data;
      this.setState({ country_Claim_Dollar

      });
        console.log('data fetched');

            return axios.get(`http://localhost:4000/api/AMS/claimQuarter`)
        }).then(res => {
              const claims = res.data;
              let claim = [];
              let puru = [];
              claims.forEach(element => {
                claim.push(element.COUNT);
                puru.push(element.USD);
              });
              this.setState({
                Data: {
                  labels: ['FY19 Q1[NOV-JAN]','FY19 Q2[FEB-APR]','FY18[SEP-NOV]'],
                  datasets:[
                     {
                        label:'',
                        data: claim ,puru,
                        backgroundColor:[
                         'rgba(255,105,145,0.6)',
                         'rgba(155,100,210,0.6)',
                         'rgb(63, 191, 191)'

                      ]
                     }
                  ]
               }
               });

           return axios.get(`http://localhost:4000/api/AMS/claimType`)
        }) .then(barGraph => {
          const claims = barGraph.data;
           let claimcount = [];
          let claimtype = [];
          claims.forEach(element => {
             claimcount.push(element.COUNT);
            claimtype.push(element.CLT_NAME);
          });
          this.setState({
            Claim_Type: {
               labels: claimtype,
              datasets:[
                 {
                    label:'',
                    data: claimcount ,
                    backgroundColor:[

                     'rgba(255,105,145,0.6)',
                     'rgba(155,100,210,0.6)',
                     'rgb(255, 0, 64)',
                     'rgb(191, 255, 0)',
                     'rgb(0, 255, 255)',
                     'rgb(128, 0, 255)'
                  ]
                 }
              ]
           }
           });
           return axios.get(`http://localhost:4000/api/AMS/claimCountry`)
        }).then(countryList => {
          const claims = countryList.data;
          let claimcount = [];
          let country = [];
          var coloR = [];
          const percent = "%";
          // let claimvalue = [];
          let claimTotal = 0;
          var dynamicColors = function() {
            var r = Math.floor(Math.random() * 255);
            var g = Math.floor(Math.random() * 255);
            var b = Math.floor(Math.random() * 255);
            return "rgb(" + r + "," + g + "," + b + ")";
         };
          claims.forEach(element => {
           claimTotal+=element.COUNT;
         });
          claims.forEach(element => {
            claimcount.push(parseFloat((element.COUNT/claimTotal)*100).toFixed(2));
            //  claimvalue.push(element.USD);
            country.push(element.COUNTRY);
            coloR.push(dynamicColors());
          });
          this.setState({
            country_claim: {
               labels: country,
               datasets:[
                 {
                    label:'ClaimCounts',
                    data: claimcount,
                    backgroundColor: coloR
                 }
              ]
           }
           });
           return axios.get(`http://localhost:4000/api/AMS/claimDollar`)
          }).then(res => {
            const claims = res.data;
            let dollar = [];
            claims.forEach(element => {
              dollar.push(element.USD);
            });
            this.setState({
              dollar_value: {
                labels: ['Q1','Q2','FY18'],
                datasets:[
                   {
                      label:'',
                      data: dollar ,
                      backgroundColor:[
                       'rgba(255,105,145,0.6)',
                       'rgba(155,100,210,0.6)',
                       'rgb(63, 191, 191)'

                    ]
                   }
                ]
             }
             });
            })

  }

Body:
If your database connection is right, and It's just take a long time to get data then cause timeout error. You only need to increase you request timeout, in express is like this:

req.setTimeout(5 * 60 * 1000);


问:
How to import CSV file data into a PostgreSQL table
How can I write a stored procedure that imports data from a CSV file and populates the table?</p>

答:
How to import CSV file data into a PostgreSQL table

Steps:

Need to connect a PostgreSQL database in the terminal

```<code> psql -U postgres -h localhost
</code>```

Need to create a database

```<code> create database mydb;
</code>```

Need to create a user

```<code> create user siva with password 'mypass';
</code>```

Connect with the database

```<code> \c mydb;
</code>```

Need to create a schema

```<code> create schema trip;
</code>```

Need to create a table

```<code> create table trip.test(VendorID int,passenger_count int,trip_distance decimal,RatecodeID int,store_and_fwd_flag varchar,PULocationID int,DOLocationID int,payment_type decimal,fare_amount decimal,extra decimal,mta_tax decimal,tip_amount decimal,tolls_amount int,improvement_surcharge decimal,total_amount
 );
</code>```

Import csv file data to postgresql

```<code> COPY trip.test(VendorID int,passenger_count int,trip_distance decimal,RatecodeID int,store_and_fwd_flag varchar,PULocationID int,DOLocationID int,payment_type decimal,fare_amount decimal,extra decimal,mta_tax decimal,tip_amount decimal,tolls_amount int,improvement_surcharge decimal,total_amount) FROM '/home/Documents/trip.csv' DELIMITER ',' CSV HEADER;
</code>```

Find the given table data

```<code> select * from trip.test;
</code>```

Body:
How to import CSV file data into a PostgreSQL table

Steps:

Need to connect a PostgreSQL database in the terminal

 psql -U postgres -h localhost

Need to create a database

 create database mydb;

Need to create a user

 create user siva with password 'mypass';

Connect with the database

 \c mydb;

Need to create a schema

 create schema trip;

Need to create a table

 create table trip.test(VendorID int,passenger_count int,trip_distance decimal,RatecodeID int,store_and_fwd_flag varchar,PULocationID int,DOLocationID int,payment_type decimal,fare_amount decimal,extra decimal,mta_tax decimal,tip_amount decimal,tolls_amount int,improvement_surcharge decimal,total_amount
 );

Import csv file data to postgresql

 COPY trip.test(VendorID int,passenger_count int,trip_distance decimal,RatecodeID int,store_and_fwd_flag varchar,PULocationID int,DOLocationID int,payment_type decimal,fare_amount decimal,extra decimal,mta_tax decimal,tip_amount decimal,tolls_amount int,improvement_surcharge decimal,total_amount) FROM '/home/Documents/trip.csv' DELIMITER ',' CSV HEADER;

Find the given table data

 select * from trip.test;


问:
How to render BULLET character in React Native?
Im trying to format data that has to be displayed on <Text>. Here is my formatData() method:

```<code>getFormattedData = (idA, idB) => {
    var formattedData = "";
    if (idA != null && idA != "") {
        formattedData = formattedData + "•" + " " + idA
    }
    if (idB != null && idB != "") {
        formattedData = formattedData + "•" + " " + idB
    }
    return formattedData;
};
</code>```

But in view, this is rendered as ABC • DEF. And not as ABC • DEF

When I use \u2B24 the bullet is very big and when using \2022, just the code is displayed.

How to render • with getFormattedData()?

答:
To parse HTML Entities you can use the npm module html-entities. </p>

```<code>import { Html5Entities } from 'html-entities';

render() {
    const entities = new Html5Entities();
    return (
      <SafeAreaView style={styles.container}>
        <View>
        <Text> {entities.decode('•')} </Text>
        </View>
      </SafeAreaView>
    );
  }
</code>```

Body:
Im trying to format data that has to be displayed on <Text>. Here is my formatData() method:

getFormattedData = (idA, idB) => {
    var formattedData = "";
    if (idA != null && idA != "") {
        formattedData = formattedData + "•" + " " + idA
    }
    if (idB != null && idB != "") {
        formattedData = formattedData + "•" + " " + idB
    }
    return formattedData;
};

But in view, this is rendered as ABC • DEF. And not as ABC • DEF

When I use \u2B24 the bullet is very big and when using \2022, just the code is displayed.

How to render • with getFormattedData()?

Body:
To parse HTML Entities you can use the npm module html-entities.

import { Html5Entities } from 'html-entities';

render() {
    const entities = new Html5Entities();
    return (
      <SafeAreaView style={styles.container}>
        <View>
        <Text> {entities.decode('&#8226;')} </Text>
        </View>
      </SafeAreaView>
    );
  }


问:
How do you access nested JSON data on React?
I am having trouble accessing the JSON data obtained from the Accuweather API on React in the Render Method.

I am doing this on React and get a undefined error even though I see the value in the JSON view when I open the link and format it. I have tried using the dot method but no luck.

```<code>import React, { Component } from 'react';

class App extends Component {

constructor(props){
super(props);
this.state = {
    items:[],
    isLoaded: false,
}
}

componentDidMount() {

fetch('http://dataservice.accuweather.com/forecasts/v1/daily/1day/2094578.json?details=true&apikey=JjaFgoA67A3eXoMR7SiRyprGyPiv4Eln')

.then(res => res.json())
.then(json => {
    this.setState({
        isLoaded:true,
        items:json,
      })
})
}
render() {
var {isLoaded, items} = this.state;
if (!isLoaded) {
    return <div> Loading...</div>;
}
else {
  return (
    <div className="App">

     <h1>IES Storm Water Forecast</h1>
     <h1>{new Date().toString()}</h1>
     <h2> Weather Forcast: {items["DailyForecasts"]["Day"]["ShortPhrase"]}</h2>

     <h3>Description: {items.Headline.Text}</h3>
     <h6>Source: Accuweather</h6>
    </div>

);
}

}

}

export default App;
</code>```

JSON object in there:

http://dataservice.accuweather.com/forecasts/v1/daily/1day/2094578.json?details=true&apikey=JjaFgoA67A3eXoMR7SiRyprGyPiv4Eln

I get the following errors:

Unhandled Rejection (TypeError): Cannot read property 'ShortPhrase' of
  undefined TypeError: Cannot read property 'ShortPhrase' of undefined

But I should be getting a short sentence on weather.

答:
The returned data has a structure like this:

```<code>obj = {
  DailyForecasts: [
    {
      Day: {
        Icon: 6,
        IconPhrase: "Mostly cloudy",
        ShortPhrase: "Mostly cloudy",
        LongPhrase: "Mostly cloudy"
      }
    }
  ]
};

</code>```

You can see DailyForecasts returns an array. You will have to access this array before you access the object inside of it:

```<code>items["DailyForecasts"][0]["Day"]["ShortPhrase"]
</code>```

or with shorter, dot notation:

```<code>items.DailyForecasts[0].Day.ShortPhrase
</code>```

Body:
I am having trouble accessing the JSON data obtained from the Accuweather API on React in the Render Method.

I am doing this on React and get a undefined error even though I see the value in the JSON view when I open the link and format it. I have tried using the dot method but no luck.

import React, { Component } from 'react';

class App extends Component {

constructor(props){
super(props);
this.state = {
    items:[],
    isLoaded: false,
}
}

componentDidMount() {

fetch('http://dataservice.accuweather.com/forecasts/v1/daily/1day/2094578.json?details=true&apikey=JjaFgoA67A3eXoMR7SiRyprGyPiv4Eln')

.then(res => res.json())
.then(json => {
    this.setState({
        isLoaded:true,
        items:json,
      })
})
}
render() {
var {isLoaded, items} = this.state;
if (!isLoaded) {
    return
 Loading...
;
}
else {
  return (

IES Storm Water Forecast

{new Date().toString()}

 Weather Forcast: {items["DailyForecasts"]["Day"]["ShortPhrase"]}

Description: {items.Headline.Text}

Source: Accuweather

);
}

}

}

export default App;

JSON object in there:

http://dataservice.accuweather.com/forecasts/v1/daily/1day/2094578.json?details=true&apikey=JjaFgoA67A3eXoMR7SiRyprGyPiv4Eln

I get the following errors:

Unhandled Rejection (TypeError): Cannot read property 'ShortPhrase' of
  undefined TypeError: Cannot read property 'ShortPhrase' of undefined

But I should be getting a short sentence on weather.

Body:
The returned data has a structure like this:

obj = {
  DailyForecasts: [
    {
      Day: {
        Icon: 6,
        IconPhrase: "Mostly cloudy",
        ShortPhrase: "Mostly cloudy",
        LongPhrase: "Mostly cloudy"
      }
    }
  ]
};

You can see DailyForecasts returns an array. You will have to access this array before you access the object inside of it:

items["DailyForecasts"][0]["Day"]["ShortPhrase"]

or with shorter, dot notation:

items.DailyForecasts[0].Day.ShortPhrase


答:
You tagged rails so you can use symbolize_keys

```<code>array.map(&:symbolize_keys)
</code>```

Title: Convert an array of hash with symbols

Body:
You tagged rails so you can use symbolize_keys

array.map(&:symbolize_keys)


问:
Why I read many response packet in every goroutine when I send a tcp shake packet(SYN) in many goroutines
I'm building a port scanner to check if some TCP port at remote machine is open.

To improve performance, I just build and send a TCP SYN packet to remote port instead of doing full 3-way handshake.And if I receive SYN-ACK packet successfully,then that port will be considered as open.

Here is a part of my code:

```<code>conn, _:= net.Dial("ip4:tcp", target)
tcpSynPacket := BuildTcpSynPacket() // here I build a tcp syn packet
conn.Write(tcpSynPacket.Marshal())
deadlineTime := time.NewTicker(time.Second * 2)
defer deadlineTime.Stop()
for {
    select {
case <-deadlineTime.C:
    return nil
default:
        bytes := make([]byte, 128)
        conn.SetReadDeadline(time.Now().Add(time.Millisecond * 200))
        readnum, err := conn.Read(bytes)
        responsePacket := parstTCPHeader(bytes[:readnum])
        matched := CHECK_IF_RESPONSE_MATCH_REQUEST(tcpSynPacket,responsePacket) // here I'll check if ack-no,src-port,dest-port in tcpSynPacket match seq-no,dest-port,src-port in response packet
        if !matched {
            // unmatched packets,may response for another routine
            continue
        }
        if responsePacket.rst_flg == 1 {
            // the port would be consider as close
            // build func return struct,and return
            ....
        }else {
            // the port would be consider as open
            // build func return struct,and return
            ....
        }
}
</code>```

There are not for loop and CHECK_IF_RESPONSE_MATCH_REQUEST statement at old code.But when I do stress test, I found it's necessary.

Let's say we'll test if port 80 is open at 66.220.146.94.I open 1000 goroutines to call above code.

```<code>goroutine1: ack-no=11111

goroutine2: ack-no=22222

goroutine2: ack-no=33333

...
</code>```

Then I found that in every goroutine,the following statement

```<code>readnum, err := conn.Read(bytes)
responsePacket := parstTCPHeader(bytes[:readnum])
</code>```

will read all response packet even the read packet do not match the syn packet sent at current goroutine.

For example, at goroutine1, I sent syn packet(ack-no=11111),and read from conn. Then I found the seq-no in read packet could be 11112,22223,33334...
So I add a loop and some check logic at CHECK_IF_RESPONSE_MATCH_REQUEST.

But the loop read and check logic make cpu so high.

Here is a test result(I run it every 60 seconds)

Top 10 cpu cost using 3-way shakehand when open 1000 goroutine(Duration: 60s, Total samples = 780ms ( 1.30%)):

Top 10 cpu cost using tcp syn port scan when open 1000 goroutine(Duration: 60s, Total samples = 30.51s (50.85%)):

What I want to know is that:

1.Why conn.Read(bytes) read all response packets in every goroutine?Is net.Dial("ip4:tcp", targetip) correct?

2.Is there a lower-cost way to do periodic port scan(every 60 seconds) without doing 3-way shakehand

答:
Quick answer:

close conn at the end of the routine. net.Dial("ip4:tcp", targetip) is correct

reuse local ephemeral port in the socket pairs local:port remote:port when you craft the syn packet

Notes on 1:

Closing conn might not be the best idea, should do 2 above for these benefits:

not wasting cpu time for closing local ports

when you make multiple conns to the same addr too quickly and let kernel assign local port, the kernel ip stack might actually plays up - for more details, digging in this keyword TCP simultaneous connect

Body:
I'm building a port scanner to check if some TCP port at remote machine is open.

To improve performance, I just build and send a TCP SYN packet to remote port instead of doing full 3-way handshake.And if I receive SYN-ACK packet successfully,then that port will be considered as open.

Here is a part of my code:

conn, _:= net.Dial("ip4:tcp", target)
tcpSynPacket := BuildTcpSynPacket() // here I build a tcp syn packet
conn.Write(tcpSynPacket.Marshal())
deadlineTime := time.NewTicker(time.Second * 2)
defer deadlineTime.Stop()
for {
    select {
case <-deadlineTime.C:
    return nil
default:
        bytes := make([]byte, 128)
        conn.SetReadDeadline(time.Now().Add(time.Millisecond * 200))
        readnum, err := conn.Read(bytes)
        responsePacket := parstTCPHeader(bytes[:readnum])
        matched := CHECK_IF_RESPONSE_MATCH_REQUEST(tcpSynPacket,responsePacket) // here I'll check if ack-no,src-port,dest-port in tcpSynPacket match seq-no,dest-port,src-port in response packet
        if !matched {
            // unmatched packets,may response for another routine
            continue
        }
        if responsePacket.rst_flg == 1 {
            // the port would be consider as close
            // build func return struct,and return
            ....
        }else {
            // the port would be consider as open
            // build func return struct,and return
            ....
        }
}

There are not for loop and CHECK_IF_RESPONSE_MATCH_REQUEST statement at old code.But when I do stress test, I found it's necessary.

Let's say we'll test if port 80 is open at 66.220.146.94.I open 1000 goroutines to call above code.

goroutine1: ack-no=11111

goroutine2: ack-no=22222

goroutine2: ack-no=33333

...

Then I found that in every goroutine,the following statement

readnum, err := conn.Read(bytes)
responsePacket := parstTCPHeader(bytes[:readnum])

will read all response packet even the read packet do not match the syn packet sent at current goroutine.

For example, at goroutine1, I sent syn packet(ack-no=11111),and read from conn. Then I found the seq-no in read packet could be 11112,22223,33334...
So I add a loop and some check logic at CHECK_IF_RESPONSE_MATCH_REQUEST.

But the loop read and check logic make cpu so high.

Here is a test result(I run it every 60 seconds)

Top 10 cpu cost using 3-way shakehand when open 1000 goroutine(Duration: 60s, Total samples = 780ms ( 1.30%)):

Top 10 cpu cost using tcp syn port scan when open 1000 goroutine(Duration: 60s, Total samples = 30.51s (50.85%)):

What I want to know is that:

1.Why conn.Read(bytes) read all response packets in every goroutine?Is net.Dial("ip4:tcp", targetip) correct?

2.Is there a lower-cost way to do periodic port scan(every 60 seconds) without doing 3-way shakehand


问:
Despite using Infer Constraints, my Text Field, and Button aren't showing in their repsective locations in preview and output
I have tried using Infer Constraints but the output is very bizarre on the emulator as compared to the preview.

I have tried using the infer constraints button

答:
Try this:</p>

```<code><TextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintEnd_toEndOf="parent"/>

  <Button
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/text"/>
</code>```

Body:
Try this:

<TextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintEnd_toEndOf="parent"/>

  <Button
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/text"/>


问:
php move_uploaded_file always returns false
I'm using plain php (MVC) and I'm trying to upload files (any type of files) but when using "move_uploaded_file" function it always return false

i've tried changing the target path multiple times with constant URLROOT (my website target) to specifying it manually but nothing works ! i have three .htaccess files if necessary i will post its content if that the case.

```<code>public function uploadvideo($id){
        if($_SERVER['REQUEST_METHOD'] == 'POST'){

            $data = [
                'order_id' =>$id,
                'errors' => '',
                'video_name'=> uniqid()
            ];

            try{

                if(empty($_FILES)){
                    throw new Exception('Invalid upload');
                }

                switch ($_FILES['file']['error']){
                    case UPLOAD_ERR_OK:
                        break;
                    case UPLOAD_ERR_NO_FILE:
                        throw new Exception('No file uploaded');
                        break;
                    case UPLOAD_ERR_INI_SIZE:
                        throw new Exception('file is too large');
                        break;
                    default:
                        throw new Exception('An error occurred');
                }

                if($_FILES['file']['size'] > 20000000){
                    throw new Exception('Video size exceded must be below 21 MB');
                }

                if(empty($data['errors'])){

                    //$destination = URLROOT . "/public/uploads/" . $_FILES['files']['name'];
                    $destination = "/public/uploads" . $_FILES['files']['name'];

                    if(move_uploaded_file($_FILES['file']['tmp_name'],$destination)){
                        if($this->adminModel->uploadVideo($data)){
                            flash('post_message','video uploaded');
                            redirect('admins/index');
                        }else{
                            die('something went wrong');
                        }

                    }else{
                        // flash('post_message','uploading error');
                        var_dump($_FILES);
                        var_dump('xxx');
                        var_dump($destination);
                        var_dump($data);
                        throw new Exception('unable to move uploaded file');
                        // redirect('admins/index');
                    }

                }else{
                    flash('post_message',$data['errors']);
                    redirect('admins/index');
                }

            } catch(Exception $e){
                $data['errors'] = $e->getMessage();
            }

        }else{
            redirect('orders/index');
        }
    }
</code>```

and my form:

```<code><form method="post" enctype="multipart/form-data" action="<?php echo URLROOT;?>/admins/uploadvideo/<?php echo $order->order_id;?>">
                        <div>
                            <input type="file" name="file" id="file">
                        </div>
                        <input type="submit" value="upload" class="btn btn-warning"/>
                    </form>
</code>```

i expect it to redirect me to index but it returns false here a bit of my debug process (var_dump):

```<code>array(1) { ["file"]=> array(5) { ["name"]=> string(6) "22.png" ["type"]=> string(9) "image/png" ["tmp_name"]=> string(14) "/tmp/phpj4ScyG" ["error"]=> int(0) ["size"]=> int(144743) } } string(3) "xxx" string(15) "/public/uploads" array(3) { ["order_id"]=> string(5) "20076" ["errors"]=> string(0) "" ["video_name"]=> string(13) "5cecf6fea5632" }
</code>```

答:
As put in comment you probably have an error due to the fact that /public/upload22.png not exist for the destination file.

You missed a slash in your code :

$destination = "/public/uploads/" . $_FILES['files']['name'];

In your comment we can see

//$destination = URLROOT . "/public/uploads/" . $_FILES['files']['name'];

this is also wrong you have a typo here
$_FILES['files'] files should be named as file but you didn't forget the / this time

Body:
I'm using plain php (MVC) and I'm trying to upload files (any type of files) but when using "move_uploaded_file" function it always return false

i've tried changing the target path multiple times with constant URLROOT (my website target) to specifying it manually but nothing works ! i have three .htaccess files if necessary i will post its content if that the case.

public function uploadvideo($id){
        if($_SERVER['REQUEST_METHOD'] == 'POST'){

            $data = [
                'order_id' =>$id,
                'errors' => '',
                'video_name'=> uniqid()
            ];

            try{

                if(empty($_FILES)){
                    throw new Exception('Invalid upload');
                }

                switch ($_FILES['file']['error']){
                    case UPLOAD_ERR_OK:
                        break;
                    case UPLOAD_ERR_NO_FILE:
                        throw new Exception('No file uploaded');
                        break;
                    case UPLOAD_ERR_INI_SIZE:
                        throw new Exception('file is too large');
                        break;
                    default:
                        throw new Exception('An error occurred');
                }

                if($_FILES['file']['size'] > 20000000){
                    throw new Exception('Video size exceded must be below 21 MB');
                }

                if(empty($data['errors'])){

                    //$destination = URLROOT . "/public/uploads/" . $_FILES['files']['name'];
                    $destination = "/public/uploads" . $_FILES['files']['name'];

                    if(move_uploaded_file($_FILES['file']['tmp_name'],$destination)){
                        if($this->adminModel->uploadVideo($data)){
                            flash('post_message','video uploaded');
                            redirect('admins/index');
                        }else{
                            die('something went wrong');
                        }

                    }else{
                        // flash('post_message','uploading error');
                        var_dump($_FILES);
                        var_dump('xxx');
                        var_dump($destination);
                        var_dump($data);
                        throw new Exception('unable to move uploaded file');
                        // redirect('admins/index');
                    }

                }else{
                    flash('post_message',$data['errors']);
                    redirect('admins/index');
                }

            } catch(Exception $e){
                $data['errors'] = $e->getMessage();
            }

        }else{
            redirect('orders/index');
        }
    }

and my form:

<form method="post" enctype="multipart/form-data" action="<?php echo URLROOT;?>/admins/uploadvideo/<?php echo $order->order_id;?>">

                            <input type="file" name="file" id="file">

                        <input type="submit" value="upload" class="btn btn-warning"/>
                    </form>

i expect it to redirect me to index but it returns false here a bit of my debug process (var_dump):

array(1) { ["file"]=> array(5) { ["name"]=> string(6) "22.png" ["type"]=> string(9) "image/png" ["tmp_name"]=> string(14) "/tmp/phpj4ScyG" ["error"]=> int(0) ["size"]=> int(144743) } } string(3) "xxx" string(15) "/public/uploads" array(3) { ["order_id"]=> string(5) "20076" ["errors"]=> string(0) "" ["video_name"]=> string(13) "5cecf6fea5632" }


问:
"Module not found" error when execute webpack from the CLI command, registered in "/bin" of own library
When I run the webpack, I got error:

```<code>Module not found: Error: Can't resolve './StaticallyImportedModules/JsModuleForStaticImport' in
'D:\OneDrive\PhpStorm\TestProject\FrontendDevelopment\1_Source\0_Devel
opment\3_FrontendScripts'
</code>```

As you see, file is actually exists, and it has been found before I added new features to my project building application based on Webpack:

What changed is now project building performs by CLI command registered in the bin/my-lib (normally frequently added .js to files in bin, but following this tutorial I did not add the filename extension):

```<code>#!/usr/bin/env node

require('../index').interpretConsoleCommandAndExecute(process.argv);
</code>```

So interpretConsoleCommandAndExecute dynamically creates webpack config and run it. Of course, I executed npm link to make available my CLI command.

Before ask this question, I collected come information that the cause could be related with bin/my-lib, but I did not understand what I have to do.

According console output, webpack finds modules in right directories. What is really wrong?

答:
In this case, I just forgot

```<code>//...
resolve: {
  extensions: [
    '.ts', '.js'
  ]
}
//...
</code>```

in Webpack config.

Body:
When I run the webpack, I got error:

Module not found: Error: Can't resolve './StaticallyImportedModules/JsModuleForStaticImport' in
'D:\OneDrive\PhpStorm\TestProject\FrontendDevelopment\1_Source\0_Devel
opment\3_FrontendScripts'

As you see, file is actually exists, and it has been found before I added new features to my project building application based on Webpack:

What changed is now project building performs by CLI command registered in the bin/my-lib (normally frequently added .js to files in bin, but following this tutorial I did not add the filename extension):

#!/usr/bin/env node

require('../index').interpretConsoleCommandAndExecute(process.argv);

So interpretConsoleCommandAndExecute dynamically creates webpack config and run it. Of course, I executed npm link to make available my CLI command.

Before ask this question, I collected come information that the cause could be related with bin/my-lib, but I did not understand what I have to do.

According console output, webpack finds modules in right directories. What is really wrong?

Body:
In this case, I just forgot

//...
resolve: {
  extensions: [
    '.ts', '.js'
  ]
}
//...

in Webpack config.


问:
Eclipse removes external imports after saving the java file
I have imported a few external library imports in a java file.
After saving the file eclipse auto removes these imports.

Quick googling showed me results about organizing imports. But these are disabled in eclipse work-space.

How should I prevent this behavior?

答:
If you convert your project into a Maven project, you can add your imports into the pom.xml file.
 Thus all your external exports would now be considered as internal ones.

If you don't want to convert your project to Maven, you could Add External libraries to Eclispe.  See here


问:
replace values in data-table based on column number and separate index vector
I am given a large data-table and I need to set cells to a fixed value (e.g. 0) based on the column number and an index dependent on the row number.

As an example, I am given a data-table 'dt' full of ones. Additionally, I have a column vector, giving the number of columns (per row) that shall remain unchanged and the remaining ones shall be set to 0.

```<code>dt <- setnames(data.table(matrix(1,nrow=100, ncol=11)),as.character(c(0:10)))

set.seed(1)
index <- sample(c(0:11),100, replace=TRUE)

> dput(index)
c(3L, 4L, 6L, 10L, 2L, 10L, 11L, 7L, 7L, 0L, 2L, 2L, 8L, 4L,
9L, 5L, 8L, 11L, 4L, 9L, 11L, 2L, 7L, 1L, 3L, 4L, 0L, 4L, 10L,
4L, 5L, 7L, 5L, 2L, 9L, 8L, 9L, 1L, 8L, 4L, 9L, 7L, 9L, 6L, 6L,
9L, 0L, 5L, 8L, 8L, 5L, 10L, 5L, 2L, 0L, 1L, 3L, 6L, 7L, 4L,
10L, 3L, 5L, 3L, 7L, 3L, 5L, 9L, 1L, 10L, 4L, 10L, 4L, 4L, 5L,
10L, 10L, 4L, 9L, 11L, 5L, 8L, 4L, 3L, 9L, 2L, 8L, 1L, 2L, 1L,
2L, 0L, 7L, 10L, 9L, 9L, 5L, 4L, 9L, 7L)
</code>```

For example, in the first row, the first three cells remain unchanged and the other ones are set to 0.
As it is a large data-table, I look for an efficient way to do this

答:
In order to avoid complexity, I've taken the reverse approach and first changed all the 1s to 0s. Then it's a double for loop to change the amount of columns indicated in index, to 1s:</p>

```<code>library(data.table)

dt <- setnames(data.table(matrix(0,nrow=100, ncol=11)),as.character(c(0:10)))

index <- sample(c(0:11),100, replace=TRUE)

for(i in 1:length(index)) {
  if (index[i] > 0) {
    for(j in 1:index[i]) {
      dt[i,j] <- 1
    }
  }
}
</code>```

Body:
I am given a large data-table and I need to set cells to a fixed value (e.g. 0) based on the column number and an index dependent on the row number.

As an example, I am given a data-table 'dt' full of ones. Additionally, I have a column vector, giving the number of columns (per row) that shall remain unchanged and the remaining ones shall be set to 0.

dt <- setnames(data.table(matrix(1,nrow=100, ncol=11)),as.character(c(0:10)))

set.seed(1)
index <- sample(c(0:11),100, replace=TRUE)

> dput(index)
c(3L, 4L, 6L, 10L, 2L, 10L, 11L, 7L, 7L, 0L, 2L, 2L, 8L, 4L,
9L, 5L, 8L, 11L, 4L, 9L, 11L, 2L, 7L, 1L, 3L, 4L, 0L, 4L, 10L,
4L, 5L, 7L, 5L, 2L, 9L, 8L, 9L, 1L, 8L, 4L, 9L, 7L, 9L, 6L, 6L,
9L, 0L, 5L, 8L, 8L, 5L, 10L, 5L, 2L, 0L, 1L, 3L, 6L, 7L, 4L,
10L, 3L, 5L, 3L, 7L, 3L, 5L, 9L, 1L, 10L, 4L, 10L, 4L, 4L, 5L,
10L, 10L, 4L, 9L, 11L, 5L, 8L, 4L, 3L, 9L, 2L, 8L, 1L, 2L, 1L,
2L, 0L, 7L, 10L, 9L, 9L, 5L, 4L, 9L, 7L)

For example, in the first row, the first three cells remain unchanged and the other ones are set to 0.
As it is a large data-table, I look for an efficient way to do this

Body:
In order to avoid complexity, I've taken the reverse approach and first changed all the 1s to 0s. Then it's a double for loop to change the amount of columns indicated in index, to 1s:

library(data.table)

dt <- setnames(data.table(matrix(0,nrow=100, ncol=11)),as.character(c(0:10)))

index <- sample(c(0:11),100, replace=TRUE)

for(i in 1:length(index)) {
  if (index[i] > 0) {
    for(j in 1:index[i]) {
      dt[i,j] <- 1
    }
  }
}


问:
How to make a .jar out from an Android Studio project
I'm using AndroidStudio and I have this project as shown:

What is inside the blue circle is myLib. myLib also needs to use an external lib that is inside the red circle, and an apache package (green circle).

So I want to make this whole thing become a single .jar, so I can use it in another projects.

A step-by-step guide would be really appreciated, I'm a beginner in the developer world.

Thanks!

答:
```<code>task deleteJar(type: Delete) {
    delete 'libs/mylibrary.jar'
}

task exportjar(type: Copy) {
    from('build/intermediates/compile_library_classes/release/')
    into('libs/')
    include('classes.jar')
    rename('classes.jar', 'mylibrary.jar')
}

exportjar.dependsOn(deleteJar, build)
</code>```


答:
i didn't obtained any conversion […] why?

to_options does return a new hash with the keys symbolized, but you didn't use that new hash – each merely traverses the array and at the end returns the array.

If you want to pick up the blocks results as the new array element, you have to use map:

```<code>array.map { |c| c.to_options }    # or array.map(&:to_options)
</code>```

Alternatively there's to_options! (with a !) which would work along with each:

```<code>array.each { |c| c.to_options! }  # or array.each(&:to_options!)
</code>```

That's because to_options! modifies the hashes in-place.

Note that to_options is an alias for symbolize_keys which might be a little clearer.

Title: Convert an array of hash with symbols

Body:
I have an array of hashes:

[{'object' => 'ob1', 'quantity' => '2'}, {'object' => 'ob2', 'quantity' => '3'}, .....]

I want to convert it to symbolized form:

[{:object => 'ob1', :quantity => '2'}, {:object => 'ob2', :quantity => '3'}, .....]

tried with:

symbolized_array = array.each => { |c| c.to_options }

but i didn't obtained any conversion, the symbolized_array is same as array

why?

Body:
i didn't obtained any conversion […] why?

to_options does return a new hash with the keys symbolized, but you didn't use that new hash – each merely traverses the array and at the end returns the array.

If you want to pick up the blocks results as the new array element, you have to use map:

array.map { |c| c.to_options }    # or array.map(&:to_options)

Alternatively there's to_options! (with a !) which would work along with each:

array.each { |c| c.to_options! }  # or array.each(&:to_options!)

That's because to_options! modifies the hashes in-place.

Note that to_options is an alias for symbolize_keys which might be a little clearer.


问:
How do I generate a JWT token in Android
I want to generate a JWT token in Android. I have the following questions:

What would be the Gradle dependencies?

Can anybody provide some sample Java code for the generation of a JWT token?

答:
You have to add Dependency like :

```<code>dependencies {
    api 'io.jsonwebtoken:jjwt-api:0.10.5'
    runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.10.5'
    runtimeOnly('io.jsonwebtoken:jjwt-orgjson:0.10.5') {
        exclude group: 'org.json', module: 'json'
    }

}
</code>```

and in proguard rules:

```<code>keepattributes InnerClasses

-keep class io.jsonwebtoken.** { *; }
-keepnames class io.jsonwebtoken.* { *; }
-keepnames interface io.jsonwebtoken.* { *; }

-keep class org.bouncycastle.** { *; }
-keepnames class org.bouncycastle.** { *; }
-dontwarn org.bouncycastle.**
</code>```

you can find full docuenattion and sample from here :

https://github.com/jwtk/jjwt

Body:
You have to add Dependency like :

dependencies {
    api 'io.jsonwebtoken:jjwt-api:0.10.5'
    runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.10.5'
    runtimeOnly('io.jsonwebtoken:jjwt-orgjson:0.10.5') {
        exclude group: 'org.json', module: 'json'
    }

}

and in proguard rules:

keepattributes InnerClasses

-keep class io.jsonwebtoken.** { *; }
-keepnames class io.jsonwebtoken.* { *; }
-keepnames interface io.jsonwebtoken.* { *; }

-keep class org.bouncycastle.** { *; }
-keepnames class org.bouncycastle.** { *; }
-dontwarn org.bouncycastle.**

you can find full docuenattion and sample from here :

https://github.com/jwtk/jjwt


问:
Oracle ORA-12154: TNS: Could not resolve service name Error?
I am a SQL Server user .

I am on a project that is using oracle (which I rarely use)
I need to create an ODBC connection so I can access the some data via MS Access
I have a application on my machine called oraHome90. It seems to allow a configuration of something called a listener in a “net configuration utility”, I think that a “Local Net Service Name Configuration” needs to also be done.  The IT support gave me this information to set up the ODBC connection . I have tried every combination that I can think of. I can get past a test that successfully passes a test to “login“  to the oracle server database.  When I try to create the ODBC connection I get the following error: ORA-12154: TNS: Could not resolve service name.

Assuming that I want to start from scratch and the following information is supposed to allow for me to connect to the database….. Any suggestions or comment ? Note: ultimately the project will have a website .ASP page query the data, but I have to first prove that I can see the data using the ODBC connection via MS Access

```<code>Service name: SERVICENAME
HOST = HOST.XYZi.com
User Id: MYUSERID
Password: MYPASSWORD
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

'Oracle Connection
Dim ocst
Dim oconn

ocst = "Provider=OraOLEDB.Oracle;" & _
        "Data Source=DATASOURCE;" & _
        "User ID=CHIJXL;" & _
        "Password=password;"

set oconn = CreateObject("ADODB.Connection")
</code>```

答: I had a same problem and the same error was showing up. my TNSNAMES:ORA file was also good to go but apparently there was a problem due to firewall blocking the access. SO a good tip would be to make sure that firewall is not blocking the access to the datasource. </p>

OwnerDisplayName: Joe

ContentLicense: CC BY-SA 2.5

Body:
I am a SQL Server user .

I am on a project that is using oracle (which I rarely use)
I need to create an ODBC connection so I can access the some data via MS Access
I have a application on my machine called oraHome90. It seems to allow a configuration of something called a listener in a “net configuration utility”, I think that a “Local Net Service Name Configuration” needs to also be done.  The IT support gave me this information to set up the ODBC connection . I have tried every combination that I can think of. I can get past a test that successfully passes a test to “login“  to the oracle server database.  When I try to create the ODBC connection I get the following error: ORA-12154: TNS: Could not resolve service name.

Assuming that I want to start from scratch and the following information is supposed to allow for me to connect to the database….. Any suggestions or comment ? Note: ultimately the project will have a website .ASP page query the data, but I have to first prove that I can see the data using the ODBC connection via MS Access

Service name: SERVICENAME
HOST = HOST.XYZi.com
User Id: MYUSERID
Password: MYPASSWORD
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

'Oracle Connection
Dim ocst
Dim oconn

ocst = "Provider=OraOLEDB.Oracle;" & _
        "Data Source=DATASOURCE;" & _
        "User ID=CHIJXL;" & _
        "Password=password;"

set oconn = CreateObject("ADODB.Connection")


问:
AuthenticationMechanism return payload for 401 with JSON not HTML
I've implemented the HttpAuthenticationMechanism where in case the user is not authenticated we would like to return a 401 status HTTP response with a JSON payload. Currently we return context.responseUnauthorized which returns the correct status of the HTTP response as 401 but the payload is in HTML format Unauthorized.

答:
Try to set the header of the response with following line:</p>

```<code>response.setHeader("Content-Type", "application/json")
</code>```

Body:
Try to set the header of the response with following line:

response.setHeader("Content-Type", "application/json")


问:
Can I use multiple spring-boot containers with different JDK versions?
I am new to docker and just started playing around with it. I am working on spring-boot micro-service. I have a total of 5 micro-services and all of them are using JDK 8. I was wondering if I can run some of them with different JDK version e.g, OpenJDK 10. Is this possible to do? If yes how will a specify the dockerfile and docker-compose?</p>

答:
Yes, it is possible. You can you use like below:

```<code>DockerFile:
ARG JDK_Path
FROM $JDK_PATH
//rest of your docker file code
</code>```

Now build you Dockerfile with the following command:

```<code>docker build --build-arg JDK_PATH=/jdk8.0 image_1 .

docker build --build-arg JDK_PATH=/jdk10.0 image_2 .
</code>```

Body:
Yes, it is possible. You can you use like below:

DockerFile:
ARG JDK_Path
FROM $JDK_PATH
//rest of your docker file code

Now build you Dockerfile with the following command:

docker build --build-arg JDK_PATH=/jdk8.0 image_1 .

docker build --build-arg JDK_PATH=/jdk10.0 image_2 .


问:
Scala naming convention for Futures
What is the naming convention in Scala for function returning result wrapped in Future? I have seen code like:

```<code>getResult
getResultF
getResultFtr
</code>```

Or even

```<code>getResultFuture
</code>```

If there is no specific convention then I would like to know what is practiced more.

答:
I usually don't name methods returning Futures any differently. My reason is that this information is already present in the return type, and will be made clear by any decent IDE upon autocompletion.

One exception is in the presence of another similar method that doesn't return a Future but does everything synchronously. In that case, I like to clearly differentiate them:

```<code>def fooSync: A
def fooAsync: Future[A]
</code>```

That's a pattern I've seen in plenty of libraries.

Title: Scala naming convention for Futures

Body:
What is the naming convention in Scala for function returning result wrapped in Future? I have seen code like:

getResult
getResultF
getResultFtr

Or even

getResultFuture

If there is no specific convention then I would like to know what is practiced more.

Body:
I usually don't name methods returning Futures any differently. My reason is that this information is already present in the return type, and will be made clear by any decent IDE upon autocompletion.

One exception is in the presence of another similar method that doesn't return a Future but does everything synchronously. In that case, I like to clearly differentiate them:

def fooSync: A
def fooAsync: Future[A]

That's a pattern I've seen in plenty of libraries.


Title: replace values in data-table based on column number and separate index vector

Body:
Since you have dt full of 1's you can recreate the entire data.table by

library(data.table)

cols <- ncol(dt)
data.table(t(sapply(seq_len(nrow(dt)), function(i)
                   rep(c(1, 0), c(index[i], cols - index[i])))))

#     V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
# 1:  1  1  1  0  0  0  0  0  0   0   0
# 2:  1  1  1  1  0  0  0  0  0   0   0
# 3:  1  1  1  1  1  1  0  0  0   0   0
# 4:  1  1  1  1  1  1  1  1  1   1   0
# 5:  1  1  0  0  0  0  0  0  0   0   0
# 6:  1  1  1  1  1  1  1  1  1   1   0
# 7:  1  1  1  1  1  1  1  1  1   1   1
# 8:  1  1  1  1  1  1  1  0  0   0   0
# 9:  1  1  1  1  1  1  1  0  0   0   0
#10:  0  0  0  0  0  0  0  0  0   0   0
#....

compare it with first 10 index values

index[1:10]
# [1]  3  4  6 10  2 10 11  7  7  0


问:
Increase clickable area of slots behind Fullcalendar event
In week view of Fullcalendar.js, there is a small space to the right of the rightmost event (in each day/overlapping), so that the slots this event occupies may remain clickable. However, the space is pretty small by default. I need to make it bigger.

I inspected every element of the tables that conform a Fullcalendar (currently using version 2.5.0), but I can't seem to find the place where the width of this space is set. I'm beginning to think it's calculated from the events' width, but I'm uncertain.

Is there any way to increase this space in week view?

EDIT:

The only provided answer does not work as intended because it adds some space to the right of ALL overlapping events (If two or more events overlap, then the space is added between the overlapping events, and not just to the rightmost event, as desired.)

EDIT:
There is now an officially accepted answer that seems to be working.

答:
It is quite old but maybe it helps someone:
You can just set the event container margin</p>

```<code>.fc-ltr .fc-time-grid .fc-event-container {
    margin: 0 5.0% 0 2px;
}
</code>```

Body:
It is quite old but maybe it helps someone:
You can just set the event container margin

.fc-ltr .fc-time-grid .fc-event-container {
    margin: 0 5.0% 0 2px;
}


问:
How to customize the form of a work item type using code in Azure Devops?
Is it possible to customize a work item programmatically (through code) instead of using the UI (Process)? I want to add a button to create two specific work items, provided some conditions are fulfilled.

I tried to achieve the above requirement using UI. However, it doesn't seem to be possible.

答:
For processes using the Inheritance model. API’s for everything you need to create and manage a process through code. This includes work item types, pages, groups, fields, states, rules, etc. Check Work Item Tracking Process APIs at the following site:

https://learn.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-5.0

For Hosted XML processes. API’s for checking to see if the process exists, importing, and exporting a Hosted XML process. Check Work Item Tracking Process Template APIs.

More details, you could refer to the following blog:

https://devblogs.microsoft.com/devops/announcing-new-rest-apis-for-process-customization/


问:
problem with android GPS provider: too many updates
Although I set minTime to 10 seconds in the requestLocatioupdate method I still get new location in less than one second.

```<code> public class GpsActivity extends Activity {
LocationManager mLocationManager;
TextView mTextView;
int count;
     /** Called when the activity is first created. */
     @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mTextView = (TextView) findViewById(R.id.text);
        count = 0;
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0,mGpsLocationListener);
     }

     Handler mHandler = new Handler(){

         @Override
         public void handleMessage(Message msg){
             switch(msg.what){
             case 1:
                 mTextView.setText("new location count:"+count);
             }
         }
    };

    LocationListener mGpsLocationListener = new LocationListener(){

    @Override
    public void onLocationChanged(Location location) {
        count++;
        mHandler.sendEmptyMessage(1);

    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }

    };

}
</code>```

My program is written for android 2.2

Any idea?

Thanks in advance.

答:
you can set a distance .if not solve,youcan see :minTime         the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.
minDistance         the minimum distance interval for notifications, in meters

so i think the time not correct,if you hope update 10s,i think you should use Time andTimeTask,or handler. or you can look http://androidforums.com/developer-101/107085-proper-provider-parameter-requestlocationupdates.html

Body:
Although I set minTime to 10 seconds in the requestLocatioupdate method I still get new location in less than one second.

 public class GpsActivity extends Activity {
LocationManager mLocationManager;
TextView mTextView;
int count;
     /** Called when the activity is first created. */
     @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mTextView = (TextView) findViewById(R.id.text);
        count = 0;
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0,mGpsLocationListener);
     }

     Handler mHandler = new Handler(){

         @Override
         public void handleMessage(Message msg){
             switch(msg.what){
             case 1:
                 mTextView.setText("new location count:"+count);
             }
         }
    };

    LocationListener mGpsLocationListener = new LocationListener(){

    @Override
    public void onLocationChanged(Location location) {
        count++;
        mHandler.sendEmptyMessage(1);

    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }

    };

}

My program is written for android 2.2

Any idea?

Thanks in advance.


问:
How to scan classes for annotations?
I have a plain jane servlets web application, and some of my classes have the following annotations:

```<code>@Controller
@RequestMapping(name = "/blog/")
public class TestController {
..

}
</code>```

Now when my servlet applications starts up, I would like to get a list of all classes that have the @Controller annotation, and then get the value of the @RequestMapping annotation and insert it in a dictionary.

How can I do this?

I'm using Guice and Guava also, but not sure if that has any annotation related helpers.

答:
If you are using Spring,

It has something called a AnnotatedTypeScanner class.

This class internally uses

```<code>ClassPathScanningCandidateComponentProvider
</code>```

This class has the code for actual scanning of the classpath resources. It does this by using the class metadata available at runtime.

One can simply extend this class or use the same class for scanning. Below is the constructor definition.

```<code>   /**
     * Creates a new {@link AnnotatedTypeScanner} for the given annotation types.
     *
     * @param considerInterfaces whether to consider interfaces as well.
     * @param annotationTypes the annotations to scan for.
     */
    public AnnotatedTypeScanner(boolean considerInterfaces, Class<? extends Annotation>... annotationTypes) {

        this.annotationTypess = Arrays.asList(annotationTypes);
        this.considerInterfaces = considerInterfaces;
    }
</code>```

Title: How to scan classes for annotations?

Body:
I have a plain jane servlets web application, and some of my classes have the following annotations:

@Controller
@RequestMapping(name = "/blog/")
public class TestController {
..

}

Now when my servlet applications starts up, I would like to get a list of all classes that have the @Controller annotation, and then get the value of the @RequestMapping annotation and insert it in a dictionary.

How can I do this?

I'm using Guice and Guava also, but not sure if that has any annotation related helpers.

Body:
If you are using Spring,

It has something called a AnnotatedTypeScanner class.

This class internally uses

ClassPathScanningCandidateComponentProvider

This class has the code for actual scanning of the classpath resources. It does this by using the class metadata available at runtime.

One can simply extend this class or use the same class for scanning. Below is the constructor definition.

   /**
     * Creates a new {@link AnnotatedTypeScanner} for the given annotation types.
     *
     * @param considerInterfaces whether to consider interfaces as well.
     * @param annotationTypes the annotations to scan for.
     */
    public AnnotatedTypeScanner(boolean considerInterfaces, Class<? extends Annotation>... annotationTypes) {

        this.annotationTypess = Arrays.asList(annotationTypes);
        this.considerInterfaces = considerInterfaces;
    }


问:
how to add user define variable with some predefine integer in javascript?
I am trying to add user define number with some predefine integer. But I am getting the wrong output.

I have a user define the variable 'qdt'. suppose the value of qdt is '5000.00'.
I want to 2000 in qdt. I need output  7000.00 but I am getting '5000.002000'.

where I am doing wrong with the function? please help.

thank You.

```<code>    <script>
            function totalise() {
            var qtd   = document.getElementById('qt').value;
            var myCheck1 = document.getElementById('myCheck1');
            var myCheck2 = document.getElementById('myCheck2');
            if (myCheck1.checked == true){
            var qtd   = document.getElementById('qt').value;

            qtd = qtd + 2000;

            } else {
                    if (myCheck2.checked == true){
                         var qtd   = document.getElementById('qt').value;

                           qtd = qtd + 500;

                    }else{
                         var qtd   = document.getElementById('qt').value;
                    }
                    var qtd   = document.getElementById('qt').value;
            }
            document.getElementById('result').value = qtd ;
            }
    </script>
</code>```

答:
You need convert to number before add</p>

```<code>var qtd   = document.getElementById('qt').value;

qtd = parseFloat(qtd) + 500;
</code>```

Body:
You need convert to number before add

var qtd   = document.getElementById('qt').value;

qtd = parseFloat(qtd) + 500;