问:
Sort numbers then strings C#
I want to this list

```<code>A
B
C
111
11
123
1
42
5
</code>```

To be sorted

```<code>1
5
11
42
111
123
A
B
C
</code>```

By default, it sorts numbers like strings (So, it goes 1,11,111,123,42,5),
But I want to sort numbers like numbers, and than strings that are not numbers.

Is there clean solution to sort it like above?

It is a list of objects, and object has several properties, one of which is a this string.

答:
What you want is called Natural sort.

I once wrote some code for that:

```<code>public static class NaturalCompare
{
    public static int Compare(string first, string second, StringComparison comparison = StringComparison.Ordinal)
    {
        if (string.Compare(first, second, comparison) == 0)
        {
            return 0;
        }

        if (first == null)
        {
            return -1;
        }

        if (second == null)
        {
            return 1;
        }

        DateTime d1, d2;

        if (DateTime.TryParse(first, out d1) && DateTime.TryParse(second, out d2))
        {
            return d1.CompareTo(d2);
        }

        var pos1 = 0;
        var pos2 = 0;

        int result;
        do
        {
            bool isNum1, isNum2;

            var part1 = GetNext(first, ref pos1, out isNum1);
            var part2 = GetNext(second, ref pos2, out isNum2);

            if (isNum1 && isNum2)
            {
                result = long.Parse(part1).CompareTo(long.Parse(part2));
            }
            else
            {
                result = String.Compare(part1, part2, comparison);
            }
        } while (result == 0 && pos1 < first.Length && pos2 < second.Length);

        return result;
    }

    public static int CompareToNatural(this string first, string second, StringComparison comparison = StringComparison.Ordinal)
    {
        return Compare(first, second, comparison);
    }

    public static IOrderedEnumerable<TSource> OrderByNatural<TSource>(this IEnumerable<TSource> source, Func<TSource, string> keySelector)
    {
        return source.OrderBy(keySelector, new NatComparer());
    }

    public static IOrderedEnumerable<TSource> OrderByNaturalDescending<TSource>(this IEnumerable<TSource> source, Func<TSource, string> keySelector)
    {
        return source.OrderByDescending(keySelector, new NatComparer());
    }

    private sealed class NatComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            return NaturalCompare.Compare(x, y);
        }
    }

    private static string GetNext(string s, ref int index, out bool isNumber)
    {
        if (index >= s.Length)
        {
            isNumber = false;
            return "";
        }

        isNumber = char.IsDigit(s[index]);

        var start = index;
        while (index < s.Length && char.IsDigit(s[index]) == isNumber)
        {
            index++;
        }
        return s.Substring(start, index - start);
    }
}
</code>```

Title: Sort numbers then strings C#

Body:
I want to this list

A
B
C
111
11
123
1
42
5

To be sorted

1
5
11
42
111
123
A
B
C

By default, it sorts numbers like strings (So, it goes 1,11,111,123,42,5),
But I want to sort numbers like numbers, and than strings that are not numbers.

Is there clean solution to sort it like above?

It is a list of objects, and object has several properties, one of which is a this string.

Body:
What you want is called Natural sort.

I once wrote some code for that:

public static class NaturalCompare
{
    public static int Compare(string first, string second, StringComparison comparison = StringComparison.Ordinal)
    {
        if (string.Compare(first, second, comparison) == 0)
        {
            return 0;
        }

        if (first == null)
        {
            return -1;
        }

        if (second == null)
        {
            return 1;
        }

        DateTime d1, d2;

        if (DateTime.TryParse(first, out d1) && DateTime.TryParse(second, out d2))
        {
            return d1.CompareTo(d2);
        }

        var pos1 = 0;
        var pos2 = 0;

        int result;
        do
        {
            bool isNum1, isNum2;

            var part1 = GetNext(first, ref pos1, out isNum1);
            var part2 = GetNext(second, ref pos2, out isNum2);

            if (isNum1 && isNum2)
            {
                result = long.Parse(part1).CompareTo(long.Parse(part2));
            }
            else
            {
                result = String.Compare(part1, part2, comparison);
            }
        } while (result == 0 && pos1 < first.Length && pos2 < second.Length);

        return result;
    }

    public static int CompareToNatural(this string first, string second, StringComparison comparison = StringComparison.Ordinal)
    {
        return Compare(first, second, comparison);
    }

    public static IOrderedEnumerable<TSource> OrderByNatural<TSource>(this IEnumerable<TSource> source, Func<TSource, string> keySelector)
    {
        return source.OrderBy(keySelector, new NatComparer());
    }

    public static IOrderedEnumerable<TSource> OrderByNaturalDescending<TSource>(this IEnumerable<TSource> source, Func<TSource, string> keySelector)
    {
        return source.OrderByDescending(keySelector, new NatComparer());
    }

    private sealed class NatComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            return NaturalCompare.Compare(x, y);
        }
    }

    private static string GetNext(string s, ref int index, out bool isNumber)
    {
        if (index >= s.Length)
        {
            isNumber = false;
            return "";
        }

        isNumber = char.IsDigit(s[index]);

        var start = index;
        while (index < s.Length && char.IsDigit(s[index]) == isNumber)
        {
            index++;
        }
        return s.Substring(start, index - start);
    }
}


来源: stackexchange

问:
How to style resizers
You know those three lines in the bottom corner of a textarea / div that indicate it can be resized? The ones like these. I want to restyle this icon so the resize functionality of my div is much more obvious. Perhaps something like this. How do I remove these lines while retaining the resize functionality of my div?

I've tried googling and searching SO. The closest I found to someone else asking the same question was this guy, but the best answer suggested turning off resize altogether, which is not what I want.

答:
html

```<code><div class="form-group resizer">
                <div class="arrow-resizer-textarea"></div>
                <textarea id="mytextArea" class="form-control" placeholder="text here....."></textarea>
            </div>
</code>```

sass

```<code>textarea {
  position: relative;
  z-index: 1;
  min-width: 1141px;
  min-height: 58px;
}

.resizer {
  position: relative;
  display: inline-block;
  &:after {
    content: "";
    border-top: 8px solid #1c87c7;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    -webkit-transform: rotate(-45deg);
    z-index: 1;
    opacity: 0.5;
    position: absolute;
    bottom: 1px;
    right: -3px;
    pointer-events: none;
  }
}
.arrow-resizer-textarea {
  height: 0;
  width: 0;
  border-top: 8px solid #1c87c7;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  -webkit-transform: rotate(-45deg);
  position: absolute;
  bottom: 1px;
  right: -3px;
  pointer-events: none;
  z-index: 2;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to style resizers

Body:
html

<div class="form-group resizer">
                <div class="arrow-resizer-textarea"></div>
                <textarea id="mytextArea" class="form-control" placeholder="text here....."></textarea>
            </div>

sass

textarea {
  position: relative;
  z-index: 1;
  min-width: 1141px;
  min-height: 58px;
}

.resizer {
  position: relative;
  display: inline-block;
  &:after {
    content: "";
    border-top: 8px solid #1c87c7;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    -webkit-transform: rotate(-45deg);
    z-index: 1;
    opacity: 0.5;
    position: absolute;
    bottom: 1px;
    right: -3px;
    pointer-events: none;
  }
}
.arrow-resizer-textarea {
  height: 0;
  width: 0;
  border-top: 8px solid #1c87c7;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  -webkit-transform: rotate(-45deg);
  position: absolute;
  bottom: 1px;
  right: -3px;
  pointer-events: none;
  z-index: 2;
}


问:
how can implement Backward scheduling in TSQL
How can i create backward scheduling using TSQL. In my old system i have something like this. Is it possible to implement the same logic using TSQL?

Field Name: A-NEST BY

and here is the formula for A-NEST BY. note [A-CUT BY] is a date field

IF(weekday(datesub(A-CUT BY, 7)) = 7, datesub(datesub(A-CUT BY, 7),1),
  if(weekday(datesub(A-CUT BY, 7)) = 1, datesub(datesub(A-CUT BY, 7),2),
  datesub(A-CUT BY, 7)))

[A-CUT BY] is calculated date field which on the first line here IF(weekday(datesub(A-CUT BY, 7)) = 7, datesub(datesub(A-CUT BY, 7),1),   if the date is 7 thge seventh date or Saturday moves the schedule to Friday. if sunday or 1 move the schedule to Monday

weekday(date) or weekday(date,format):

Returns the day of week of a date. The second input is optional, but if given must be one of "number",
"name", or "abbrev". If "number" or omitted, the result will be a number, with 1 for Sunday, 2 for
Monday, up to 7 for Saturday. If "name", the result will be the word Sunday, Monday, etc. If "abbrev",
the result will be the word Sun, Mon, etc.

datesub(date, N)or datesub(date, N,unit):

Subtracts N days from date, that is, returns the date N days before the input date. If N is negative, it
will return the date N days after the input date. The third input is optional; if provided, it must be one of
years, months, days, hours, or minutes. If not provided, days will be assumed.

答:
I am totally guessing here because this question lacks any clarity. I think you just want to use a case expression. Here is an example of what I think you might want.

```<code>set datefirst 7 --Sunday

declare @ACUTBY datetime = getdate()

select
case datepart(WEEKDAY, @ACUTBY)
    when 1 then 2
    when 7 then 5
    else datepart(WEEKDAY, @ACUTBY)
end as [A-CUT BY]
</code>```

--EDIT--

SqlZim made an excellent suggestion to add datefirst to avoid any issues if using another language or the first day of the week is changed for whatever reason.

You can read more about DATEFIRST here. https://learn.microsoft.com/en-us/sql/t-sql/statements/set-datefirst-transact-sql

Body:
I am totally guessing here because this question lacks any clarity. I think you just want to use a case expression. Here is an example of what I think you might want.

set datefirst 7 --Sunday

declare @ACUTBY datetime = getdate()

select
case datepart(WEEKDAY, @ACUTBY)
    when 1 then 2
    when 7 then 5
    else datepart(WEEKDAY, @ACUTBY)
end as [A-CUT BY]

--EDIT--

SqlZim made an excellent suggestion to add datefirst to avoid any issues if using another language or the first day of the week is changed for whatever reason.

You can read more about DATEFIRST here. https://learn.microsoft.com/en-us/sql/t-sql/statements/set-datefirst-transact-sql


问:
Passing a file through a function in c
Now whenever i run this it opens up a "Make a file" tab and gives me an error saying something wrong with line 25 from that tab. Not sure if its the way im passing it through.

Another problem is if i name the file " Anything" it will appear is " A@@ "

Thank you
(closed the file  just to test it )

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void generateFile(char,FILE);
void inputFile(int,FILE);
void printFile();

int main(int argc, char** argv) {

    char fname;
    int max_num;

    srand(time(NULL));

    printf("Enter file name \n");
    scanf("%c", &fname);

    printf("Enter max_num \n");
    scanf("%d",&max_num);

    FILE *fp;

    generateFile(fname,*fp);
    inputFile(max_num,*fp);

    return 0;
}

void generateFile(char fname,FILE *fp){

    fp = fopen( &fname, "w");

    fprintf(fp,"Testing");

    return;
}

void inputFile(int max_num, FILE *fp){

    int i,array[25];

    for(i=0;i<max_num;i++){
        array[i] = rand() % 100 + 50;
        fprintf(fp,"%d\n",array[i]);

        fclose(fp);

    }

}
</code>```

答:
You are passing fp incorrectly. You can either pass-by-reference:

```<code>void generateFile(char *fname, FILE **fp)
    *fp = fopen(fname, "w");
    // Check for error....
    fprintf(*fp, "Testing");
    return;
}
</code>```

Usage: generateFile(fname, &fp);

Or, I prefer, have the function return a pointer:

```<code>FILE * void generateFile(char *fname) {
    FILE *fp = fopen(fname, "w");
    // Check for error....
    fprintf(fp, "Testing");
    return fp;
}
</code>```

Usage: FILE *fp = generateFile(fname);

And the name should be pass as a char *, or const char *.

Also, in the next call, just pass the pointer:

```<code>inputFile(max_num, fp);
</code>```

And, you should also check that the file was successfully opened.

And, remove fclose(fp); from the for loop else only the 1st write will succeed.

Title: Passing a file through a function in c

Body:
Now whenever i run this it opens up a "Make a file" tab and gives me an error saying something wrong with line 25 from that tab. Not sure if its the way im passing it through.

Another problem is if i name the file " Anything" it will appear is " A@@ "

Thank you
(closed the file  just to test it )

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void generateFile(char,FILE);
void inputFile(int,FILE);
void printFile();

int main(int argc, char** argv) {

    char fname;
    int max_num;

    srand(time(NULL));

    printf("Enter file name \n");
    scanf("%c", &fname);

    printf("Enter max_num \n");
    scanf("%d",&max_num);

    FILE *fp;

    generateFile(fname,*fp);
    inputFile(max_num,*fp);

    return 0;
}

void generateFile(char fname,FILE *fp){

    fp = fopen( &fname, "w");

    fprintf(fp,"Testing");

    return;
}

void inputFile(int max_num, FILE *fp){

    int i,array[25];

    for(i=0;i<max_num;i++){
        array[i] = rand() % 100 + 50;
        fprintf(fp,"%d\n",array[i]);

        fclose(fp);

    }

}

Body:
You are passing fp incorrectly. You can either pass-by-reference:

void generateFile(char *fname, FILE **fp)
    *fp = fopen(fname, "w");
    // Check for error....
    fprintf(*fp, "Testing");
    return;
}

Usage: generateFile(fname, &fp);

Or, I prefer, have the function return a pointer:

FILE * void generateFile(char *fname) {
    FILE *fp = fopen(fname, "w");
    // Check for error....
    fprintf(fp, "Testing");
    return fp;
}

Usage: FILE *fp = generateFile(fname);

And the name should be pass as a char *, or const char *.

Also, in the next call, just pass the pointer:

inputFile(max_num, fp);

And, you should also check that the file was successfully opened.

And, remove fclose(fp); from the for loop else only the 1st write will succeed.

ContentLicense: CC BY-SA 4.0


问:
Can't parse GET request using express
I read a lot about node, express and many useful modules.
I'm trying to parse GET HTTP request but I'm doing something wrong.

Maybe this problem could be solved using express.Router() and views engine but I would like to know WHY this code doesn't work?

Server is up and running! Public files are very well served BUT I cannot parse GET request.

```<code>app.use(express.static(path.join(__dirname, 'public')));

/*I would like to get req.session here*/
app.get('/', function (req, res, next) {
    console.log('I'm trying to log this string');
})
</code>```

I'm also using morgan to log all HTTP request and this is the output:

```<code>Listening at: http://localhost:8080
GET / 200 14.288 ms - 9139
GET /css/materialize.css 304 16.311 ms - -
GET /css/style.css 304 24.775 ms - -
GET /js/materialize.js 304 21.287 ms - -
GET /js/init.js 304 20.238 ms - -
GET /js/index.js 200 51.159 ms - 2719
GET /fonts/roboto/Roboto-Regular.woff2 304 2.419 ms - -
GET /fonts/roboto/Roboto-Medium.woff2 304 3.663 ms - -
GET /fonts/roboto/Roboto-Light.woff2 304 7.958 ms - -
GET /fonts/roboto/Roboto-Bold.woff2 304 9.010 ms - -
</code>```

It works commenting :

```<code>//app.use(express.static(path.join(__dirname, 'public')));
</code>```

But, obviously, no file are served.

Thank you!

PS: I never seen tutorial or code snippet explaining the situation described above.

答:
I'm guessing that you have a file called index.html in the public/ directory, which is the one that will get served when requesting /, because that's what express.static() does by default.

You can disable that behaviour, so the request will be passed to your / handler:

```<code>app.use(express.static(path.join(__dirname, 'public'), { index : false }));
</code>```

This is documented here.

Alternatively, you can make sure that the request hits the / handler by declaring it before the static middleware:

```<code>app.get('/', function (req, res, next) {
  console.log('I'm trying to log this string');
  // make sure to end the response, to prevent hanging requests.
  res.end();
});

app.use(express.static(path.join(__dirname, 'public')));
</code>```

Title: Can't parse GET request using express

Body:
I read a lot about node, express and many useful modules.
I'm trying to parse GET HTTP request but I'm doing something wrong.

Maybe this problem could be solved using express.Router() and views engine but I would like to know WHY this code doesn't work?

Server is up and running! Public files are very well served BUT I cannot parse GET request.

app.use(express.static(path.join(__dirname, 'public')));

/*I would like to get req.session here*/
app.get('/', function (req, res, next) {
    console.log('I'm trying to log this string');
})

I'm also using morgan to log all HTTP request and this is the output:

Listening at: http://localhost:8080
GET / 200 14.288 ms - 9139
GET /css/materialize.css 304 16.311 ms - -
GET /css/style.css 304 24.775 ms - -
GET /js/materialize.js 304 21.287 ms - -
GET /js/init.js 304 20.238 ms - -
GET /js/index.js 200 51.159 ms - 2719
GET /fonts/roboto/Roboto-Regular.woff2 304 2.419 ms - -
GET /fonts/roboto/Roboto-Medium.woff2 304 3.663 ms - -
GET /fonts/roboto/Roboto-Light.woff2 304 7.958 ms - -
GET /fonts/roboto/Roboto-Bold.woff2 304 9.010 ms - -

It works commenting :

//app.use(express.static(path.join(__dirname, 'public')));

But, obviously, no file are served.

Thank you!

PS: I never seen tutorial or code snippet explaining the situation described above.

Body:
I'm guessing that you have a file called index.html in the public/ directory, which is the one that will get served when requesting /, because that's what express.static() does by default.

You can disable that behaviour, so the request will be passed to your / handler:

app.use(express.static(path.join(__dirname, 'public'), { index : false }));

This is documented here.

Alternatively, you can make sure that the request hits the / handler by declaring it before the static middleware:

app.get('/', function (req, res, next) {
  console.log('I'm trying to log this string');
  // make sure to end the response, to prevent hanging requests.
  res.end();
});

app.use(express.static(path.join(__dirname, 'public')));


问:
ZooKeeper cluster of 2 nodes - strange behavior when one node is down programmatically
When I have two nodes operational, then everything works as expected

```<code>[dmitry@zk2-prod]/etc/supervisor.d% sudo /opt/zookeeper/bin/zkServer.sh status
ZooKeeper JMX enabled by default
Using config: /opt/zookeeper/bin/../conf/zoo.cfg
Mode: leader
</code>```

however as soon as I stop one of the nodes zk1-prod (via supervisord's supervisorctl)

```<code>[dmitry@zk2-prod]/etc/supervisor.d% sudo /opt/zookeeper/bin/zkServer.sh status
ZooKeeper JMX enabled by default
Using config: /opt/zookeeper/bin/../conf/zoo.cfg
Error contacting service. It is probably not running
</code>```

hoewever

```<code>[dmitry@zk2-prod]/etc/supervisor.d% sudo supervisorctl status
zookeeper                        RUNNING   pid 4838, uptime 0:04:01
</code>```

As soon as I bring the slave back - I'm immediately get first output (mode: leader)

```<code>[dmitry@zk2-prod]/etc/supervisor.d% ps aufx G zoo
89:zookeep+  4838  0.2  1.4 2970424 56816 ?       Sl   19:32   0:00  \_ java -Dzookeeper.log.dir=. -Dzookeeper.root.logger=INFO,CONSOLE -cp /opt/zookeeper/bin/../build/classes:/opt/zookeeper/bin/../build/lib/*.jar:/opt/zookeeper/bin/../lib/slf4j-log4j12-1.6.1.jar:/opt/zookeeper/bin/../lib/slf4j-api-1.6.1.jar:/opt/zookeeper/bin/../lib/netty-3.10.5.Final.jar:/opt/zookeeper/bin/../lib/log4j-1.2.16.jar:/opt/zookeeper/bin/../lib/jline-0.9.94.jar:/opt/zookeeper/bin/../zookeeper-3.4.10.jar:/opt/zookeeper/bin/../src/java/lib/*.jar:/opt/zookeeper/bin/../conf: -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.local.only=false org.apache.zookeeper.server.quorum.QuorumPeerMain /opt/zookeeper/bin/../conf/zoo.cfg
</code>```

Do I need 3 instances at least so org.apache.zookeeper.server.quorum.QuorumPeerMain can select a leader?

I thought one instance will be able to select itself as a leader and continue serve requests.

Am I missing something?

答:
Do I need 3 instances at least so
  org.apache.zookeeper.server.quorum.QuorumPeerMain can select a leader?

Yes, to tolerate the event of losing one server.

In a Zookeeper quorum, as long as majority of Servers are available the zookeeper service will be available. A server cannot elect itself as a leader.

In this case where 2 servers form the ensemble, 2 is the majority. When one is lost, the majority making member is lost along with it. Losing the majority is considered as the failure of the quorum.

A much easier to explain 3 server scenario, If one is lost still 2 remains to maintain the majority but in the event of losing 2, the majority making member in this 3-member quorum is lost which will lead to unavailability of zookeeper service.

Body:
When I have two nodes operational, then everything works as expected

[dmitry@zk2-prod]/etc/supervisor.d% sudo /opt/zookeeper/bin/zkServer.sh status
ZooKeeper JMX enabled by default
Using config: /opt/zookeeper/bin/../conf/zoo.cfg
Mode: leader

however as soon as I stop one of the nodes zk1-prod (via supervisord's supervisorctl)

[dmitry@zk2-prod]/etc/supervisor.d% sudo /opt/zookeeper/bin/zkServer.sh status
ZooKeeper JMX enabled by default
Using config: /opt/zookeeper/bin/../conf/zoo.cfg
Error contacting service. It is probably not running

hoewever

[dmitry@zk2-prod]/etc/supervisor.d% sudo supervisorctl status
zookeeper                        RUNNING   pid 4838, uptime 0:04:01

As soon as I bring the slave back - I'm immediately get first output (mode: leader)

[dmitry@zk2-prod]/etc/supervisor.d% ps aufx G zoo
89:zookeep+  4838  0.2  1.4 2970424 56816 ?       Sl   19:32   0:00  \_ java -Dzookeeper.log.dir=. -Dzookeeper.root.logger=INFO,CONSOLE -cp /opt/zookeeper/bin/../build/classes:/opt/zookeeper/bin/../build/lib/*.jar:/opt/zookeeper/bin/../lib/slf4j-log4j12-1.6.1.jar:/opt/zookeeper/bin/../lib/slf4j-api-1.6.1.jar:/opt/zookeeper/bin/../lib/netty-3.10.5.Final.jar:/opt/zookeeper/bin/../lib/log4j-1.2.16.jar:/opt/zookeeper/bin/../lib/jline-0.9.94.jar:/opt/zookeeper/bin/../zookeeper-3.4.10.jar:/opt/zookeeper/bin/../src/java/lib/*.jar:/opt/zookeeper/bin/../conf: -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.local.only=false org.apache.zookeeper.server.quorum.QuorumPeerMain /opt/zookeeper/bin/../conf/zoo.cfg

Do I need 3 instances at least so org.apache.zookeeper.server.quorum.QuorumPeerMain can select a leader?

I thought one instance will be able to select itself as a leader and continue serve requests.

Am I missing something?


问:
connect to SQL hosted on a local machine from my laptop (using an IP)
I set up an SQL server on my Windows 7 PC.

I have a laptop, from which I want to connect to the SQL server (using visual studio 2010).
I need to fill in a "server name" when creating a database connection.

I tried "My.IP.Address/SQLEXPRESS,custom-port", but that doesn't work. All examples talk about using server names which are formatted like so "TOM-PC/SQLEXPRESS", but I have an important requirement:

I want to be able to connect from anywhere (not only when in the same local network), therefore I'm trying to use the IP address (the port isn't simply 1433 since my ISP blocks it).

The custom port is open, and reachable in tests.

I've been Googling this all day long, but can't find a solution. Please help!

Thank you,

Tom

答: Have you tried using a wild card? For example let others access you through '%', since you want your computer to be accessed anywhere, your MySQL host is actually your IP address.</p>

ContentLicense: CC BY-SA 2.5


问:
SFTP connection returns "Auth cancel"
I'm using PhpStorm 2016.2.1, Windows 10. I'm trying to connect to remote host via SFTP. Credentials are correct. When I'm testing the connection, I have this error:

```<code>Connection to 'foobar.com' failed.
Auth cancel
</code>```

I can connect using FileZilla. I've cleared PhpStorm known_hosts. On different machines (PC, Mac) connection works perfect. Tried key pair auth, disable antivirus/firewall - same error. Traditional FTP connection on port 21 works perfect.

I have no idea what is wrong. Any ideas?

// update: 2017.1: same issue

答:
"Auth cancel" is a SSH error (and SFTP works over SSH), and it means that an authenticator failed critically (or all of them failed).

If at all possible, set debug to max (-vvv) on the server's SSHd and see what error it reports exactly. This way you'll be sure of what's really happenig.

Failing that, these are some random attempts:

Usually this is caused by a key mismatch, or by an authenticator that is not implemented correctly by the client. For example if PHPStorm's SSH auth using public-key or keyboard-interactive malfunctioned, and the server allowed it, and no other authenticators were available before that, you would get "Auth cancel", and to solve it you would need to:

either disable the failing auth module on the server (unless it is the last, in which case it would change nothing)

or change the order of authenticators in the client and/or server to ensure a working authenticator gets a chance to play first

One possibility is to try all authenticators one at a time, both on server and client, until you find one that works. Then put it first in the authenticator list on the server.

Update

I'm trying to set up a SFTP connection to a server in PHPStorm 2017.1:

```<code>Settings > Building, Execution, Deployment > Deployment > Options
</code>```

I create a new server ("Remote Server")

```<code>Connection tab:

Type: [ SFTP      ]

SFTP host: [ my host    ]
Port     : [ 22 ]
Root path: [ /var/www/default/htdocs ]
User name: [ lserni ]
Auth type: [ Password ]
Password : [ *********** ] [x] Save password
</code>```

and it worked (I needed to supply a password). You can set Auth type to "Key pair" and in that case PHPStorm asks for the private key (either in PuTTY or OpenSSH format - that's nice, as I use PuTTY on Windows; here you'll find how to generate both and convert between them. OpenSSH public keys are stored in /home/your-remote-user/.ssh/authorized_keys in the server) with its passphrase.

Possible causes of failure

Identity mismatch between local known_hosts (in Windows 7, it is C:\Users\YourName.ssh\known_hosts) and server identification. Solution: remove the known_hosts file on Windows. It will be correctly re-created at the next connection. I successfully recreated this by simply regenerating the server key.

Cipher mismatch between local PHPStorm and remote OpenSSH server. I had to pretty wreck the OpenSSH server to do this, but it can be done. Check out on the SSH server the line specifying ciphers (if there is none, then it is the default). Apparently my own PHPStorm uses AES-CBC-256, but it actually depends on the Java version that PHPStorm uses. See this answer for more info. Again, adding logging to the server SSHd should tell something useful:

```<code>LogLevel DEBUG3
Subsystem internal-sftp -l DEBUG3
</code>```

(comment them with # after you're done - syslog debug file is going to be appreciably massive).

If this is the problem you will get

```<code>no matching cipher found: client aes256-cbc server [everything but].
</code>```

Solution: set a shared Ciphers that work in sshd_config. In the case above, "aes256-cbc" must appear in the ciphers. Unfortunately what the ciphers are depends on client Java package, which may vary. I believe I have a vanilla install and it uses AES-256-CBC, so removing aes256-cbc made it fail, and putting it back made it work again. Some servers might prefer CTR by default, and not have CBC at all, and this might explain the failure. See this for more.

Title: SFTP connection returns "Auth cancel"

Body:
I'm using PhpStorm 2016.2.1, Windows 10. I'm trying to connect to remote host via SFTP. Credentials are correct. When I'm testing the connection, I have this error:

Connection to 'foobar.com' failed.
Auth cancel

I can connect using FileZilla. I've cleared PhpStorm known_hosts. On different machines (PC, Mac) connection works perfect. Tried key pair auth, disable antivirus/firewall - same error. Traditional FTP connection on port 21 works perfect.

I have no idea what is wrong. Any ideas?

// update: 2017.1: same issue

Body:
"Auth cancel" is a SSH error (and SFTP works over SSH), and it means that an authenticator failed critically (or all of them failed).

If at all possible, set debug to max (-vvv) on the server's SSHd and see what error it reports exactly. This way you'll be sure of what's really happenig.

Failing that, these are some random attempts:

Usually this is caused by a key mismatch, or by an authenticator that is not implemented correctly by the client. For example if PHPStorm's SSH auth using public-key or keyboard-interactive malfunctioned, and the server allowed it, and no other authenticators were available before that, you would get "Auth cancel", and to solve it you would need to:

either disable the failing auth module on the server (unless it is the last, in which case it would change nothing)

or change the order of authenticators in the client and/or server to ensure a working authenticator gets a chance to play first

One possibility is to try all authenticators one at a time, both on server and client, until you find one that works. Then put it first in the authenticator list on the server.

Update

I'm trying to set up a SFTP connection to a server in PHPStorm 2017.1:

Settings > Building, Execution, Deployment > Deployment > Options

I create a new server ("Remote Server")

Connection tab:

Type: [ SFTP      ]

SFTP host: [ my host    ]
Port     : [ 22 ]
Root path: [ /var/www/default/htdocs ]
User name: [ lserni ]
Auth type: [ Password ]
Password : [ *********** ] [x] Save password

and it worked (I needed to supply a password). You can set Auth type to "Key pair" and in that case PHPStorm asks for the private key (either in PuTTY or OpenSSH format - that's nice, as I use PuTTY on Windows; here you'll find how to generate both and convert between them. OpenSSH public keys are stored in /home/your-remote-user/.ssh/authorized_keys in the server) with its passphrase.

Possible causes of failure

Identity mismatch between local known_hosts (in Windows 7, it is C:\Users\YourName.ssh\known_hosts) and server identification. Solution: remove the known_hosts file on Windows. It will be correctly re-created at the next connection. I successfully recreated this by simply regenerating the server key.

Cipher mismatch between local PHPStorm and remote OpenSSH server. I had to pretty wreck the OpenSSH server to do this, but it can be done. Check out on the SSH server the line specifying ciphers (if there is none, then it is the default). Apparently my own PHPStorm uses AES-CBC-256, but it actually depends on the Java version that PHPStorm uses. See this answer for more info. Again, adding logging to the server SSHd should tell something useful:

LogLevel DEBUG3
Subsystem internal-sftp -l DEBUG3

(comment them with # after you're done - syslog debug file is going to be appreciably massive).

If this is the problem you will get

no matching cipher found: client aes256-cbc server [everything but].

Solution: set a shared Ciphers that work in sshd_config. In the case above, "aes256-cbc" must appear in the ciphers. Unfortunately what the ciphers are depends on client Java package, which may vary. I believe I have a vanilla install and it uses AES-256-CBC, so removing aes256-cbc made it fail, and putting it back made it work again. Some servers might prefer CTR by default, and not have CBC at all, and this might explain the failure. See this for more.


问:
WebGL shader checking status of texture sampler2D
I want to have prepared shader component (for multi sampler tex)

In my current state i use (activate and bind) only 2 texture image.

But this line :

```<code>gl_FragColor = textureColor + textureColor1 + textureColor2;
</code>```

Makes trouble with my texture view as the texture I sample textureColor2 from is not bound.

In shaders its not possible to use console.log or any other standard debugging methods.I am interested to learn more about shaders but i am stuck.

Code :

...

```<code>precision mediump float;

varying vec2 vTextureCoord;
varying vec3 vLightWeighting;

uniform sampler2D uSampler;
uniform sampler2D uSampler1;
uniform sampler2D uSampler2;
uniform sampler2D uSampler3;
uniform sampler2D uSampler4;
uniform sampler2D uSampler5;
uniform sampler2D uSampler6;
uniform sampler2D uSampler7;
uniform sampler2D uSampler8;
uniform sampler2D uSampler9;
uniform sampler2D uSampler10;
uniform sampler2D uSampler11;
uniform sampler2D uSampler12;
uniform sampler2D uSampler13;

void main(void) {

vec4 textureColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
vec4 textureColor1 = texture2D(uSampler1, vec2(vTextureCoord.s, vTextureCoord.t));
vec4 textureColor2 = texture2D(uSampler2, vec2(vTextureCoord.s, vTextureCoord.t));

// Need help here
gl_FragColor = textureColor + textureColor1 ;

//gl_FragColor = textureColor + textureColor1 + textureColor2;
</code>```

//UPDATED QUESTION

```<code>    if (  ${numTextures} == 1)
        {
            gl_FragColor = textureColor;
        }
    else if (${numTextures} == 2)
        {
            gl_FragColor = textureColor + textureColor1;
        }
    else if (${numTextures} == 3)
        {
            gl_FragColor = textureColor + textureColor1 + textureColor2;
        }
</code>```

// i use simple pragmatic if else for now .

// i pass value to the shader on load

// i still cant update shader in run time

///////////////////////////////////////

// This is segment of draw function :

```<code>for (var t=0;t<object.textures.length;t++) {

 eval( "  world.GL.gl.activeTexture(world.GL.gl.TEXTURE"+t+");  " )
    world.GL.gl.bindTexture(world.GL.gl.TEXTURE_2D, object.textures[t]);
    world.GL.gl.pixelStorei(world.GL.gl.UNPACK_FLIP_Y_WEBGL, false);
    world.GL.gl.texParameteri(world.GL.gl.TEXTURE_2D, world.GL.gl.TEXTURE_MAG_FILTER, world.GL.gl.NEAREST);
    world.GL.gl.texParameteri(world.GL.gl.TEXTURE_2D, world.GL.gl.TEXTURE_MIN_FILTER, world.GL.gl.NEAREST);
    world.GL.gl.texParameteri(world.GL.gl.TEXTURE_2D, world.GL.gl.TEXTURE_WRAP_S, world.GL.gl.CLAMP_TO_EDGE);
    world.GL.gl.texParameteri(world.GL.gl.TEXTURE_2D, world.GL.gl.TEXTURE_WRAP_T, world.GL.gl.CLAMP_TO_EDGE);
    // -- Allocate storage for the texture
    //world.GL.gl.texStorage2D(world.GL.gl.TEXTURE_2D, 1, world.GL.gl.RGB8, 512, 512);
    //world.GL.gl.texSubImage2D(world.GL.gl.TEXTURE_2D, 0, 0, 0, world.GL.gl.RGB, world.GL.gl.UNSIGNED_BYTE, image);
    //world.GL.gl.generateMipmap(world.GL.gl.TEXTURE_2D);
    world.GL.gl.uniform1i(object.shaderProgram.samplerUniform, t);

}
</code>```

...

Maybe in run time best way is to manipulate with object.textures array ?!

Finally :

Override shader with new flag

Compile shader
New material is updated

答:
What are you trying to accomplish?

The normal way to use lots of textures is to use a texture atlas which is covered toward the bottom of this article

Otherwise, no there is no way to detect if a texture is loaded in the shader. You need to pass in your own flags. For example

```<code> uniform bool textureLoaded[NUM_TEXTURES];
</code>```

or

```<code> uniform float textureMixAmount[NUM_TEXTURES];
</code>```

I'd use a texture atlas though if I were you unless you really know you're doing something unique that actually needs 14 textures.

It's also common to generate shaders on the fly. Pretty much all game engines do this. Three.js does it as well. So rather than turn textures on and off, write some code that generates a shader for N textures. Then when you only have one texture generate a 1 texture shader, when you have 2 generate a 2 texture shader, etc. That's far more efficient for the GPU than having a 14 texture shader and trying to turn off 13 textures.

Example:

// note, I'm not recommending this shader, only showing some code
// that generates a shader

function generateShaderSrc(numTextures) {

  return `
    // shader for ${numTextures} textures
    precision mediump float;

    varying vec2 vTextureCoord;
    varying vec3 vLightWeighting;

    uniform sampler2D uSampler[${numTextures}];
    uniform float uMixAmount[${numTextures}];

    void main() {
      vec4 color = vec4(0);

      for (int i = 0; i < ${numTextures}; ++i) {
        vec4 texColor = texture2D(uSampler[i], vTextureCoord);
        color = mix(color, texColor, uMixAmount[i]);
      }

      gl_FragColor = color;
    }
  `;
}

log(generateShaderSrc(1));
log(generateShaderSrc(4));

function log(...args) {
  const elem = document.createElement("pre");
  elem.textContent = [...args].join(' ');
  document.body.appendChild(elem);
}```

That's a pretty simple example. Real shader generators often do a whole lot more string manipulation.

You should also be aware WebGL 1.0 only requires support for 8 texture units. According to webglstats about 15% of devices only support 8 texture units so you probably want to check how many texture units the user has and warn them your app is not going to work if they have less than your app needs.

Body:
I want to have prepared shader component (for multi sampler tex)

In my current state i use (activate and bind) only 2 texture image.

But this line :

gl_FragColor = textureColor + textureColor1 + textureColor2;

Makes trouble with my texture view as the texture I sample textureColor2 from is not bound.

In shaders its not possible to use console.log or any other standard debugging methods.I am interested to learn more about shaders but i am stuck.

Code :

...

precision mediump float;

varying vec2 vTextureCoord;
varying vec3 vLightWeighting;

uniform sampler2D uSampler;
uniform sampler2D uSampler1;
uniform sampler2D uSampler2;
uniform sampler2D uSampler3;
uniform sampler2D uSampler4;
uniform sampler2D uSampler5;
uniform sampler2D uSampler6;
uniform sampler2D uSampler7;
uniform sampler2D uSampler8;
uniform sampler2D uSampler9;
uniform sampler2D uSampler10;
uniform sampler2D uSampler11;
uniform sampler2D uSampler12;
uniform sampler2D uSampler13;

void main(void) {

vec4 textureColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
vec4 textureColor1 = texture2D(uSampler1, vec2(vTextureCoord.s, vTextureCoord.t));
vec4 textureColor2 = texture2D(uSampler2, vec2(vTextureCoord.s, vTextureCoord.t));

// Need help here
gl_FragColor = textureColor + textureColor1 ;

//gl_FragColor = textureColor + textureColor1 + textureColor2;

//UPDATED QUESTION

    if (  ${numTextures} == 1)
        {
            gl_FragColor = textureColor;
        }
    else if (${numTextures} == 2)
        {
            gl_FragColor = textureColor + textureColor1;
        }
    else if (${numTextures} == 3)
        {
            gl_FragColor = textureColor + textureColor1 + textureColor2;
        }

// i use simple pragmatic if else for now .

// i pass value to the shader on load

// i still cant update shader in run time

///////////////////////////////////////

// This is segment of draw function :

for (var t=0;t<object.textures.length;t++) {

 eval( "  world.GL.gl.activeTexture(world.GL.gl.TEXTURE"+t+");  " )
    world.GL.gl.bindTexture(world.GL.gl.TEXTURE_2D, object.textures[t]);
    world.GL.gl.pixelStorei(world.GL.gl.UNPACK_FLIP_Y_WEBGL, false);
    world.GL.gl.texParameteri(world.GL.gl.TEXTURE_2D, world.GL.gl.TEXTURE_MAG_FILTER, world.GL.gl.NEAREST);
    world.GL.gl.texParameteri(world.GL.gl.TEXTURE_2D, world.GL.gl.TEXTURE_MIN_FILTER, world.GL.gl.NEAREST);
    world.GL.gl.texParameteri(world.GL.gl.TEXTURE_2D, world.GL.gl.TEXTURE_WRAP_S, world.GL.gl.CLAMP_TO_EDGE);
    world.GL.gl.texParameteri(world.GL.gl.TEXTURE_2D, world.GL.gl.TEXTURE_WRAP_T, world.GL.gl.CLAMP_TO_EDGE);
    // -- Allocate storage for the texture
    //world.GL.gl.texStorage2D(world.GL.gl.TEXTURE_2D, 1, world.GL.gl.RGB8, 512, 512);
    //world.GL.gl.texSubImage2D(world.GL.gl.TEXTURE_2D, 0, 0, 0, world.GL.gl.RGB, world.GL.gl.UNSIGNED_BYTE, image);
    //world.GL.gl.generateMipmap(world.GL.gl.TEXTURE_2D);
    world.GL.gl.uniform1i(object.shaderProgram.samplerUniform, t);

}

...

Maybe in run time best way is to manipulate with object.textures array ?!

Finally :

Override shader with new flag

Compile shader
New material is updated

Body:
What are you trying to accomplish?

The normal way to use lots of textures is to use a texture atlas which is covered toward the bottom of this article

Otherwise, no there is no way to detect if a texture is loaded in the shader. You need to pass in your own flags. For example

 uniform bool textureLoaded[NUM_TEXTURES];

or

 uniform float textureMixAmount[NUM_TEXTURES];

I'd use a texture atlas though if I were you unless you really know you're doing something unique that actually needs 14 textures.

It's also common to generate shaders on the fly. Pretty much all game engines do this. Three.js does it as well. So rather than turn textures on and off, write some code that generates a shader for N textures. Then when you only have one texture generate a 1 texture shader, when you have 2 generate a 2 texture shader, etc. That's far more efficient for the GPU than having a 14 texture shader and trying to turn off 13 textures.

Example:

// note, I'm not recommending this shader, only showing some code
// that generates a shader

function generateShaderSrc(numTextures) {

  return `
    // shader for ${numTextures} textures
    precision mediump float;

    varying vec2 vTextureCoord;
    varying vec3 vLightWeighting;

    uniform sampler2D uSampler[${numTextures}];
    uniform float uMixAmount[${numTextures}];

    void main() {
      vec4 color = vec4(0);

      for (int i = 0; i < ${numTextures}; ++i) {
        vec4 texColor = texture2D(uSampler[i], vTextureCoord);
        color = mix(color, texColor, uMixAmount[i]);
      }

      gl_FragColor = color;
    }
  `;
}

log(generateShaderSrc(1));
log(generateShaderSrc(4));

function log(...args) {
  const elem = document.createElement("pre");
  elem.textContent = [...args].join(' ');
  document.body.appendChild(elem);
}

That's a pretty simple example. Real shader generators often do a whole lot more string manipulation.

You should also be aware WebGL 1.0 only requires support for 8 texture units. According to webglstats about 15% of devices only support 8 texture units so you probably want to check how many texture units the user has and warn them your app is not going to work if they have less than your app needs.


问:
Finding out whether a TCP server has sent a data

I have a TCP server which writes data back to the client only for certain messages which the clients sends to the server.

It is basically is a command based server for which the server responds with a string only for certain commands otherwise nothing is sent back to the client.

The code given below is an approach which assumes that if any data is sent by the server it shows it as "MESSAGE FROM SERVER" appended with the data which was sent.

```<code>    class TcpEchoClient
    {
    static void Main(string[] args)
    {
    Console.WriteLine("Starting echo client...");

            string ipaddress = "127.0.0.1";
            TcpClient client = null;
            NetworkStream netstream = null;

            try
            {

                client = new TcpClient(ipaddress,1000);
                netstream = client.GetStream();

            }
            catch
            {
                Console.ReadKey();
                Environment.Exit(0);
            }

            while(true)
            {
                Console.WriteLine("Message :  ");
                string t = Console.ReadLine();
                string readdata = null;
                Console.WriteLine("\n");

                if (write(t,netstream))
                {
                    Console.WriteLine("Message sent.");

                    if (client.Available!=0)
                    {
                        readdata = read(netstream);
                        Console.WriteLine("MESSAGE FROM SERVER : "+readdata);
                    }

                }
                else
                {
                    Console.WriteLine("Unable to send message.");
                }
            }

        }

        static bool write(string dat, NetworkStream stream)
        {

            try
            {

                StreamWriter writer = new StreamWriter(stream) { AutoFlush = true };

                try{writer.WriteLine(dat);}
                catch (IOException){return false;}

                if (SHAHash(dat, "DATA") != SHAHash(read(stream), "DATA"))
                    return false;
            }catch (InvalidOperationException){return false;}

            return true;
        }

        static string read(NetworkStream stream)
        {

            StreamReader reader = new StreamReader(stream);

            string readdata = null;

            try
            {
                readdata = reader.ReadLine();
                reader.BaseStream.Flush();
            }
            catch(IOException)
            {
                return null;
            }

            return readdata;
        }
}
</code>```

The function SHAHash is not shown in this post. Its format is SHAHash(message,salt).

The problem faced is that messages sent by the server is not always read by the client. Sometimes the data sent by the server shows up a the client console, and sometimes it does not.

What correction should I make to the above code so that I can read data from the server only when it sends it. That is I require the following code to be executed only when the server sends some data to the client otherwise it should not be executed.

```<code>readdata = read(netstream);
Console.WriteLine("MESSAGE FROM SERVER : "+readdata);
</code>```

答:
Be prudent when using flush or autoflush. Sometimes it executes before send/receive operations... but this usually happens when working with threads.

My first tip that the stream readers/writers are not destructed properly. Try packing them into a using statement.

Body:
I have a TCP server which writes data back to the client only for certain messages which the clients sends to the server.

It is basically is a command based server for which the server responds with a string only for certain commands otherwise nothing is sent back to the client.

The code given below is an approach which assumes that if any data is sent by the server it shows it as "MESSAGE FROM SERVER" appended with the data which was sent.

    class TcpEchoClient
    {
    static void Main(string[] args)
    {
    Console.WriteLine("Starting echo client...");

            string ipaddress = "127.0.0.1";
            TcpClient client = null;
            NetworkStream netstream = null;

            try
            {

                client = new TcpClient(ipaddress,1000);
                netstream = client.GetStream();

            }
            catch
            {
                Console.ReadKey();
                Environment.Exit(0);
            }

            while(true)
            {
                Console.WriteLine("Message :  ");
                string t = Console.ReadLine();
                string readdata = null;
                Console.WriteLine("\n");

                if (write(t,netstream))
                {
                    Console.WriteLine("Message sent.");

                    if (client.Available!=0)
                    {
                        readdata = read(netstream);
                        Console.WriteLine("MESSAGE FROM SERVER : "+readdata);
                    }

                }
                else
                {
                    Console.WriteLine("Unable to send message.");
                }
            }

        }

        static bool write(string dat, NetworkStream stream)
        {

            try
            {

                StreamWriter writer = new StreamWriter(stream) { AutoFlush = true };

                try{writer.WriteLine(dat);}
                catch (IOException){return false;}

                if (SHAHash(dat, "DATA") != SHAHash(read(stream), "DATA"))
                    return false;
            }catch (InvalidOperationException){return false;}

            return true;
        }

        static string read(NetworkStream stream)
        {

            StreamReader reader = new StreamReader(stream);

            string readdata = null;

            try
            {
                readdata = reader.ReadLine();
                reader.BaseStream.Flush();
            }
            catch(IOException)
            {
                return null;
            }

            return readdata;
        }
}

The function SHAHash is not shown in this post. Its format is SHAHash(message,salt).

The problem faced is that messages sent by the server is not always read by the client. Sometimes the data sent by the server shows up a the client console, and sometimes it does not.

What correction should I make to the above code so that I can read data from the server only when it sends it. That is I require the following code to be executed only when the server sends some data to the client otherwise it should not be executed.

readdata = read(netstream);
Console.WriteLine("MESSAGE FROM SERVER : "+readdata);


问:
Converting RiotGames JSON API to PHP
I'm having an issue retrieving certain information from RiotGames API. The code shown below is me retrieving the wins and losses for game types (if available).

```<code><?php
    // get that summoner's wins and losses for each game type
    $result = file_get_contents('https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/' . $summoner->id . '/summary?api_key=' . $apiKey);
    $stats = json_decode($result);
    // var_dump($stats);
    foreach($stats->playerStatSummaries as $statSummary){
        // $statSummary->losses: sometimes losses isn't set
        $losses = property_exists($statSummary, 'losses')? $statSummary->losses : '(not available)';
        print '<p><b>' . $statSummary->playerStatSummaryType . '</b>: ' .
                $statSummary->wins . ' wins, ' . $losses . ' losses</p>';
    }
?>
</code>```

It fetches the wins and losses of Riot's API and returns it. But if I try to grab something different such as totalAssists from their aggregatedStats and replace wins with totalAssists it will return false with this error

"type 8 -- Undefined property: stdClass::$totalAssists -- at line 35"

Why does this not work? (You can find all the information of RiotsAPI by clicking here and then clicking the second "GET" under "STATS-V1.3"

答:
It might be possible that the total assists doesn't exist also.

You said if you "replace wins with totalAssists" that you get an error. You need to check to see if wins exists too.

Title: Converting RiotGames JSON API to PHP

Body:
I'm having an issue retrieving certain information from RiotGames API. The code shown below is me retrieving the wins and losses for game types (if available).

<?php
    // get that summoner's wins and losses for each game type
    $result = file_get_contents('https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/' . $summoner->id . '/summary?api_key=' . $apiKey);
    $stats = json_decode($result);
    // var_dump($stats);
    foreach($stats->playerStatSummaries as $statSummary){
        // $statSummary->losses: sometimes losses isn't set
        $losses = property_exists($statSummary, 'losses')? $statSummary->losses : '(not available)';
        print '
' . $statSummary->playerStatSummaryType . ': ' .
                $statSummary->wins . ' wins, ' . $losses . ' losses
';
    }
?>

It fetches the wins and losses of Riot's API and returns it. But if I try to grab something different such as totalAssists from their aggregatedStats and replace wins with totalAssists it will return false with this error

"type 8 -- Undefined property: stdClass::$totalAssists -- at line 35"

Why does this not work? (You can find all the information of RiotsAPI by clicking here and then clicking the second "GET" under "STATS-V1.3"


问:
deref an atom after recursive function completes
I have an atom fs that I'm updating inside a recursive function freq-seq that's the value that holds the results of my computation. I have another function mine-freq-seqs to start freq-seq and when mine-freq-seqs is done I would like to receive the last value of said atom. So I thought I would do it like so

```<code>(ns freq-seq-enum)

(def fs (atom #{}))

(defn locally-frequents
  [sdb min-sup]
  (let [uniq-sdb (map (comp frequencies set) sdb)
        freqs (apply merge-with + uniq-sdb)]
    (->> freqs
         (filter #(<= min-sup (second %)))
         (map #(vector (str (first %)) (second %))))))

(defn project-sdb
  [sdb prefix]
  (if (empty? prefix) sdb
                      (into [] (->> sdb
                           (filter #(re-find (re-pattern (str (last prefix))) %))
                           (map #(subs % (inc (.indexOf % (str (last prefix))))))
                           (remove empty?)))))

(defn freq-seq
  [sdb prefix prefix-support min-sup frequent-seqs]
  (if ((complement empty?) prefix) (swap! fs conj [prefix prefix-support]))
  (let [lf (locally-frequents sdb min-sup)]
(if (empty? lf) nil
                (for [[item sup] lf] (freq-seq (project-sdb sdb (str prefix item)) (str prefix item) sup min-sup @fs)))))

(defn mine-freq-seqs
  [sdb min-sup]
  (freq-seq sdb "" 0 min-sup @fs))
</code>```

running it first

```<code>(mine-freq-seqs ["CAABC" "ABCB" "CABC" "ABBCA"] 2)
</code>```

then deref-ing the atom
(deref fs)

yields

```<code>#{["B" 4]
  ["BC" 4]
  ["AB" 4]
  ["CA" 3]
  ["CAC" 2]
  ["AC" 4]
  ["ABC" 4]
  ["CAB" 2]
  ["A" 4]
  ["CABC" 2]
  ["ABB" 2]
  ["CC" 2]
  ["CB" 3]
  ["C" 4]
  ["BB" 2]
  ["CBC" 2]
  ["AA" 2]}
</code>```

however (doall (mine-freq-seqs ["CAABC" "ABCB" "CABC" "ABBCA"] 2) (deref fs))

just gives #{}

What I want is to let the freq-seq recurse to completion then get the value of the atom fs. So I can call mine-freq-seq and have my result returned in the REPL instead of having to manually deref it there.

答:
First some alternate code without the atom then a look at why you get the empty return.

A more compact version where the sequences in a string are derived with a reduce rather than the recursion with regex and substr.

Then just do a frequencies on those results.

```<code>(defn local-seqs
  [s]
  (->> s
       (reduce (fn [acc a] (into acc (map #(conj % a) acc))) #{[]})
       (map #(apply str %))
       (remove empty?)))

(defn freq-seqs
  [sdb min-sup]
  (->> (mapcat local-seqs sdb)
       frequencies
       (filter #(>= (second %) min-sup))
       set))
</code>```

That's the whole thing!
I haven't involved an atom because I didn't see a need but add it at the end if freq-seqs if you like.

For your original question: why the return that you see?

You are calling doall with 2 args, the result of your call and a collection.  doall is a function and not a macro so the deref is performed immediately.

```<code>(defn doall
   ;; <snip>
  ([n coll]        ;; you have passed #{} as coll
   (dorun n coll)  ;; and this line evals to nil
   coll)           ;; and #{} is returned
</code>```

You have passed your result as the n arg and an empty set as the coll (from (deref fs))

Now when doall calls dorun, it encounters the following:

```<code>(defn dorun
 ;; <snip>
([n coll]
 (when (and (seq coll) (pos? n)) ;; coll is #{} so the seq is falesy
   (recur (dec n) (next coll)))) ;; and a nil is returned
</code>```

Since the empty set from fs is the second arg (coll) and and is a macro, it will be falsey on (seq coll), return nil and then doall returns the empty set that was it's second arg.

Final note:

So that is something that works and why yours failed.  As to how to make yours work, to fix the call above I tried:

```<code>(do (doall (mine-freq-seqs ["CAABC" "ABCB" "CABC" "ABBCA"] 2))
    (deref fs))
</code>```

That is closer to working but with the recusion in your process, it only forces the eval one level deep.  So you could push the doall deeper into your funcs but I have proposed a completely different internal structure so I will leave the rest to you if you really need that structure.

Body:
I have an atom fs that I'm updating inside a recursive function freq-seq that's the value that holds the results of my computation. I have another function mine-freq-seqs to start freq-seq and when mine-freq-seqs is done I would like to receive the last value of said atom. So I thought I would do it like so

(ns freq-seq-enum)

(def fs (atom #{}))

(defn locally-frequents
  [sdb min-sup]
  (let [uniq-sdb (map (comp frequencies set) sdb)
        freqs (apply merge-with + uniq-sdb)]
    (->> freqs
         (filter #(<= min-sup (second %)))
         (map #(vector (str (first %)) (second %))))))

(defn project-sdb
  [sdb prefix]
  (if (empty? prefix) sdb
                      (into [] (->> sdb
                           (filter #(re-find (re-pattern (str (last prefix))) %))
                           (map #(subs % (inc (.indexOf % (str (last prefix))))))
                           (remove empty?)))))

(defn freq-seq
  [sdb prefix prefix-support min-sup frequent-seqs]
  (if ((complement empty?) prefix) (swap! fs conj [prefix prefix-support]))
  (let [lf (locally-frequents sdb min-sup)]
(if (empty? lf) nil
                (for [[item sup] lf] (freq-seq (project-sdb sdb (str prefix item)) (str prefix item) sup min-sup @fs)))))

(defn mine-freq-seqs
  [sdb min-sup]
  (freq-seq sdb "" 0 min-sup @fs))

running it first

(mine-freq-seqs ["CAABC" "ABCB" "CABC" "ABBCA"] 2)

then deref-ing the atom
(deref fs)

yields

#{["B" 4]
  ["BC" 4]
  ["AB" 4]
  ["CA" 3]
  ["CAC" 2]
  ["AC" 4]
  ["ABC" 4]
  ["CAB" 2]
  ["A" 4]
  ["CABC" 2]
  ["ABB" 2]
  ["CC" 2]
  ["CB" 3]
  ["C" 4]
  ["BB" 2]
  ["CBC" 2]
  ["AA" 2]}

however (doall (mine-freq-seqs ["CAABC" "ABCB" "CABC" "ABBCA"] 2) (deref fs))

just gives #{}

What I want is to let the freq-seq recurse to completion then get the value of the atom fs. So I can call mine-freq-seq and have my result returned in the REPL instead of having to manually deref it there.

Body:
First some alternate code without the atom then a look at why you get the empty return.

A more compact version where the sequences in a string are derived with a reduce rather than the recursion with regex and substr.

Then just do a frequencies on those results.

(defn local-seqs
  [s]
  (->> s
       (reduce (fn [acc a] (into acc (map #(conj % a) acc))) #{[]})
       (map #(apply str %))
       (remove empty?)))

(defn freq-seqs
  [sdb min-sup]
  (->> (mapcat local-seqs sdb)
       frequencies
       (filter #(>= (second %) min-sup))
       set))

That's the whole thing!
I haven't involved an atom because I didn't see a need but add it at the end if freq-seqs if you like.

For your original question: why the return that you see?

You are calling doall with 2 args, the result of your call and a collection.  doall is a function and not a macro so the deref is performed immediately.

(defn doall
   ;; <snip>
  ([n coll]        ;; you have passed #{} as coll
   (dorun n coll)  ;; and this line evals to nil
   coll)           ;; and #{} is returned

You have passed your result as the n arg and an empty set as the coll (from (deref fs))

Now when doall calls dorun, it encounters the following:

(defn dorun
 ;; <snip>
([n coll]
 (when (and (seq coll) (pos? n)) ;; coll is #{} so the seq is falesy
   (recur (dec n) (next coll)))) ;; and a nil is returned

Since the empty set from fs is the second arg (coll) and and is a macro, it will be falsey on (seq coll), return nil and then doall returns the empty set that was it's second arg.

Final note:

So that is something that works and why yours failed.  As to how to make yours work, to fix the call above I tried:

(do (doall (mine-freq-seqs ["CAABC" "ABCB" "CABC" "ABBCA"] 2))
    (deref fs))

That is closer to working but with the recusion in your process, it only forces the eval one level deep.  So you could push the doall deeper into your funcs but I have proposed a completely different internal structure so I will leave the rest to you if you really need that structure.


问:
Heroku always executes the dependancies check and slows down the push process
I am using the free version of heroku server. When ever i push to the heroku, I always get:

```<code>Gemfile detected, running Bundler version 1.0.0
</code>```

This happens even if I have not changed GemFile. Starting bundler on every push slows down the git push wasting effort. Any ideas on how to work around this are appreciated.

Thanks in advance !!!

答:
I much prefer spending one minute waiting on Heroku to run Bundler for me (and reject the push if installing the app fails).

The one minute Heroku spends running Bundler is preferable to to the hours upon hours I would have to spend doing manual dependency resolution on my local box and then SSHing into multiple servers and ensuring that the same exact versions of the gems are installed (and no others) on each of the servers.

Hopefully Heroku will upgrade their version of Bundler soon to take advantage of some of the performance improvements. But even if they don't, the benefit of Heroku + Bundler far outweighs the costs.

Body:
I am using the free version of heroku server. When ever i push to the heroku, I always get:

Gemfile detected, running Bundler version 1.0.0

This happens even if I have not changed GemFile. Starting bundler on every push slows down the git push wasting effort. Any ideas on how to work around this are appreciated.

Thanks in advance !!!


问:
How can I locate an Azure resource or setting creating empty WADMetrics Tables?
We have a resource constantly creating completely empty WADMetrics tables on a storage account. We have a significant amount of Azure resources and are unable to locate what is creating them since they are completely empty. It appears 2 tables are created every 10 days designed to store data in 1Hour and 5Min buckets.

How can we determine what is creating these tables?

答:
WAD stands for Windows Azure Diagnostics, which is probably enabled on a VM or other computing resource that uses this storage account for diagnostics.

You can read more here about WAD and specifically about WADMetrics table.

If you know what service is using this storage, you can simply disable Diagnostics.

Also, generally speaking, you can turn on storage diagnostics, specifically Table Service logs, to see who's creating those tables:

Go to Azure portal

Choose the relevant storage account.

On the left pane - click Diagnostics and check 'Table logs'.

A new container named '$logs' will be created in the storage account, containing all the logs you've enabled.

Those logs audit all the operations executed on this storage Azure tables.


问:
Clone SVN via PHP WebSVN over HTTP://
How may I clone/mirror a SVN repository that has no svn:// access but does have a private(forum-login) WebSVN viewer?</p>

答:
svn:// access, http:// access - its all the same, one gets passed through svnserve the other gets apssed through apache and mod_svn.

So to clone, you can use svnhotcopy, or svnsync. I like svnsync best as it will incrementally pull down changes - there's plenty of answers on SO describing how to set it up.

Soon there will be a svnadmin rdump which will remotely dump a repository but that'd not quite released yet. You could get it from the very latest svn repository and try it if you wanted to experiment.

OwnerDisplayName: Xaekai

Title: Clone SVN via PHP WebSVN over HTTP://


问:
Javascript with ajax values
Im trying to send email through ajax at my webiste. The form is in modal (im using custombox) But for some reasons every values that i have send are nulls.How can I use getElementById in modal content ?

Link to custombox git's hub : https://github.com/dixso/custombox

```<code>function _(id) { return document.getElementById(id);}
function submitForm() {
    _("mybtn").disabled = true;
    var formdata = new FormData();
    formdata.append( "n", _("n").value);
    formdata.append( "e", _("e").value);
    formdata.append( "m", _("m").value);
    var ajax = new XMLHttpRequest();
    ajax.open("POST","php/parser.php");
    ajax.onreadystatechange = function() {
        if(ajax.readyState == 4 && ajax.status == 200) {
            if(ajax.responseText == "success") {
                alert("Message has been send.");
            } else {
                btn.disabled = false;
            }
        }
    }
    ajax.send (formdata);
}
</code>```

HTML :

```<code>    <!-- Modal -->
    <section class="modal" id="myModal">
        <!-- Modal content-->
        <div class="modal-content" id="modal-content">
            <img class="modal-home-logo" src="img/logo.png" alt="logo">
            <p id="modal-contact-title">Are you intrested in cooperation?</p>
            <p id="modal-contact-sub-title">Just hit me up via this simple email form !</p>
            <form id="my_form" onsubmit="submitForm(); return false;">
                <p><input id="n" placeholder="Your name - HERE" required></p>
                <p><input id="e" placeholder="Your email - HERE" type="email" required> </p>
                <textarea id="m" placeholder="Tell me about your project... what is it? What do you hope to accomplish ? How can i help ? Oh try to ESC if missclicked :)" rows="10" required></textarea>
                <p><input id="mybtn" type="submit" value="Let's do this !"></p>
                <p id="modal-contact-sub-title">Awsome thanks !</p>
            </form>
        </div>

    </section>
    <!-- End Modal -->
</code>```

document.GetElementById returns the right HTML component but .value function is not working since it returns NULL. When i turn off my modal everything works just fine.

Well if you write document.GetElementById('n').value = "someText" in dev Console it works but document.GetElementById('n').value return null like always :(

Well i remove custombox plugin and made modal animations myself. So it is working now.

答: Well i remove custombox plugin and made modal animations myself. So it is working now.</p>

Title: Javascript with ajax values

Body:
Im trying to send email through ajax at my webiste. The form is in modal (im using custombox) But for some reasons every values that i have send are nulls.How can I use getElementById in modal content ?

Link to custombox git's hub : https://github.com/dixso/custombox

function _(id) { return document.getElementById(id);}
function submitForm() {
    _("mybtn").disabled = true;
    var formdata = new FormData();
    formdata.append( "n", _("n").value);
    formdata.append( "e", _("e").value);
    formdata.append( "m", _("m").value);
    var ajax = new XMLHttpRequest();
    ajax.open("POST","php/parser.php");
    ajax.onreadystatechange = function() {
        if(ajax.readyState == 4 && ajax.status == 200) {
            if(ajax.responseText == "success") {
                alert("Message has been send.");
            } else {
                btn.disabled = false;
            }
        }
    }
    ajax.send (formdata);
}

HTML :

Are you intrested in cooperation?

Just hit me up via this simple email form !

            <form id="my_form" onsubmit="submitForm(); return false;">

<input id="n" placeholder="Your name - HERE" required>

<input id="e" placeholder="Your email - HERE" type="email" required>

                <textarea id="m" placeholder="Tell me about your project... what is it? What do you hope to accomplish ? How can i help ? Oh try to ESC if missclicked :)" rows="10" required></textarea>

<input id="mybtn" type="submit" value="Let's do this !">

Awsome thanks !

            </form>

document.GetElementById returns the right HTML component but .value function is not working since it returns NULL. When i turn off my modal everything works just fine.

Well if you write document.GetElementById('n').value = "someText" in dev Console it works but document.GetElementById('n').value return null like always :(

Well i remove custombox plugin and made modal animations myself. So it is working now.


问:
Vector of vectors to 1D array
I was wondering if there is a clever way of presenting the information in a vector as a 1D array. Example:
Let's create a vector of vectors of 5x3 int elements

```<code>vector< vector<int>> iVector;
ivector.resize( 5 );
for(i = 0; i < 5; i++){
    iVector[i].resize(3);
}
</code>```

But now I want this structure to be converted into a 1D array:

```<code>int* myArray = new int[5*3];
</code>```

So I could access each element which I want as follows:

```<code>for (i =0;i < 5; i++)
  for(j =0; j< 3; j++)
      myArray[i*3+j] = ...
</code>```

I know I could just copy the vector to the array element by element, but I was wondering if there is a method that directly addresses the vector to array conversion. I also know that the vector can me addressed as iVector[i][j] , but unfortunately it needs to be an array as it will be sent to a GPU and GPUs dont understand vectors.

答:
Or you can use plain old C.

You first initialize the array size to be the number of rows * the number of columns your vector of vectors has. Then you use memcpy to copy each vector to the array.

```<code>vector<vector<int> > v = { {1,2},{3,4},{5,6} }; //v is 3 by 2 matrix
int *arr = (int*)malloc( (3*2) * sizeof(int)); // arr has size 3*2 = 6
for (int i = 0; i < 3; i++)
    memcpy(arr + v[i].size() * i, &(v[i][0]), v[i].size() * sizeof(int));
</code>```

Here's a function that I wrote that does this for you:

```<code>template<typename T>
T *vectorToArray(vector<vector<T> > const &v) {
    T *rv = (T*)malloc((v.size()*v[0].size()) * sizeof(T)); //Assuming all rows have the same size
    for (unsigned i = 0; i < v.size(); i++)
        memcpy(rv + v[i].size() * i, &(v[i][0]), v[i].size() * sizeof(T));
    return rv;
}
</code>```

So now you can do something like this:

```<code>vector<vector<int> > v = { {1,2},{3,4},{5,6} }; //v is 3 by 2 matrix
int *arr = vectorToArray(v);
</code>```

I hope this helps

Title: Vector of vectors to 1D array

Body:
I was wondering if there is a clever way of presenting the information in a vector as a 1D array. Example:
Let's create a vector of vectors of 5x3 int elements

vector< vector<int>> iVector;
ivector.resize( 5 );
for(i = 0; i < 5; i++){
    iVector[i].resize(3);
}

But now I want this structure to be converted into a 1D array:

int* myArray = new int[5*3];

So I could access each element which I want as follows:

for (i =0;i < 5; i++)
  for(j =0; j< 3; j++)
      myArray[i*3+j] = ...

I know I could just copy the vector to the array element by element, but I was wondering if there is a method that directly addresses the vector to array conversion. I also know that the vector can me addressed as iVector[i][j] , but unfortunately it needs to be an array as it will be sent to a GPU and GPUs dont understand vectors.

Body:
Or you can use plain old C.

You first initialize the array size to be the number of rows * the number of columns your vector of vectors has. Then you use memcpy to copy each vector to the array.

vector<vector<int> > v = { {1,2},{3,4},{5,6} }; //v is 3 by 2 matrix
int *arr = (int*)malloc( (3*2) * sizeof(int)); // arr has size 3*2 = 6
for (int i = 0; i < 3; i++)
    memcpy(arr + v[i].size() * i, &(v[i][0]), v[i].size() * sizeof(int));

Here's a function that I wrote that does this for you:

template<typename T>
T *vectorToArray(vector<vector<T> > const &v) {
    T *rv = (T*)malloc((v.size()*v[0].size()) * sizeof(T)); //Assuming all rows have the same size
    for (unsigned i = 0; i < v.size(); i++)
        memcpy(rv + v[i].size() * i, &(v[i][0]), v[i].size() * sizeof(T));
    return rv;
}

So now you can do something like this:

vector<vector<int> > v = { {1,2},{3,4},{5,6} }; //v is 3 by 2 matrix
int *arr = vectorToArray(v);

I hope this helps


问:
Embedded Tomcat in spring boot blocking some keywords
We are facing some issue with our spring boot application. we are using Embedded tomcat. when we hit couple of urls with the keywords having special characters, its not reaching our application. The application is hosted in google cloud. We are unable to reproduce this on local, but when he hit the same url in other environments , we can see the blank page. We checked by adding lot of logs in filters and our controllers, the request is not coming to our application it self. Can somebody help me with this issue.</p>

```<code>Example: www.test.com/s/5%2F8%20spark%20plug
</code>```

答:
as @chrylis mentioned, there isn't anything that you can do in your application to allow this type of URL to work, as the problem is before your application, and your application never gets the request.

I recommend that instead of spending a lot of time investigating why the Google Cloud platform is choking on the URLs, you take a hard look at your application and ask yourself if you really need these 'nonstandard' urls.

If,  for instance, "5%2F8%20spark%20plug" is something provided by an end-user (or a url-encoded version of something provided by an end-user), then perhaps it would be better to use an id (a Long or a UUID) instead - something that is "normalized" and known to not create a URL-parsing issue.

Body:
We are facing some issue with our spring boot application. we are using Embedded tomcat. when we hit couple of urls with the keywords having special characters, its not reaching our application. The application is hosted in google cloud. We are unable to reproduce this on local, but when he hit the same url in other environments , we can see the blank page. We checked by adding lot of logs in filters and our controllers, the request is not coming to our application it self. Can somebody help me with this issue.

Example: www.test.com/s/5%2F8%20spark%20plug


问:
Java Sorting a List whilst ignoring a apostrophe
I have a list that I am sorting which is reading from a CSV file.

Now when i sort the code I get:

But if I sort the CSV file on Excel it's slightly different

So technically Excel is ignoring the case of Apostrophe but mine isn't. The criteria doesn't specify what to do in this case, but I would assume my code is incorrect then. How would i ignore the case of the Apostrophe and go onto the next character?

My code is:

```<code>public static Comparator<Hill> compareName = new Comparator<Hill>() {
    public int compare(Hill one, Hill other) {
        return one.name.compareTo(other.name);
    }
};

public static void exercise5d() {
    List<Hill> hills = readHills();
    for (int i = 0; i < 20; i++) {
        Collections.sort(hills, Hill.compareName);
        System.out.println(hills.get(i));
    }

}
</code>```

答:
In your comparator,

replace

return one.name.compareTo(other.name);

with

return one.name.replaceAll("'","").compareTo(other.name.replaceAll("'",""));

Body:
I have a list that I am sorting which is reading from a CSV file.

Now when i sort the code I get:

But if I sort the CSV file on Excel it's slightly different

So technically Excel is ignoring the case of Apostrophe but mine isn't. The criteria doesn't specify what to do in this case, but I would assume my code is incorrect then. How would i ignore the case of the Apostrophe and go onto the next character?

My code is:

public static Comparator<Hill> compareName = new Comparator<Hill>() {
    public int compare(Hill one, Hill other) {
        return one.name.compareTo(other.name);
    }
};

public static void exercise5d() {
    List<Hill> hills = readHills();
    for (int i = 0; i < 20; i++) {
        Collections.sort(hills, Hill.compareName);
        System.out.println(hills.get(i));
    }

}


问:
OS X Django/Apache app not serving media files, works using python shell
I have a simple Django app that displays a bunch of thumbnails to videos. The first thing the app does is finds all of the thumbnail files in the MEDIA_ROOT. Everything else trickles down from that. I've got apache serving my site correctly, however it can't find the files in my media_root.

views.py:

```<code>def index(request):
    def walk_dir_tree(path, file_type):
        return[os.path.basename(x) for x in glob.glob(path + file_type,
                                                      recursive=True)]
    # Gets all .jpgs in media_root
    all_thumb_files = sorted(walk_dir_tree(
        settings.MEDIA_ROOT + 'thumbnails/**/*', '.jpg'), reverse=True)
...
return HttpResponse(template.render(context, request))
</code>```

relevant info from settings.py:

```<code># URLs
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

# Root Dirs:
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
# Dev
MEDIA_ROOT = '/Users/user/Documents/temp/secureDash/'
</code>```

http-vhosts.conf:

```<code><VirtualHost *:80>

    LogLevel debug

    ServerName securedash
    ServerAdmin <email>

    Alias /static /Users/user/icloud/projects/secureDash/static
    <Directory /Users/user/icloud/projects/secureDash/static>
        Require all granted
    </Directory>

    Alias /media /Users/user/Documents/temp/secureDash
    <Directory /Users/user/Documents/temp/secureDash>
        Require all granted
    </Directory>

    <Directory /Users/user/icloud/projects/secureDash/secureDash>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIDaemonProcess securedash python-path=/Users/user/icloud/projects/secureDash/secureDash python-home=/Users/user/Documents/VirtualEnvs/securedash
    WSGIProcessGroup securedash
    WSGIScriptAlias / /Users/user/icloud/projects/secureDash/secureDash/wsgi.py
</VirtualHost>
</code>```

As a test to ensure that the path to my media was correct, I wrote a quick script and ran it in the python3 shell:

```<code>MEDIA_ROOT = '/Users/user/Documents/temp/secureDash/'

def walk_dir_tree(path, file_type):
    return[os.path.basename(x) for x in glob.glob(path + file_type,
                                                  recursive=True)]

all_thumb_files = sorted(walk_dir_tree(
    MEDIA_ROOT + 'thumbnails/**/*', '.jpg'), reverse=True)

# prints a list of all jpgs
print(walk_dir_tree('/Users/user/Documents/temp/secureDash/thumbnails/**/*', '.jpg'))
# also prints a list of all jpgs
print(all_thumb_files)
</code>```

There are no errors logged anywhere. It just returns an empty list every time. I figure this is likely an issue with my settings.py or apache configuration but I've tried numerous combinations and nothing has worked.

I have this exact configuration working on my "production" server on my raspberry pi. I'm just trying to set up a dev environment that more closely matches the production one. Only differences are the OSs and MEDIA_ROOT locations.

Django 1.10 | OSX 10.11 El Capitan | Apache 2.4

答:
This ended up being a permission issue with /Users/user/Documents/temp/secureDash/, but what helped me work that out was the suggestion by @mithuntnt to glob a different folder. So I went back and globbed /Users/user/Documents which did return results. Then adding /temp which returned results. Then /secureDash which did not. I tried a different directory in /temp that was at the same level as /secureDash and that worked. So I checked the permissions on /secureDash and it was:

```<code>17276808 drwx------@  6 user  _www                           204B Mar 29 15:04 secureDash
</code>```

So I ran chmod -R 755 /Users/user/Documents/temp/secureDash/

And now the thumbnails are loading. Shouldn't I have seen file permission errors in the apache logs being that was the issue? I had LogLevel debug in http-vhosts.conf. What is a good LogLevel setting for a development environment?

Body:
I have a simple Django app that displays a bunch of thumbnails to videos. The first thing the app does is finds all of the thumbnail files in the MEDIA_ROOT. Everything else trickles down from that. I've got apache serving my site correctly, however it can't find the files in my media_root.

views.py:

def index(request):
    def walk_dir_tree(path, file_type):
        return[os.path.basename(x) for x in glob.glob(path + file_type,
                                                      recursive=True)]
    # Gets all .jpgs in media_root
    all_thumb_files = sorted(walk_dir_tree(
        settings.MEDIA_ROOT + 'thumbnails/**/*', '.jpg'), reverse=True)
...
return HttpResponse(template.render(context, request))

relevant info from settings.py:

# URLs
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

# Root Dirs:
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
# Dev
MEDIA_ROOT = '/Users/user/Documents/temp/secureDash/'

http-vhosts.conf:

<VirtualHost *:80>

    LogLevel debug

    ServerName securedash
    ServerAdmin <email>

    Alias /static /Users/user/icloud/projects/secureDash/static
    <Directory /Users/user/icloud/projects/secureDash/static>
        Require all granted
    </Directory>

    Alias /media /Users/user/Documents/temp/secureDash
    <Directory /Users/user/Documents/temp/secureDash>
        Require all granted
    </Directory>

    <Directory /Users/user/icloud/projects/secureDash/secureDash>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIDaemonProcess securedash python-path=/Users/user/icloud/projects/secureDash/secureDash python-home=/Users/user/Documents/VirtualEnvs/securedash
    WSGIProcessGroup securedash
    WSGIScriptAlias / /Users/user/icloud/projects/secureDash/secureDash/wsgi.py
</VirtualHost>

As a test to ensure that the path to my media was correct, I wrote a quick script and ran it in the python3 shell:

MEDIA_ROOT = '/Users/user/Documents/temp/secureDash/'

def walk_dir_tree(path, file_type):
    return[os.path.basename(x) for x in glob.glob(path + file_type,
                                                  recursive=True)]

all_thumb_files = sorted(walk_dir_tree(
    MEDIA_ROOT + 'thumbnails/**/*', '.jpg'), reverse=True)

# prints a list of all jpgs
print(walk_dir_tree('/Users/user/Documents/temp/secureDash/thumbnails/**/*', '.jpg'))
# also prints a list of all jpgs
print(all_thumb_files)

There are no errors logged anywhere. It just returns an empty list every time. I figure this is likely an issue with my settings.py or apache configuration but I've tried numerous combinations and nothing has worked.

I have this exact configuration working on my "production" server on my raspberry pi. I'm just trying to set up a dev environment that more closely matches the production one. Only differences are the OSs and MEDIA_ROOT locations.

Django 1.10 | OSX 10.11 El Capitan | Apache 2.4

Body:
This ended up being a permission issue with /Users/user/Documents/temp/secureDash/, but what helped me work that out was the suggestion by @mithuntnt to glob a different folder. So I went back and globbed /Users/user/Documents which did return results. Then adding /temp which returned results. Then /secureDash which did not. I tried a different directory in /temp that was at the same level as /secureDash and that worked. So I checked the permissions on /secureDash and it was:

17276808 drwx------@  6 user  _www                           204B Mar 29 15:04 secureDash

So I ran chmod -R 755 /Users/user/Documents/temp/secureDash/

And now the thumbnails are loading. Shouldn't I have seen file permission errors in the apache logs being that was the issue? I had LogLevel debug in http-vhosts.conf. What is a good LogLevel setting for a development environment?


问:
window border width and height in Win32 - how do I get it?
```
      ::GetSystemMetrics (SM_CYBORDER)
```

...comes back with 1 and I know the title bar is taller than ONE pixel :/

I also tried:

```
     RECT r;
      r.left = r.top = 0;   r.right = r.bottom = 400;
      ::AdjustWindowRect (& r, WS_OVERLAPPED, FALSE);
      _bdW = (uword)(r.right - r.left - 400);
      _bdH = (uword)(r.bottom - r.top - 400);
```

But border w,h came back as 0.

In my WM_SIZE handler, I need to make sure the window's height changes in
"steps" so, for example a whole new line of text could fit in the window
with no "junky partial line space" at the bottom.

But ::MoveWindow needs the dimensions WITH the border space added in.

SOMEbody must have done this before...
Thanks for any help :)

答: I think what you're looking for is SM_CYCAPTION -- that's the height of the title bar. SM_CYBORDER is the height of the horizontal edges of a window.

OwnerDisplayName: Stephen Hazel

Body:
      ::GetSystemMetrics (SM_CYBORDER)

...comes back with 1 and I know the title bar is taller than ONE pixel :/

I also tried:

     RECT r;
      r.left = r.top = 0;   r.right = r.bottom = 400;
      ::AdjustWindowRect (& r, WS_OVERLAPPED, FALSE);
      _bdW = (uword)(r.right - r.left - 400);
      _bdH = (uword)(r.bottom - r.top - 400);

But border w,h came back as 0.

In my WM_SIZE handler, I need to make sure the window's height changes in
"steps" so, for example a whole new line of text could fit in the window
with no "junky partial line space" at the bottom.

But ::MoveWindow needs the dimensions WITH the border space added in.

SOMEbody must have done this before...
Thanks for any help :)

OwnerDisplayName: Head Geek


问:
Windows EventLog: How fast are operations with it?
I have a service application that is processing client requests over TCP and writing any events into Windows EventLog. Since this application is expected to service many clients and lots of requests from each client in a short amount of time (let's say between 1 and 50 requests per second), I'm curious to know how intensive (CPU wise and time wise) and how fast can writing into Windows EventLog be?

More specifically, how intensive are the operations of connecting to, reading from and writing to EventLog?

答:
Don't do that. The event log is not designed for such an activity:

It has a maximum size.

When the maximum size is reached, it can overwrite events or stop logging, depending on settings (recent Windows can also archive the log and start a new one). If events are not overwritten, they can fill your partition or block other applications until the logs are manually cleared.

The event log is not a general logging facility. It should be used to report errors, situations that needs attention, and even informative reports, but not every little bit of information one has to write somewhere. If you have heavt log needs, use your own log facilities and report issues - if any - in the event log with a "pointer" where to find detailed data if needed.

NOTE: if really the event log is needed, at least the application should use its own log destination, not one of the standard ones (application or even worse system). This way it won't impact other applications operations, and won't "hide" other application events "flooding" the log with its events, making more difficult to spot the others without looking for them.


问:
How can I programmatically create a Firebase project?
Is it possible to create a Firebase project in my account without having to do it through the console?  Can I do it with an API?  I didn't see anything about it in the docs.

I want to use Firebase for my SaaS project, but I use Firebase for authentication.  I don't want to keep all the users in one project.

答:
This is not currently possible. I'd encourage you to file a feature request with a detailed use case.

For what it's worth, it most likely will never be possible to spin up a project for each customer of a SaaS product (unless customers are in the 10s).

The Firebase Management API launched at the Firebase Developer Summit in October 2018, and can be used to (among other things) create Firease projects by adding Firebase to existing Google Cloud Platform projects.


问:
Merge continuous 15-min time series dataset with discontinuous 15-min time series dataset
Pretty new to R, I appreciate any help you can give me on this issue.

I have two 15-min time series datasets that I would like to merge.  I would like to then plot a combination of variables from this merged dataset on a common x-axis. Here’s the catch, one of the datasets is missing values/dates.  Let’s call the datasets A and B.

A has a date-time column formatted as posixlt and 14 numeric variables (related to water quality).  Readings are at 15 minute intervals.  However, the time series is incomplete, some readings, due to equipment error are missing.
B also has a 15-minute interval date-time column formatted as posixlt and 1 numeric variable. However this series is continuous i.e. no missing data.

Here is a shortened example but the data covers about 6 months, with this problem repeated randomly throughout (notice data A is missing the 2:45 reading):

```<code>Temp Turb            DATETIME                 Q            DATETIME
1   21    5 2017-03-19 02:00:00             1 3 2017-03-19 02:00:00
2   15    5 2017-03-19 02:15:00             2 3 2017-03-19 02:15:00
3   18    5 2017-03-19 02:30:00             3 3 2017-03-19 02:30:00
4   17   17 2017-03-19 03:00:00             4 5 2017-03-19 02:45:00
5   18    5 2017-03-19 03:15:00             5 7 2017-03-19 03:00:00
6   17    5 2017-03-19 03:30:00             6 6 2017-03-19 03:15:00
7   17    6 2017-03-19 03:45:00             7 4 2017-03-19 03:30:00
                                            8 3 2017-03-19 03:45:00
</code>```

Here is the code for the shortened example.

```<code>A<- data.frame("DATE" =c("3/19/17","3/19/17","3/19/17","3/19/17",
                        "3/19/17","3/19/17","3/19/17"), "TIME"=c("02:00:00","02:15:00",
                         "02:30:00","03:00:00","03:15:00","03:30:00","03:45:00"),
                        "Temp" = c(21,15,18,17,18,17,17), "Turb" = c(5,5,5,17,5,5,6))
                          A$DATETIME <-paste(A$DATE,A$TIME)
                         A$DATETIME <- strptime(A$DATETIME, "%m/%d/%y %H:%M:%S")
                         A<-subset( A, select = -c(DATE,TIME) )
B <- data.frame("DATE" =c("3/19/17","3/19/17","3/19/17","3/19/17",
                        "3/19/17","3/19/17","3/19/17","3/19/17"), "TIME"=c("02:00:00","02:15:00",
                         "02:30:00","02:45:00","03:00:00","03:15:00","03:30:00","03:45:00"),
                         "Q" = c(3,3,3,5,7,6,4,3))
                          B$DATETIME <-paste(B$DATE,B$TIME)
                          B$DATETIME <- strptime(B$DATETIME, "%m/%d/%y %H:%M:%S")
                         B<-subset( B, select = -c(DATE,TIME) )
</code>```

I was hoping to use padr to fill in missing data in A with blanks so that the numeric variables from A and B could be interchangeably plotted with the time of A and B. Unfortunately 15 minutes is a nonstandard time interval for using padr. I have looked at stack overflow for examples and the closest I could find was here  but couldn’t make it work. It fleshed my dataset out to 1 minute data intervals but NA’s replaced all my numeric variables even at the 15-minute mark. Errors included statements such as DateTime variable was unsorted.

Any other recommendations or more specific guidance on the linked example? Thanks!!!

答:
Does a full_join give you the desired output? In the code below, we need to convert DATETIME to POSIXct format, but you can convert back after, if needed.

```<code>library(dplyr)

A$DATETIME = as.POSIXct(A$DATETIME)
B$DATETIME = as.POSIXct(B$DATETIME)

AB = full_join(A, B, by="DATETIME")  # a dplyr function
</code>```

```<code>  Temp Turb            DATETIME Q
1   21    5 2017-03-19 02:00:00 3
2   15    5 2017-03-19 02:15:00 3
3   18    5 2017-03-19 02:30:00 3
4   17   17 2017-03-19 03:00:00 7
5   18    5 2017-03-19 03:15:00 6
6   17    5 2017-03-19 03:30:00 4
7   17    6 2017-03-19 03:45:00 3
8   NA   NA 2017-03-19 02:45:00 5
</code>```

With base R, the equivalent would be:

```<code>AB = merge(A,B, by="DATETIME", all=TRUE)
</code>```

Body:
Pretty new to R, I appreciate any help you can give me on this issue.

I have two 15-min time series datasets that I would like to merge.  I would like to then plot a combination of variables from this merged dataset on a common x-axis. Here’s the catch, one of the datasets is missing values/dates.  Let’s call the datasets A and B.

A has a date-time column formatted as posixlt and 14 numeric variables (related to water quality).  Readings are at 15 minute intervals.  However, the time series is incomplete, some readings, due to equipment error are missing.
B also has a 15-minute interval date-time column formatted as posixlt and 1 numeric variable. However this series is continuous i.e. no missing data.

Here is a shortened example but the data covers about 6 months, with this problem repeated randomly throughout (notice data A is missing the 2:45 reading):

Temp Turb            DATETIME                 Q            DATETIME
1   21    5 2017-03-19 02:00:00             1 3 2017-03-19 02:00:00
2   15    5 2017-03-19 02:15:00             2 3 2017-03-19 02:15:00
3   18    5 2017-03-19 02:30:00             3 3 2017-03-19 02:30:00
4   17   17 2017-03-19 03:00:00             4 5 2017-03-19 02:45:00
5   18    5 2017-03-19 03:15:00             5 7 2017-03-19 03:00:00
6   17    5 2017-03-19 03:30:00             6 6 2017-03-19 03:15:00
7   17    6 2017-03-19 03:45:00             7 4 2017-03-19 03:30:00
                                            8 3 2017-03-19 03:45:00

Here is the code for the shortened example.

A<- data.frame("DATE" =c("3/19/17","3/19/17","3/19/17","3/19/17",
                        "3/19/17","3/19/17","3/19/17"), "TIME"=c("02:00:00","02:15:00",
                         "02:30:00","03:00:00","03:15:00","03:30:00","03:45:00"),
                        "Temp" = c(21,15,18,17,18,17,17), "Turb" = c(5,5,5,17,5,5,6))
                          A$DATETIME <-paste(A$DATE,A$TIME)
                         A$DATETIME <- strptime(A$DATETIME, "%m/%d/%y %H:%M:%S")
                         A<-subset( A, select = -c(DATE,TIME) )
B <- data.frame("DATE" =c("3/19/17","3/19/17","3/19/17","3/19/17",
                        "3/19/17","3/19/17","3/19/17","3/19/17"), "TIME"=c("02:00:00","02:15:00",
                         "02:30:00","02:45:00","03:00:00","03:15:00","03:30:00","03:45:00"),
                         "Q" = c(3,3,3,5,7,6,4,3))
                          B$DATETIME <-paste(B$DATE,B$TIME)
                          B$DATETIME <- strptime(B$DATETIME, "%m/%d/%y %H:%M:%S")
                         B<-subset( B, select = -c(DATE,TIME) )

I was hoping to use padr to fill in missing data in A with blanks so that the numeric variables from A and B could be interchangeably plotted with the time of A and B. Unfortunately 15 minutes is a nonstandard time interval for using padr. I have looked at stack overflow for examples and the closest I could find was here  but couldn’t make it work. It fleshed my dataset out to 1 minute data intervals but NA’s replaced all my numeric variables even at the 15-minute mark. Errors included statements such as DateTime variable was unsorted.

Any other recommendations or more specific guidance on the linked example? Thanks!!!

Body:
Does a full_join give you the desired output? In the code below, we need to convert DATETIME to POSIXct format, but you can convert back after, if needed.

library(dplyr)

A$DATETIME = as.POSIXct(A$DATETIME)
B$DATETIME = as.POSIXct(B$DATETIME)

AB = full_join(A, B, by="DATETIME")  # a dplyr function

  Temp Turb            DATETIME Q
1   21    5 2017-03-19 02:00:00 3
2   15    5 2017-03-19 02:15:00 3
3   18    5 2017-03-19 02:30:00 3
4   17   17 2017-03-19 03:00:00 7
5   18    5 2017-03-19 03:15:00 6
6   17    5 2017-03-19 03:30:00 4
7   17    6 2017-03-19 03:45:00 3
8   NA   NA 2017-03-19 02:45:00 5

With base R, the equivalent would be:

AB = merge(A,B, by="DATETIME", all=TRUE)