问:
Youtube data API v3, upload progression in progressBar
I am currently developing a software for a school project. in this software, I need to publish a video on YouTube (using YouTube data API v3), and to show the progression while doing so. I got an event that is being called each time the progression changes, and show it in the console. Because my application is a winForm, I need to show it in a progressBar (or something like this). And when I try to do this, it gives me an error:
"Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on."
I already tried to do this:

progressBar1.BeginInvoke(new MethodInvoker(delegate { progressBar1.Value = prog; }));

It doesn't give me an error, but it only show the progression at the end(when 100%), so I need a way to show during the process.

Here is the code that call the event:

```<code>            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = title[i];
            video.Snippet.Description = description[i];

            string[] tags = tag[i].Split(',');
            video.Snippet.Tags = tags;

            video.Snippet.CategoryId = category[i]; // See https://gist.github.com/dgp/1b24bf2961521bd75d6c
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = privacy[i]; // or "private" or "public" or "unlisted"
            var filePath = vidpath[i]; // Replace with path to actual movie file.

            current_vid = i;

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                const int KB = 0x400;
                var minimumChunkSize = 256 * KB;

                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
                // The default chunk size is 10MB, here will use 1MB.
                videosInsertRequest.ChunkSize = minimumChunkSize * 4;
                videosInsertRequest.Upload();
            }
</code>```

and here is the event:

```<code>        switch (progress.Status)
        {
            case UploadStatus.Uploading:
                progressBar1.BeginInvoke(new MethodInvoker(delegate { progressBar1.Value = Convert.ToInt32(progress.BytesSent * 100 / total_size); }));
                Console.WriteLine(progress.BytesSent * 100 / total_size);
                break;

            case UploadStatus.Failed:
                Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                break;
        }
</code>```

答:
The only way I was able to correct this problem, was by creating a console app, and showing the console, when I want to give the progression.

Thanks for your support.

Body:
I am currently developing a software for a school project. in this software, I need to publish a video on YouTube (using YouTube data API v3), and to show the progression while doing so. I got an event that is being called each time the progression changes, and show it in the console. Because my application is a winForm, I need to show it in a progressBar (or something like this). And when I try to do this, it gives me an error:
"Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on."
I already tried to do this:

progressBar1.BeginInvoke(new MethodInvoker(delegate { progressBar1.Value = prog; }));

It doesn't give me an error, but it only show the progression at the end(when 100%), so I need a way to show during the process.

Here is the code that call the event:

            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = title[i];
            video.Snippet.Description = description[i];

            string[] tags = tag[i].Split(',');
            video.Snippet.Tags = tags;

            video.Snippet.CategoryId = category[i]; // See https://gist.github.com/dgp/1b24bf2961521bd75d6c
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = privacy[i]; // or "private" or "public" or "unlisted"
            var filePath = vidpath[i]; // Replace with path to actual movie file.

            current_vid = i;

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                const int KB = 0x400;
                var minimumChunkSize = 256 * KB;

                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
                // The default chunk size is 10MB, here will use 1MB.
                videosInsertRequest.ChunkSize = minimumChunkSize * 4;
                videosInsertRequest.Upload();
            }

and here is the event:

        switch (progress.Status)
        {
            case UploadStatus.Uploading:
                progressBar1.BeginInvoke(new MethodInvoker(delegate { progressBar1.Value = Convert.ToInt32(progress.BytesSent * 100 / total_size); }));
                Console.WriteLine(progress.BytesSent * 100 / total_size);
                break;

            case UploadStatus.Failed:
                Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                break;
        }


来源: stackexchange

问:
'return outside of function' error with correct indentation?
in python, it comes out with 'return outside of function', I check the indentation is nothing wrong. any clue on that?</p>

```<code>dict={1:10,2:20,3:30}

for a,b in dict.items():
  if b==30:
    return a
</code>```

答:
There's no function, so you cannot use return. You may wrap the code in def:

```<code>d={1:10,2:20,3:30}

def return_30(d):
  for a,b in d.items():
    if b==30:
      return a
</code>```

Also I renamed dict to d, because dict is a name of the type, and when you redefine it you lose access to original dict.

ContentLicense: CC BY-SA 3.0

Body:
in python, it comes out with 'return outside of function', I check the indentation is nothing wrong. any clue on that?

dict={1:10,2:20,3:30}

for a,b in dict.items():
  if b==30:
    return a

Body:
There's no function, so you cannot use return. You may wrap the code in def:

d={1:10,2:20,3:30}

def return_30(d):
  for a,b in d.items():
    if b==30:
      return a

Also I renamed dict to d, because dict is a name of the type, and when you redefine it you lose access to original dict.


问:
Silverlight Memory Leaks
We have a rather large silverlight 4 application. We are in the process of finding memory leaks in the application and this has turned into a daunting task.

Things have changed completely with this one, for those of you that have seen the original post!

I realised that ANTS memory profiler wasn't showing me the right stuff. That was because the memory leak was not in the managed code, but in the native code. I did fix some issues with ANTS - it is a good tool for managed code memory leaks.

So I found this blog,

http://blogs.msdn.com/b/slperf/archive/2010/08/19/analyzing-silverlight-memory-usage-part-1-obtaining-measurements.aspx

Which was excellent. I used xPerf and xPerfViewer to view the native heap and see what I suspect is the actual memory leak.

So I can see a stack trace which looks like this,

```<code>CCoreServices::Draw
    CCoreServices::Tick
    CUElement::Render
        CUIElement::Render
        CUIElement::RenderWithTransform
        CUIElement::RenderVisual
        CUIElement::RenderChildren
            {Repeat of the above in a recursive fashion}
</code>```

So in this 'Render' method somewhere it allocates about 520 bytes of memory, and as far as I can tell it doesn't free it.

I can also see a method or class called

```<code>SDBitmapCreate
</code>```

is leaking memory too.

Interesting because it seems like I have found something, but I am not really sure what.

Any other suggestions?

Thanks.

答: There's a good tutorial on troubleshooting Silverlight memory leaks here: http://davybrion.com/blog/2009/08/finding-memory-leaks-in-silverlight-with-windbg/.  It's complicated, and you have to deal with WinDBG commands, but I've found it helpful in the past.  Of course, this doesn't answer your question specifically, but it may point you in the right direction.</p>

ContentLicense: CC BY-SA 2.5

Title: Silverlight Memory Leaks

Body:
We have a rather large silverlight 4 application. We are in the process of finding memory leaks in the application and this has turned into a daunting task.

Things have changed completely with this one, for those of you that have seen the original post!

I realised that ANTS memory profiler wasn't showing me the right stuff. That was because the memory leak was not in the managed code, but in the native code. I did fix some issues with ANTS - it is a good tool for managed code memory leaks.

So I found this blog,

http://blogs.msdn.com/b/slperf/archive/2010/08/19/analyzing-silverlight-memory-usage-part-1-obtaining-measurements.aspx

Which was excellent. I used xPerf and xPerfViewer to view the native heap and see what I suspect is the actual memory leak.

So I can see a stack trace which looks like this,

CCoreServices::Draw
    CCoreServices::Tick
    CUElement::Render
        CUIElement::Render
        CUIElement::RenderWithTransform
        CUIElement::RenderVisual
        CUIElement::RenderChildren
            {Repeat of the above in a recursive fashion}

So in this 'Render' method somewhere it allocates about 520 bytes of memory, and as far as I can tell it doesn't free it.

I can also see a method or class called

SDBitmapCreate

is leaking memory too.

Interesting because it seems like I have found something, but I am not really sure what.

Any other suggestions?

Thanks.


问:
How to remove lines from File A that are in File B in Windows command shell?
This other question is excellent for joining two files.  I need to do sort of the opposite.  I need to remove lines from File A that are in File B.

This question is similar to this other question, except that question is for unix and this is for the windows command shell (cmd.exe).

I would like to use tools that are native to Windows 7 Pro.

Update:

The files are hosts files.  Each one has lines consisting of:

127.0.0.1   host.domain.com

or

0.0.0.0   host.domain.com

or

# this is a comment

Files may have up to 200,000 lines.  Spaces and tabs may be present.

Although I prefer it to be preserved, order does not affect function.

Here are some examples of hosts files:

https://adaway.org/hosts.txt

https://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&mimetype=plaintext

https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts

https://hosts-file.net/ad_servers.txt

http://winhelp2002.mvps.org/hosts.txt

http://someonewhocares.org/hosts/hosts

(Don't worry about 0.0.0.0 vs '127.0.0.1` for this question.)

答:
```<code>findstr /v /x /g:"fileb" "filea">resultfile
</code>```

find strings in file A that do not (/v) exactly match (/x) those in fileb.

Body:
findstr /v /x /g:"fileb" "filea">resultfile

find strings in file A that do not (/v) exactly match (/x) those in fileb.


问:
Generating all variations of certain length out of string
I've seen few implementations of variations of string in C#, but none of them had any limitation on their length. Unfortunately, I cannot modify them to achieve my goal which is e.g.

for:

```<code>string = "ABCD" and variationLength = 2
</code>```

generate new strings:

```<code>AB, AC, AD, BA, BC, BD, CA, CB, CD, DA, DB, DC
</code>```

I'm looking for exactly this Python's itertools.permutations implementation but in C#. (https://docs.python.org/3/library/itertools.html#itertools.permutations)

Is there anything similar to its in C#? If not, then what is the easiest way to implement it?

Edit_2:
so far I came up with an idea to list all unique chars of given string and then get variations out of them

```<code>static void PrintAllKLengthPerm(string str, int k)
{
    int n = str.Length;
    PrintAllKLengthPermRec(str, "", n, k);
}

// The main recursive method to print all possible strings of length k
static void PrintAllKLengthPermRec(string str, String prefix, int n, int k)
{
    // Base case: k is 0, print prefix
    if (k == 0)
    {
        Console.WriteLine(prefix);
        return;
    }

    // One by one add all characters from str and recursively
    // call for k equals to k-1
    for (int i = 0; i < n; ++i)
    {
        // Next character of input added
        String newPrefix = prefix + str[i];

        // k is decreased, because we have added a new character
        PrintAllKLengthPermRec(str, newPrefix, n, k - 1);
    }
}

static void Main(string[] args)
{
    string str = "ABCD";
    int permLen = 2;

    //get all unique characters in string
    string uniqStr = new String(str.Distinct().ToArray());

    // Print all possible strings of length permLen out of uniqStr characters
    PrintAllKLengthPerm(uniqStr, permLen);
}
</code>```

However I am looking for more optimal and effective solution

答:
Here's a truly recursive permutation method:

```<code>public IEnumerable<string> Permutate(string source, int count)
{
    if (source.Length == 1)
    {
        yield return source;
    }
    else if (count == 1)
    {
        for (var n = 0; n < source.Length; n++)
        {
            yield return source.Substring(n, 1);
        }
    }
    else
    {
        for (var n = 0; n < source.Length; n++)
            foreach (var suffix in Permutate(
                source.Substring(0, n)
                    + source.Substring(n + 1, source.Length - n - 1), count -1))
            {
                yield return source.Substring(n, 1) + suffix;
            }
    }
}
</code>```

It can be called with Permutate("ABCD", 2) and returns this:

Body:
I've seen few implementations of variations of string in C#, but none of them had any limitation on their length. Unfortunately, I cannot modify them to achieve my goal which is e.g.

for:

string = "ABCD" and variationLength = 2

generate new strings:

AB, AC, AD, BA, BC, BD, CA, CB, CD, DA, DB, DC

I'm looking for exactly this Python's itertools.permutations implementation but in C#. (https://docs.python.org/3/library/itertools.html#itertools.permutations)

Is there anything similar to its in C#? If not, then what is the easiest way to implement it?

Edit_2:
so far I came up with an idea to list all unique chars of given string and then get variations out of them

static void PrintAllKLengthPerm(string str, int k)
{
    int n = str.Length;
    PrintAllKLengthPermRec(str, "", n, k);
}

// The main recursive method to print all possible strings of length k
static void PrintAllKLengthPermRec(string str, String prefix, int n, int k)
{
    // Base case: k is 0, print prefix
    if (k == 0)
    {
        Console.WriteLine(prefix);
        return;
    }

    // One by one add all characters from str and recursively
    // call for k equals to k-1
    for (int i = 0; i < n; ++i)
    {
        // Next character of input added
        String newPrefix = prefix + str[i];

        // k is decreased, because we have added a new character
        PrintAllKLengthPermRec(str, newPrefix, n, k - 1);
    }
}

static void Main(string[] args)
{
    string str = "ABCD";
    int permLen = 2;

    //get all unique characters in string
    string uniqStr = new String(str.Distinct().ToArray());

    // Print all possible strings of length permLen out of uniqStr characters
    PrintAllKLengthPerm(uniqStr, permLen);
}

However I am looking for more optimal and effective solution

Body:
Here's a truly recursive permutation method:

public IEnumerable<string> Permutate(string source, int count)
{
    if (source.Length == 1)
    {
        yield return source;
    }
    else if (count == 1)
    {
        for (var n = 0; n < source.Length; n++)
        {
            yield return source.Substring(n, 1);
        }
    }
    else
    {
        for (var n = 0; n < source.Length; n++)
            foreach (var suffix in Permutate(
                source.Substring(0, n)
                    + source.Substring(n + 1, source.Length - n - 1), count -1))
            {
                yield return source.Substring(n, 1) + suffix;
            }
    }
}

It can be called with Permutate("ABCD", 2) and returns this:


答:
The for loop, isn't a function.
A function in python is DEFined using the def keyword as in:

```<code>def function():
    print(1+2) # Im inside the function, return keyword here is valid

# I'm outside the function.
for x in range(10):
    print(x)
    #This is not a function, return keyword here is invalid.
</code>```

Title: 'return outside of function' error with correct indentation?

Body:
The for loop, isn't a function.
A function in python is DEFined using the def keyword as in:

def function():
    print(1+2) # Im inside the function, return keyword here is valid

# I'm outside the function.
for x in range(10):
    print(x)
    #This is not a function, return keyword here is invalid.


问:
Error printing a string
I'm creating a algorithm that generate numbers (numbers like strings) from 0 to 9999 and search its frequency in a array a[50000].

```<code>  char key[4];
  int freq;
  for (int i = 0; i < 10000; i++) {
    sprintf(key,"%04i",i); // save 4 digits in key, if i <1000 save leading 0's
    freq = BruteForceStringMatch(key,a,n); //n length of a.
    printf("%s-%i\n",key,freq);
  }
  free(a);
</code>```

but, when I run the program, I get it.

```<code>.
.
.
9845-7
9846
-10
9847-4
9848-5
-139
9850-3
9851-6
9852-5
9853-4
9854-2
9855-7
9856-5
9857-4
9858-5
9859    -9
9860-3

.
.
.
9968-6
9969    -9
9970-5
9971-4
9972-7
9973-6
9974-6
9975-2
9976-7
9977-4
9978-2
9979-7
9980-3
9981-4
9982-3
9983    -9
9984-6
9985-7
998-8
9987    -9
9988-3
9989    -9
9990-4
9991-3
9992-5
9993-2
9994    -9
9995-5
9996-6
9997-7
9998-7
</code>```

There are tabs in randoms position,sometimes the last digit of key is eliminated and there are 139,113,etc that I have no idea where they come from. I'm using gcc version 5.4.0 (GCC) and compile it with windows 10 and the terminal babun.

More information:

BruteForceStringMatch search the frequency of key in a.

```<code>int BruteForceStringMatch(char key[4], char* a, int length ){
  int freq=0;
  int k;
  for (int j = 0; j < length -4; j++) {
    k =0;
    while(k <4 && key[k] == a[j+k])
      k=k+1;
    if(k == 4)
        freq++;
  }
  return freq;
}
</code>```

I get a from a file with 5000 digits.

```<code>FILE *inputfile;
  char c;
  int largo = 0;
  char *a = (char *)malloc(50000*sizeof(char *));;
  char *b = (char *)malloc(50000*sizeof(char *));;
  inputfile = fopen("archivo_1.tex", "r");
  if (inputfile == NULL) {
      fprintf(stderr, "Failed to open the file.\n");
      exit(1);
  }
  if (inputfile) {
      for ( int i=0; (c = getc(inputfile)) != EOF; i++){
          a[i] = c;
          //putchar(a[i]);
          largo++;
      }
      fclose(inputfile);
  }
</code>```

答: It seems to me your problem is that you defined "key" to only be four chars, when it should be five -- four digits plus the terminating null.  So that null ends up in the first byte of "freq"... then when you set "freq" in line 5, that value gets seen by printf (on line 6) as part of the "key" string.  In particular, you can see this in the output for the values 9859 and 8859, where the value of "freq" happens to be 9, which is the ASCII code for a tab.  Also, for value 9846 and "freq" is 10, which happens to be the ASCII value for linefeed (i.e., newline), and on 9849, where "freq" is 13, which is a carriage return, so "-13" prints over the first three characters of 9849.

Title: Error printing a string

Body:
I'm creating a algorithm that generate numbers (numbers like strings) from 0 to 9999 and search its frequency in a array a[50000].

  char key[4];
  int freq;
  for (int i = 0; i < 10000; i++) {
    sprintf(key,"%04i",i); // save 4 digits in key, if i <1000 save leading 0's
    freq = BruteForceStringMatch(key,a,n); //n length of a.
    printf("%s-%i\n",key,freq);
  }
  free(a);

but, when I run the program, I get it.

.
.
.
9845-7
9846
-10
9847-4
9848-5
-139
9850-3
9851-6
9852-5
9853-4
9854-2
9855-7
9856-5
9857-4
9858-5
9859    -9
9860-3

.
.
.
9968-6
9969    -9
9970-5
9971-4
9972-7
9973-6
9974-6
9975-2
9976-7
9977-4
9978-2
9979-7
9980-3
9981-4
9982-3
9983    -9
9984-6
9985-7
998-8
9987    -9
9988-3
9989    -9
9990-4
9991-3
9992-5
9993-2
9994    -9
9995-5
9996-6
9997-7
9998-7

There are tabs in randoms position,sometimes the last digit of key is eliminated and there are 139,113,etc that I have no idea where they come from. I'm using gcc version 5.4.0 (GCC) and compile it with windows 10 and the terminal babun.

More information:

BruteForceStringMatch search the frequency of key in a.

int BruteForceStringMatch(char key[4], char* a, int length ){
  int freq=0;
  int k;
  for (int j = 0; j < length -4; j++) {
    k =0;
    while(k <4 && key[k] == a[j+k])
      k=k+1;
    if(k == 4)
        freq++;
  }
  return freq;
}

I get a from a file with 5000 digits.

FILE *inputfile;
  char c;
  int largo = 0;
  char *a = (char *)malloc(50000*sizeof(char *));;
  char *b = (char *)malloc(50000*sizeof(char *));;
  inputfile = fopen("archivo_1.tex", "r");
  if (inputfile == NULL) {
      fprintf(stderr, "Failed to open the file.\n");
      exit(1);
  }
  if (inputfile) {
      for ( int i=0; (c = getc(inputfile)) != EOF; i++){
          a[i] = c;
          //putchar(a[i]);
          largo++;
      }
      fclose(inputfile);
  }


问:
background-image isn't applying fully
I want that my background-image applies fully to the table borders, but it doesn't really work, it only applies to the center of the table borders.

It doesn't work without

border-collapse: separate;

So I don't know what else to do.
Yes, im a CSS and HTML beginner.

tbody {
  color: black;
}
th {
  color: black;
}

h1 {
  color: black;
}

.table, .table-bordered{
  border-spacing: 4px;
  border-collapse: separate;
  background-image: url('http://fs5.directupload.net/images/170604/sahdx5gv.png');
  background-size: 100% auto;
  background-repeat: repeat;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
  border: none;
  background-color: #fff;
}

Heres my HTML CODE:```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<!-- Latest compiled and minified CSS -->
<head>
<link rel="stylesheet" href="shitfuck.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<div class="container">
  <h1 class="text-center">OpSec Leaderboard</h1>
  <table class="table table-bordered"></br>
    <thead>

      <tr>

        <th>Place</th>
        <th>Username</th>
        <th>Rank</th>
        <th>Points</th>

      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>username</td>
        <td>rank</td>
        <td>1337</td>
      </tr>
      <tr>
        <td>2</td>
        <td>username</td>
        <td>rank</td>
        <td>1337</td>
      </tr>
      <tr>
        <td>3</td>
        <td>username</td>
        <td>rank</td>
        <td>1337</td>
      </tr>
    </tbody>
  </table>
</div>
</div></code>```

答:
You just want a solid background, so remove the background image properties and just use background-color: blue; or background: blue; for short.

tbody {
  color: black;
}
th {
  color: black;
}

h1 {
  color: black;
}

.table, .table-bordered{
  border-spacing: 4px;
  border-collapse: separate;
  /*
  background-image: url('http://fs5.directupload.net/images/170604/sahdx5gv.png');
  background-size: cover;
  background-repeat: repeat;
  background-position: center center;
  */
  background: blue;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
  border: none;
  background-color: #fff;
}

Heres my HTML CODE:```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<!-- Latest compiled and minified CSS -->
<head>
<link rel="stylesheet" href="shitfuck.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<div class="container">
  <h1 class="text-center">OpSec Leaderboard</h1>
  <table class="table table-bordered"></br>
    <thead>

      <tr>

        <th>Place</th>
        <th>Username</th>
        <th>Rank</th>
        <th>Points</th>

      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>username</td>
        <td>rank</td>
        <td>1337</td>
      </tr>
      <tr>
        <td>2</td>
        <td>username</td>
        <td>rank</td>
        <td>1337</td>
      </tr>
      <tr>
        <td>3</td>
        <td>username</td>
        <td>rank</td>
        <td>1337</td>
      </tr>
    </tbody>
  </table>
</div>
</div></code>```

Title: background-image isn't applying fully

Body:
I want that my background-image applies fully to the table borders, but it doesn't really work, it only applies to the center of the table borders.

It doesn't work without

border-collapse: separate;

So I don't know what else to do.
Yes, im a CSS and HTML beginner.

tbody {
  color: black;
}
th {
  color: black;
}

h1 {
  color: black;
}

.table, .table-bordered{
  border-spacing: 4px;
  border-collapse: separate;
  background-image: url('http://fs5.directupload.net/images/170604/sahdx5gv.png');
  background-size: 100% auto;
  background-repeat: repeat;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
  border: none;
  background-color: #fff;
}

Heres my HTML CODE:

<!DOCTYPE html>

<link rel="stylesheet" href="shitfuck.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

OpSec Leaderboard

        Place
        Username
        Rank
        Points

        1
        username
        rank
        1337

        2
        username
        rank
        1337

        3
        username
        rank
        1337

Body:
You just want a solid background, so remove the background image properties and just use background-color: blue; or background: blue; for short.

tbody {
  color: black;
}
th {
  color: black;
}

h1 {
  color: black;
}

.table, .table-bordered{
  border-spacing: 4px;
  border-collapse: separate;
  /*
  background-image: url('http://fs5.directupload.net/images/170604/sahdx5gv.png');
  background-size: cover;
  background-repeat: repeat;
  background-position: center center;
  */
  background: blue;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
  border: none;
  background-color: #fff;
}

Heres my HTML CODE:

<!DOCTYPE html>
<!-- Latest compiled and minified CSS -->
<head>
<link rel="stylesheet" href="shitfuck.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<div class="container">
  <h1 class="text-center">OpSec Leaderboard</h1>
  <table class="table table-bordered"></br>
    <thead>

      <tr>

        <th>Place</th>
        <th>Username</th>
        <th>Rank</th>
        <th>Points</th>

      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>username</td>
        <td>rank</td>
        <td>1337</td>
      </tr>
      <tr>
        <td>2</td>
        <td>username</td>
        <td>rank</td>
        <td>1337</td>
      </tr>
      <tr>
        <td>3</td>
        <td>username</td>
        <td>rank</td>
        <td>1337</td>
      </tr>
    </tbody>
  </table>
</div>
</div>


问:
Responsabilities in API gateway or specific service
I have a problem dividing responsibilities among services.

Example scenario

Imagine we have following reduced number of services, communicating each other via RabbitMQ:

API service. A single HTTP entry point for all business logic.

Users service. Which handles the users logic.

To implement the user creation feature: should I enforce the business restrictions in the API or in the users service?

For example, if only admins can create users with "isAdmin" property set up as true, the following options comes to my mind:

Tentative solutions

Checks in API service

API service checks if the user is authorized and if it is, send the operation to users service. operation to users service.

Advantages: Users service is more flexible. If other service want to create users in the future is not restrained to perform anything it wants (for example, create users without a "creator user"). Data is also validated early.

Disadvantages: If the business logic is too common I have to duplicate the checks in multiple points. I have the business logic of Users split

Checks in Users service

Users service checks the authorization and returns an error to API. API pass that error to client.

Do any good practice exists? Have you faced this dilemma before? How it worked?

答:
From Domain driven design perspective, the authorization should be a separate bounded context. Thus, the authorization checks should be done outside the Users administration  bounded context. So, in the simplest implementation, you could use some Api services that do the actual checking, called from the Application layer. If the current authenticated user has the required permission (for example CanCreateNewUsers) then the call to the Users administration bounded context is allowed, otherwise is rejected with an error.

A more complex/DDD solution would be to use an Anti-coruption layer between the two bounded contexts.

Btw, I suggest you to use permissions and not roles when you do the actual checking. You can use roles in the Authorization bounded context.


问:
How to take an input that is equal to 10 and perform a function that says awesome to the screen
I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.</p>

```<code>    <!DOCTYPE html>
    <html>

    <head>
        <title>Fizzbuzz Input Field</title>
        <script src="scripts.js"></script>
    </head>

    <body>
        <form>
            <input type="number" id="userInput"></input>
            <button onclick="fizzBuzz()">Go</button>
        </form>
    </body>

    </html>

    window.onload = function() {
        alert("Page is loaded");
    };

    var fizzBuzz = function() {
    var userInput = document.getElementById("userInput");
        fizzBuzz.onclick = function() {
        if(userInput.value == 10) {
            document.write("awesome");
        };
        };
    }
</code>```

答: I think what you are looking for is eval before using it, you should search the web for why eval is evil.

Body:
I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.

    <!DOCTYPE html>

        <title>Fizzbuzz Input Field</title>

        <form>
            <input type="number" id="userInput"></input>
            <button onclick="fizzBuzz()">Go</button>
        </form>

    window.onload = function() {
        alert("Page is loaded");
    };

    var fizzBuzz = function() {
    var userInput = document.getElementById("userInput");
        fizzBuzz.onclick = function() {
        if(userInput.value == 10) {
            document.write("awesome");
        };
        };
    }


问:
how to read SetEnv in PHP when calling from the command line?
What I like about Apache .conf files, and what is commonly used obviously is the SetEnv command.  However, when I run php artisan do:something from the command line, this same access to the .conf file appears to not be available (after all there is no "domain" or "website" understood from the command line).

In short, what is an alternate way to either read the same .conf file for the envvar's (ideal) or read from some file outside my codebase to differentiate environment (not ideal but certainly OK)?

答:
You can use .htaccess parser when running Your app.

```<code><?php
require_once 'vendor/autoload.php';

if(php_sapi_name() === 'cli') {
  $file = new \SplFileObject(__DIR__.'/.htaccess');
  $parser = new \Tivie\HtaccessParser\Parser();
  $htaccess = $parser->parse(null, IGNORE_WHITELINES|IGNORE_COMMENTS);

  foreach($htaccess AS $line) {
    if($line->getName() == 'SetEnv') {
      putenv($line->getArguments()[0], $line->getArguments()[1]);
    }
  }
}
</code>```

Just FYI In modern containerized world it's better to use environment variables that passed on script invocation or in container image directives.

Let's say this is Your script (test.php):

```<code><?php

if(getenv('PASSWORD') === 'blablabla') {
  // do something secret
  echo 'Psst... I have got a secret to share with You';
}
</code>```

And execute it like:

```<code>PASSWORD=blablabla php test.php
</code>```

how it looks in Dockerfile (part of it):

```<code>ENV MODE dev

CMD ['php', 'test.php']
</code>```

and in php code:

```<code>if(getenv('MODE') == 'dev') {
  // enable logger, debugger and etc...
}
</code>```

Body:
You can use .htaccess parser when running Your app.

<?php
require_once 'vendor/autoload.php';

if(php_sapi_name() === 'cli') {
  $file = new \SplFileObject(__DIR__.'/.htaccess');
  $parser = new \Tivie\HtaccessParser\Parser();
  $htaccess = $parser->parse(null, IGNORE_WHITELINES|IGNORE_COMMENTS);

  foreach($htaccess AS $line) {
    if($line->getName() == 'SetEnv') {
      putenv($line->getArguments()[0], $line->getArguments()[1]);
    }
  }
}

Just FYI In modern containerized world it's better to use environment variables that passed on script invocation or in container image directives.

Let's say this is Your script (test.php):

<?php

if(getenv('PASSWORD') === 'blablabla') {
  // do something secret
  echo 'Psst... I have got a secret to share with You';
}

And execute it like:

PASSWORD=blablabla php test.php

how it looks in Dockerfile (part of it):

ENV MODE dev

CMD ['php', 'test.php']

and in php code:

if(getenv('MODE') == 'dev') {
  // enable logger, debugger and etc...
}


问:
How do I encrypt a build step?
I need a secret token to be part of a command executed by Travis CI, but am in a public repository.  I found that I can encrypt parts of .travis.yml to keep secrets safe.  However, encrypting the command like in the following example fails saying Y95MgqDf...Bc=}: No such file or directory

after_deploy:
- secure: "Y95MgqDf...Bc="
```

答:
You don't encrypt the step. That does not appear to be supported by Travis.

Instead, encrypt only secret part:

$ travis encrypt TOKEN=verysecret
secure: "CnLZ...lI="
```

<p>Put the secret in an environment variable:</p>

<pre class="lang-yaml prettyprint-override"><code>env:
  global:
    secure: CnLZ...lI=
</code>```

Then dereference the environment variable when you need your secret.

after_deploy:
- mycommand $TOKEN
```

Title: How do I encrypt a build step?

Body:
You don't encrypt the step. That does not appear to be supported by Travis.

Instead, encrypt only secret part:

$ travis encrypt TOKEN=verysecret
secure: "CnLZ...lI="

Put the secret in an environment variable:

env:
  global:
    secure: CnLZ...lI=

Then dereference the environment variable when you need your secret.

after_deploy:
- mycommand $TOKEN


问:
Providing acces to issue tracker only in bitbuckets repository
Questions:

If I have a user group related to clients added to a repository with read access, would they be able to clone the repository on their local system?

If yes, what measures should I take to keep a group or user restricted to issue tracker only and not the code, means they should be able to create,update and close the issues but they should not be able to clone the repository, is there any way to do it, as I do not want the client to have access to the code until he has paid for the whole project.

答:
Bitbucket's permissions do not support what you want to do.

Users with read access can clone the repository:

View, clone, and fork the repository code. All public repositories grant all Bitbucket Cloud users read permissions automatically. Read access on a repository also allows users to create issues, comment on issues, and edit wiki pages.

There is no configuration that permits users to create and freely browse issues while restricting read access to the repository. The most likely setting would be private repository / public issue tracker, but in this case access to the issue tracker for users without repository access is restricted:

Only users who have access to the private repository can create an issue. Other Bitbucket users and any Internet browser can view the issue tracker if you publish the URL.

There may be other services that support your requirements.

ContentLicense: CC BY-SA 4.0


问:
How to Configure Unity in n-tier ASP .net MVC application
I am having a little problem figuring out how to configure Unity IoC container in my n-tier ASP .net MVC application.

I have 3 projects in my solution:
1. MVC (Used as View) : Has referene to Business Logic Layer only
2. Business Logic Layer: Has reference to Repository project only
3. Respository: Do not have reference to any of the above projects

Please notice the way my reference work, I have done it like this so I will be able to replace the communication between my tiers using WCF with less difficulties.

I have configured a Unity container in my MVC application doing something like this (Global.asax):

container.RegisterType(); //MyService is in my Business Logic Layer

The MyService class uses my repository in its constructor meaning that when one of those MyService classes is created a MyRepository is also required:

public MyService(IRepository repository) : base(repository)
 {       }

As you can see I still have not configured IRepository in my container.

I don't want to do it in my Global.asax because i dont want to add any reference of Repository to MVC (View) tier.

Where is the best place to configure this ? I am kind of confused here....

Thanks in advance.

答: Have you tried: http://mvcunity.codeplex.com/</p>


问:
Image width/height as an attribute or in CSS?
What's the "correct" semantic way to specify image height and width?  In CSS...

```<code>width:15px;
</code>```

or inline...

```<code><img width="15"
</code>```

?

CSS seems like the right place to put visual information.  On the other hand, few would argue that image "src" should not be specified as an attribute and the height/width seem as tied to the binary image data as the "src" is.

(Yes, I realize from a technical, end-user perspective this really doesn't matter.)

答:
Per the  article at MDN, the HTML attributes indicate the intrinsic dimensions of the image, i.e. its real dimensions. That's why, whereas HTML 4 also allowed percentage values, HTML5 only allows px values. (common pitfall: the "px" should not be written)

If you want to display the image with these dimensions, job done. Otherwise, you also have to add CSS to specify the display size.

Of course, it's better to serve the image in the displayed size, to avoid browser resizing, save bandwidth, etc. but that's not always possible.

See also the answers to this question: What's the difference between HTML's and CSS's width attribute?

OwnerDisplayName: Wayne Kao

Body:
What's the "correct" semantic way to specify image height and width?  In CSS...

width:15px;

or inline...

<img width="15"

?

CSS seems like the right place to put visual information.  On the other hand, few would argue that image "src" should not be specified as an attribute and the height/width seem as tied to the binary image data as the "src" is.

(Yes, I realize from a technical, end-user perspective this really doesn't matter.)

Body:
Per the <img> article at MDN, the HTML attributes indicate the intrinsic dimensions of the image, i.e. its real dimensions. That's why, whereas HTML 4 also allowed percentage values, HTML5 only allows px values. (common pitfall: the "px" should not be written)

If you want to display the image with these dimensions, job done. Otherwise, you also have to add CSS to specify the display size.

Of course, it's better to serve the image in the displayed size, to avoid browser resizing, save bandwidth, etc. but that's not always possible.

See also the answers to this question: What's the difference between HTML's and CSS's width attribute?


问:
Tomcat 8.5.4 SSL Empty Response
I recently renewed a Let's Encrypt certificate for a Tomcat server I have been running on Ubuntu.

After updating the keystore with the new fullchain.pem and restarting Tomcat, SSL requests return an empty response. Any non-SSL requests to port 80 work perfectly fine.

I created a keystore.jks with the password "password" and alias "tomcat", using the following commands:

```<code>openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem -out pkcs.p12 -name tomcat
keytool -importkeystore -deststorepass password -destkeypass password -destkeystore keystore.jks -srckeystore pkcs.p12 -srcstoretype PKCS12 -srcstorepass password -alias tomcat
</code>```

In my Tomcat's server.xml, I have two connectors enabled:

```<code>    <Connector port="80" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="443"
               address="serveraddress"
               maxHttpHeaderSize="65536"
                />
    <Connector port="443" protocol="HTTP/1.1"
               maxThreads="25" scheme="https" secure="true"
               SSLEnabled="true" keystorePass="password"
               keystoreFile="conf/keystore.jks" clientAuth="false"
               keyAlias="tomcat" sslProtocol="TLSv1.2"
               address="serveraddress"
               maxHttpHeaderSize="65536"
               />
</code>```

The curl request curl server.com succeeds, but curl server.com:443 returns an empty response. I have tried both curling externally and to the port when it's bound to localhost.

I have looked this up everywhere and I still can't figure out why it's happening. Any suggestions?

答:
You need to include the protocol HTTPS. curl https://server.com:443

The 443 is optional since it is the default port for HTTPS.

"If you specify URL without protocol:// prefix, curl will attempt to guess what protocol you might want. It will then default to HTTP but try other protocols based on often-used host name prefixes. For example, for host names starting with "ftp." curl will assume you want to speak FTP."

https://curl.haxx.se/docs/manpage.html

Title: Tomcat 8.5.4 SSL Empty Response

Body:
I recently renewed a Let's Encrypt certificate for a Tomcat server I have been running on Ubuntu.

After updating the keystore with the new fullchain.pem and restarting Tomcat, SSL requests return an empty response. Any non-SSL requests to port 80 work perfectly fine.

I created a keystore.jks with the password "password" and alias "tomcat", using the following commands:

openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem -out pkcs.p12 -name tomcat
keytool -importkeystore -deststorepass password -destkeypass password -destkeystore keystore.jks -srckeystore pkcs.p12 -srcstoretype PKCS12 -srcstorepass password -alias tomcat

In my Tomcat's server.xml, I have two connectors enabled:

    <Connector port="80" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="443"
               address="serveraddress"
               maxHttpHeaderSize="65536"
                />
    <Connector port="443" protocol="HTTP/1.1"
               maxThreads="25" scheme="https" secure="true"
               SSLEnabled="true" keystorePass="password"
               keystoreFile="conf/keystore.jks" clientAuth="false"
               keyAlias="tomcat" sslProtocol="TLSv1.2"
               address="serveraddress"
               maxHttpHeaderSize="65536"
               />

The curl request curl server.com succeeds, but curl server.com:443 returns an empty response. I have tried both curling externally and to the port when it's bound to localhost.

I have looked this up everywhere and I still can't figure out why it's happening. Any suggestions?


问:
Reverse Function Array String

Why is my reverse function not reversing my string back to Hello! when i am calling my function the second time?

What could i change to use my function to reverse + dereverse my string multiple times?

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

void reverse(char arr[], int numberOfChars);

int main()
{
    char myString[] = "Hello!";
    int length = strlen(myString);

    for (int i = 0; i < length; i++)
    {
        printf("%c", myString[i]);
    }
    printf("\n");

    reverse(myString, length);
    reverse(myString, length);

    getchar();
    return 0;
}

void reverse(char arr[], int numberOfChars)
{
    for (int i = numberOfChars - 1; i >= 0; i--)
    {
        printf("%c", arr[i]);
    }
    getchar();
}
</code>```

答:
If you want to reverse the words "Hello!", it is more convenient to define it as string and then use reverse(myString.begin(), myString.end()) orreverse(&myString[0], myString.length())

The parameter of the functionreverse(p1, p2) should be reverse(first_position, last_position)

Besides, if you really want to define the string as char, you should put them inside iteration and then reverse them one by one as @unwind said.

More details about the reverse function can be found at http://www.cplusplus.com/reference/algorithm/reverse/

Title: Reverse Function Array String

Body:
Why is my reverse function not reversing my string back to Hello! when i am calling my function the second time?

What could i change to use my function to reverse + dereverse my string multiple times?

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

void reverse(char arr[], int numberOfChars);

int main()
{
    char myString[] = "Hello!";
    int length = strlen(myString);

    for (int i = 0; i < length; i++)
    {
        printf("%c", myString[i]);
    }
    printf("\n");

    reverse(myString, length);
    reverse(myString, length);

    getchar();
    return 0;
}

void reverse(char arr[], int numberOfChars)
{
    for (int i = numberOfChars - 1; i >= 0; i--)
    {
        printf("%c", arr[i]);
    }
    getchar();
}


问:
Host C# rest service - Error on return type
I'm trying to host a Rest service i created in c#, deploying a .dll file and importing it in a new project with main method.

To create an host in the main I created an interface for my Rest service, but after the declaration of this interface i keep getting the error

"The name Content does not exist in the current context"

. Content is the return of my method, that should return only void or Task or Task T> because is async method.
How should I resolve this error?

This is part of the controller(Rest Service):

```<code>    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Net;
    using System.Net.Http.Headers;
    using System.Security.Cryptography;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Http;
    using System.ServiceModel;
    using Couchbase;
    using Couchbase.Core;
    using Couchbase.IO;
    using JWT;

    [ServiceContract]
    public interface ApiController
    {
        Task<IHttpActionResult> SignUp(LoginModel model);
    }

    namespace Nerder_Backend.Controllers
    {
        [RoutePrefix("api/user")]
        public class UserController : ApiController
        {
            private readonly IBucket _bucket = ClusterHelper.GetBucket(ConfigurationManager.AppSettings.Get("CouchbaseUserBucket"));
            private readonly string _secretKey = ConfigurationManager.AppSettings["JWTTokenSecret"];

            [Route("signup")]
            [HttpPost]
            public async Task<IHttpActionResult> SignUp(LoginModel model)
            {
                if (model == null || !model.IsValid())
                {
                    return Content(HttpStatusCode.BadRequest, new Error("Invalid email and/or password"));
                }

 var userKey = CreateUserKey(model.Email);
            if (await _bucket.ExistsAsync(userKey))
            {
                return Content(HttpStatusCode.Conflict, new Error($"email '{model.Email}' already exists"));
            }

            var userDoc = new Document<User>
            {
                Id = userKey,
                Content = new User
                {
                    Email = model.Email,
                    Password = CalcuateMd5Hash(model.Password)
                },
                Expiry = model.Expiry
            };

            var result = await _bucket.InsertAsync(userDoc);
            if (!result.Success)
            {
                return Content(HttpStatusCode.InternalServerError, new Error(result.Message));
            }

            var data = new
            {
                token = BuildToken(model.Email)
            };
            var context = $"Created user with ID '{userKey}' in bucket '{_bucket.Name}' that expires in {userDoc.Expiry}ms";
            return Content(HttpStatusCode.Accepted, new Result(data, context));
        }
</code>```

This is the main method :

```<code>namespace MockServer
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8080/signup");

            // Create the ServiceHost.
            using (ServiceHost host = new ServiceHost(typeof(UserController), baseAddress))
            {
                // Enable metadata publishing.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);

                // Open the ServiceHost to start listening for messages. Since
                // no endpoints are explicitly configured, the runtime will create
                // one endpoint per base address for each service contract implemented
                // by the service.
                host.Open();

                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                // Close the ServiceHost.
                host.Close();
            }
        }
    }
}
</code>```

答:
Update main to host the web api properly.

include the following using statements

```<code>using System.Web.Http;
using System.Web.Http.SelfHost; //install the nuget package Microsoft.AspNet.WebApi.SelfHost
</code>```

update Program class to Host the Web API

```<code>class Program {
    static void Main(string[] args) {
        var baseAddress = "http://localhost:8080";
        var config = new HttpSelfHostConfiguration(baseAddress);
        config.MapHttpAttributeRoutes();//map attribute routes
        // Create the server
        using (var server = new HttpSelfHostServer(config)) {
            server.OpenAsync().Wait();
            Console.WriteLine("The service is ready at {0}", baseAddress);
            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();
        }
    }
}
</code>```

Now make sure the api controller it correctly defined.

```<code>[RoutePrefix("api/user")]
public class UserController : ApiController {
    private readonly IBucket _bucket = ClusterHelper.GetBucket(ConfigurationManager.AppSettings.Get("CouchbaseUserBucket"));
    private readonly string _secretKey = ConfigurationManager.AppSettings["JWTTokenSecret"];
    [HttpPost]
    [Route("signup")] //Matches POST api/user/signup
    public async Task<IHttpActionResult> SignUp(LoginModel model) {

        //...code removed for brevity

    }
}
</code>```

Given the program set and controller attribute routes,  the action would be found at

POST http://localhost:8080/api/user/signup
```

Body:
I'm trying to host a Rest service i created in c#, deploying a .dll file and importing it in a new project with main method.

To create an host in the main I created an interface for my Rest service, but after the declaration of this interface i keep getting the error

"The name Content does not exist in the current context"

. Content is the return of my method, that should return only void or Task or Task T> because is async method.
How should I resolve this error?

This is part of the controller(Rest Service):

    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Net;
    using System.Net.Http.Headers;
    using System.Security.Cryptography;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Http;
    using System.ServiceModel;
    using Couchbase;
    using Couchbase.Core;
    using Couchbase.IO;
    using JWT;

    [ServiceContract]
    public interface ApiController
    {
        Task<IHttpActionResult> SignUp(LoginModel model);
    }

    namespace Nerder_Backend.Controllers
    {
        [RoutePrefix("api/user")]
        public class UserController : ApiController
        {
            private readonly IBucket _bucket = ClusterHelper.GetBucket(ConfigurationManager.AppSettings.Get("CouchbaseUserBucket"));
            private readonly string _secretKey = ConfigurationManager.AppSettings["JWTTokenSecret"];

            [Route("signup")]
            [HttpPost]
            public async Task<IHttpActionResult> SignUp(LoginModel model)
            {
                if (model == null || !model.IsValid())
                {
                    return Content(HttpStatusCode.BadRequest, new Error("Invalid email and/or password"));
                }

 var userKey = CreateUserKey(model.Email);
            if (await _bucket.ExistsAsync(userKey))
            {
                return Content(HttpStatusCode.Conflict, new Error($"email '{model.Email}' already exists"));
            }

            var userDoc = new Document<User>
            {
                Id = userKey,
                Content = new User
                {
                    Email = model.Email,
                    Password = CalcuateMd5Hash(model.Password)
                },
                Expiry = model.Expiry
            };

            var result = await _bucket.InsertAsync(userDoc);
            if (!result.Success)
            {
                return Content(HttpStatusCode.InternalServerError, new Error(result.Message));
            }

            var data = new
            {
                token = BuildToken(model.Email)
            };
            var context = $"Created user with ID '{userKey}' in bucket '{_bucket.Name}' that expires in {userDoc.Expiry}ms";
            return Content(HttpStatusCode.Accepted, new Result(data, context));
        }

This is the main method :

namespace MockServer
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8080/signup");

            // Create the ServiceHost.
            using (ServiceHost host = new ServiceHost(typeof(UserController), baseAddress))
            {
                // Enable metadata publishing.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);

                // Open the ServiceHost to start listening for messages. Since
                // no endpoints are explicitly configured, the runtime will create
                // one endpoint per base address for each service contract implemented
                // by the service.
                host.Open();

                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                // Close the ServiceHost.
                host.Close();
            }
        }
    }
}

Body:
Update main to host the web api properly.

include the following using statements

using System.Web.Http;
using System.Web.Http.SelfHost; //install the nuget package Microsoft.AspNet.WebApi.SelfHost

update Program class to Host the Web API

class Program {
    static void Main(string[] args) {
        var baseAddress = "http://localhost:8080";
        var config = new HttpSelfHostConfiguration(baseAddress);
        config.MapHttpAttributeRoutes();//map attribute routes
        // Create the server
        using (var server = new HttpSelfHostServer(config)) {
            server.OpenAsync().Wait();
            Console.WriteLine("The service is ready at {0}", baseAddress);
            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();
        }
    }
}

Now make sure the api controller it correctly defined.

[RoutePrefix("api/user")]
public class UserController : ApiController {
    private readonly IBucket _bucket = ClusterHelper.GetBucket(ConfigurationManager.AppSettings.Get("CouchbaseUserBucket"));
    private readonly string _secretKey = ConfigurationManager.AppSettings["JWTTokenSecret"];
    [HttpPost]
    [Route("signup")] //Matches POST api/user/signup
    public async Task<IHttpActionResult> SignUp(LoginModel model) {

        //...code removed for brevity

    }
}

Given the program set and controller attribute routes,  the action would be found at

POST http://localhost:8080/api/user/signup


问:
Reload data from database without refreshing page
My Ajax successfully update some information in database and as a result he should update one element, which shows this information. But it doesn't. However, after refreshing page, which cause reconnecting to db, information updating. Here is the function:

```<code>function topUpTheBalance(){
        var d = document.getElementById("numberForm").value;
        $.ajax({
        type: 'POST',
        url: 'handler.php',
        data: {
            'topUpBalance':d,
        },
        success: function () {
            var k = document.getElementById("balanceNumber");
            k.innerHTML ="Your balance: "+ <?php echo $userRow['userBalance']; ?>;
        }
        }
        );
    }
</code>```

and the handler.php

```<code><?php
    ob_start();
    session_start();
    require_once 'dbconnect.php';

    if( !isset($_SESSION['user']) ) {
    header("Location: index.php");
     exit;
    }
    $res=mysqli_query($link, "SELECT * FROM users WHERE userId=".$_SESSION['user']);
    $userRow=mysqli_fetch_array($res);
    //$link =  mysqli_connect("localhost","username","password", "users");
    $bal = $userRow['userBalance']+$_POST['topUpBalance'];
    if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ? WHERE userId = ?")){
            mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_bind_result($stmt, $result);
            mysqli_stmt_fetch($stmt);
            mysqli_stmt_close($stmt);
    }
    mysqli_close($link);
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
<?php ob_end_flush(); ?>
</code>```

Can anyone suggest me how to update this information without refreshing the page?

答:
there is no detail information to help you but the first thing i noticed is your AJAX call, to get data you need to call it through GET type: </p>

```<code>$.ajax({
    'url': 'getdata.php',
    'type': 'GET',
    'dataType': 'json',
    'data': {'topUpBalance':d},
    'success': function(data) {
      // if the request calls properly
    },
    'error': function(data) {
      // if the request fails.
    }
});
</code>```

Body:
My Ajax successfully update some information in database and as a result he should update one element, which shows this information. But it doesn't. However, after refreshing page, which cause reconnecting to db, information updating. Here is the function:

function topUpTheBalance(){
        var d = document.getElementById("numberForm").value;
        $.ajax({
        type: 'POST',
        url: 'handler.php',
        data: {
            'topUpBalance':d,
        },
        success: function () {
            var k = document.getElementById("balanceNumber");
            k.innerHTML ="Your balance: "+ <?php echo $userRow['userBalance']; ?>;
        }
        }
        );
    }

and the handler.php

<?php
    ob_start();
    session_start();
    require_once 'dbconnect.php';

    if( !isset($_SESSION['user']) ) {
    header("Location: index.php");
     exit;
    }
    $res=mysqli_query($link, "SELECT * FROM users WHERE userId=".$_SESSION['user']);
    $userRow=mysqli_fetch_array($res);
    //$link =  mysqli_connect("localhost","username","password", "users");
    $bal = $userRow['userBalance']+$_POST['topUpBalance'];
    if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ? WHERE userId = ?")){
            mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_bind_result($stmt, $result);
            mysqli_stmt_fetch($stmt);
            mysqli_stmt_close($stmt);
    }
    mysqli_close($link);
?>
<!DOCTYPE html>

<?php ob_end_flush(); ?>

Can anyone suggest me how to update this information without refreshing the page?

Body:
there is no detail information to help you but the first thing i noticed is your AJAX call, to get data you need to call it through GET type:

$.ajax({
    'url': 'getdata.php',
    'type': 'GET',
    'dataType': 'json',
    'data': {'topUpBalance':d},
    'success': function(data) {
      // if the request calls properly
    },
    'error': function(data) {
      // if the request fails.
    }
});


问:
Where can I download the source for cron utility?
I have searched for the source for cron, to adapt it to modify/exend it. I cant locate it (thought it would be in coreutils).

Anyone knows where I can get the sources for cron?

BTW, I am running on Linux (Ubuntu 10.0.4)

答: apt-get source cron should fetch you the sources assuming you have the repositories properly setup.


问:
androidplot dual scale XY with range scales not independent
back in 0.9.8 i created 2 overlayed plots with one having the range legend left and the other right in a nice symmetric setup

depending which one side was selected as indicated by the same color for the grid and domain labels the range labels and range grid lined up with this side and the opposite range labels and their divisions were according to their originals settings but not lining up with the grid but still provided some indication of the values with respect to the grid

as mentioned, the grid was in accordance and lining up to selected side

now in 1.4.3 i have a 2 range label sets available, but only one gobal setting for the range grid, which is fine, but also for the range labels

```<code>Plot.setRangeStep (StepMode.INCREMENT_BY_VAL, div) ;
</code>```

do i see this correct ???

now i have the not selected range labels lined up at the global grid lines and with divisions which look awful with all the decimal fraction-ed values and weird spacing

this solution might make the use of a single plot useless for me

i have no problems using 2 plots, but there is a big plot.redraw penalty for 2 plots and my setup is already not as fast as i would like

i might be able to have 2 plots where the second one only provides the grid and right range legend ... this asymmetric setup seems to become quite a mess

any suggestions are highly welcome ... if a new release (1.4.5) would have a fix, then i do not need this fix right now, since the whole project will take a couple of month more at least and i can implement it when available ... just got the bt data acquisition and plotting framework done and the last 10 % take always 90 % of time ;)

pict examples

dual plot 0.9.8 left blue range is selected, domain and grid are also blue  ... right magenta range has non fractured labels, but doesn't line up which is fine

single plot 1.4.3 right green range selected, domain and grid are also green ... left red range has fractured labels (awful) but lines up which is not so important since un-aligned grid provides some guideline

答:
finally it seems like i have it working again with 1.4.3

i have now one main plot with one range legend on the left plus a left connected range grid and a domain legend with a domain grid at the bottom ... all series data is also handled in the main plot ... this single plot draws all the series data plots and is faster with redraw compared to 2 separate series data plots

then i have a second plot with a range on the right plus a right connected range grid

both plots overlap physically with the second one having a bunch set to transparency or being null'ed out (hidden) to overlay the main plot

only the selected side's range grid is displayed, while the other is null

```<code>gw.setRangeGridLinePaint (null) ;
</code>```

for the rangestep setup i use selectively both plots

```<code>if (left) {
  more code ...
  PlotL.setRangeStep (StepMode.INCREMENT_BY_VAL, div) ;
} else {
  more code ...
  PlotR.setRangeStep (StepMode.INCREMENT_BY_VAL, div) ;
}
</code>```

to answer the question about normalized data :

i took it very easy with setting all ranges from 0.0 to 1000.0 and scale the data provided accordingly so that it fits within the min and max expected values per series ... eSzeX = 500 and eSzeY = 1000

```<code>PlotL.setDomainBoundaries (0, eSzeX, BoundaryMode.FIXED) ;
PlotL.setRangeBoundaries  (0, eSzeY, BoundaryMode.FIXED) ;
PlotR.setRangeBoundaries  (0, eSzeY, BoundaryMode.FIXED) ;
</code>```

i need to re-evaluate the 500 x-axis data points which keep the cpu extremely busy with 6 series data plots and slows things down a bit

... every series has it's own final scaling in the XYSeries getX (int idx) implementation with a single multiply and additive linear offset

i'm not a genius and the same data structs need to work in a similar manner with QWT plotting under QT for the desktop solution

the main data pre-processsing is handled in a JNI wrapper sharing code with the QT implementation

the series data arrays contain massive data points, depending on the size of the log file, but only 500 are being displayed and the indexing is being handled also via simple JNI access routines ... all data specific information is contained within the C++ code to be compatible with the QT and QWT code without rewriting it in java

the scrolling is not as smooth as i would like at the moment, but much better than with the dual plot under 0.9.8, but i have no time for optimization right now and have already done quite some

it would be very very nice if this complicated setup could be avoided and androidplot would have a similar built in ability ... maybe it does via sub-classing or similar techniques, but without examples i would not know where to look or how to do it

i was able to use

```<code>private class LabelRendererY extends LineLabelRenderer { ... }
</code>```

to play a bit with label data and position processing ... i was lucky to find an example somewhere

it's very hard to make a living in this dry desert of open source software

thanks for your response Nick ... i might have more questions later

for now i'm not messing with separate data series legends since what i have keeps me pretty busy

Body:
back in 0.9.8 i created 2 overlayed plots with one having the range legend left and the other right in a nice symmetric setup

depending which one side was selected as indicated by the same color for the grid and domain labels the range labels and range grid lined up with this side and the opposite range labels and their divisions were according to their originals settings but not lining up with the grid but still provided some indication of the values with respect to the grid

as mentioned, the grid was in accordance and lining up to selected side

now in 1.4.3 i have a 2 range label sets available, but only one gobal setting for the range grid, which is fine, but also for the range labels

Plot.setRangeStep (StepMode.INCREMENT_BY_VAL, div) ;

do i see this correct ???

now i have the not selected range labels lined up at the global grid lines and with divisions which look awful with all the decimal fraction-ed values and weird spacing

this solution might make the use of a single plot useless for me

i have no problems using 2 plots, but there is a big plot.redraw penalty for 2 plots and my setup is already not as fast as i would like

i might be able to have 2 plots where the second one only provides the grid and right range legend ... this asymmetric setup seems to become quite a mess

any suggestions are highly welcome ... if a new release (1.4.5) would have a fix, then i do not need this fix right now, since the whole project will take a couple of month more at least and i can implement it when available ... just got the bt data acquisition and plotting framework done and the last 10 % take always 90 % of time ;)

pict examples

dual plot 0.9.8 left blue range is selected, domain and grid are also blue  ... right magenta range has non fractured labels, but doesn't line up which is fine

single plot 1.4.3 right green range selected, domain and grid are also green ... left red range has fractured labels (awful) but lines up which is not so important since un-aligned grid provides some guideline

Body:
finally it seems like i have it working again with 1.4.3

i have now one main plot with one range legend on the left plus a left connected range grid and a domain legend with a domain grid at the bottom ... all series data is also handled in the main plot ... this single plot draws all the series data plots and is faster with redraw compared to 2 separate series data plots

then i have a second plot with a range on the right plus a right connected range grid

both plots overlap physically with the second one having a bunch set to transparency or being null'ed out (hidden) to overlay the main plot

only the selected side's range grid is displayed, while the other is null

gw.setRangeGridLinePaint (null) ;

for the rangestep setup i use selectively both plots

if (left) {
  more code ...
  PlotL.setRangeStep (StepMode.INCREMENT_BY_VAL, div) ;
} else {
  more code ...
  PlotR.setRangeStep (StepMode.INCREMENT_BY_VAL, div) ;
}

to answer the question about normalized data :

i took it very easy with setting all ranges from 0.0 to 1000.0 and scale the data provided accordingly so that it fits within the min and max expected values per series ... eSzeX = 500 and eSzeY = 1000

PlotL.setDomainBoundaries (0, eSzeX, BoundaryMode.FIXED) ;
PlotL.setRangeBoundaries  (0, eSzeY, BoundaryMode.FIXED) ;
PlotR.setRangeBoundaries  (0, eSzeY, BoundaryMode.FIXED) ;

i need to re-evaluate the 500 x-axis data points which keep the cpu extremely busy with 6 series data plots and slows things down a bit

... every series has it's own final scaling in the XYSeries getX (int idx) implementation with a single multiply and additive linear offset

i'm not a genius and the same data structs need to work in a similar manner with QWT plotting under QT for the desktop solution

the main data pre-processsing is handled in a JNI wrapper sharing code with the QT implementation

the series data arrays contain massive data points, depending on the size of the log file, but only 500 are being displayed and the indexing is being handled also via simple JNI access routines ... all data specific information is contained within the C++ code to be compatible with the QT and QWT code without rewriting it in java

the scrolling is not as smooth as i would like at the moment, but much better than with the dual plot under 0.9.8, but i have no time for optimization right now and have already done quite some

it would be very very nice if this complicated setup could be avoided and androidplot would have a similar built in ability ... maybe it does via sub-classing or similar techniques, but without examples i would not know where to look or how to do it

i was able to use

private class LabelRendererY extends LineLabelRenderer { ... }

to play a bit with label data and position processing ... i was lucky to find an example somewhere

it's very hard to make a living in this dry desert of open source software

thanks for your response Nick ... i might have more questions later

for now i'm not messing with separate data series legends since what i have keeps me pretty busy


问:
IntelliJ IDEA "The selected directory is not a valid home for JDK"
I just installed IntelliJ IDEA and I'm trying to set it up. I've gotten to the part where I need to select my home directory for my JDK.

I tried navigating to my Java installation, C:\Program Files (x86)\Java, and clicked okay but it told me the message above. So, I tried C:\Program Files (x86)\Java\jre7 and that didn't work either.

I tried reinstalling the latest JDK (from here) and I still couldn't choose my JDK. I even dragged the .jar installer I got from the website and the file selector window wouldn't recognize it.

I'm at a standstill and I don't know what to do.

答:
One thing we should note: the jdk should be installed on C: drive.

I had JDK installed on my D: drive like this:

```<code>D:\Program Files\Java\jdk1.8.0_101
</code>```

And it would still give me the same error. For some reason Java should be installed on C: drive.

Body:
One thing we should note: the jdk should be installed on C: drive.

I had JDK installed on my D: drive like this:

D:\Program Files\Java\jdk1.8.0_101

And it would still give me the same error. For some reason Java should be installed on C: drive.


答:
You are setting a property 'onclick' of function 'fizzBuzz',
you should use the input event.</p>

```<code>var userInput = document.getElementById('userInput');
userInput.oninput = function() {

    if( this.value == 10 ) alert('awesome');

}
</code>```

Title: How to take an input that is equal to 10 and perform a function that says awesome to the screen

Body:
You are setting a property 'onclick' of function 'fizzBuzz',
you should use the input event.

var userInput = document.getElementById('userInput');
userInput.oninput = function() {

    if( this.value == 10 ) alert('awesome');

}


问:
Bypass JSF validation for a UIInput component
Here is the issue, JSF validation keeps flipping a field back to the last known value.

We are editing a page where the backing bean already has values.
(frequency = "weekly")

And we are required to show the default value of "please select.." even though that value will not pass validation (yes, I just want to leave the user on the page with the error message).

Is there any way to allow the user to choose "Select.." and not reset it to the last good value?

The user wont be allowed to save obviously, but we want to leave their invalid value selected.

User adds new object, selecting proper value from drop down

User saves successfully.

User Clicks "edit" and displays object with known value ("weekly")

User changes "weekly" to "select"

User clicks save

Validation message is shown (good) but frequency goes back to last value "weekly" (bad, I need it to stay on "Please select.." and let the user fix the drop down manually.

immediate="true" does not work on inputComponents, only commandComponents.

答:
I recognize this, I've reported this more than one year ago as JSF issue 1299. This is still not resolved since it has a low priority. This is not specific to all UIInput components, but to MenuRenderer which is responsible for rendering the HTML <select> elements. All other HTML input elements behave as you would expect, the submitted value will be redisplayed (well, which is actually nothing as well).

Since you're already on JSF 2.0, I suggest you to solve this with a little help of f:ajax so that the dropdown won't be re-rendered and thus keeps its selection.

```<code><h:selectOneMenu id="frequency" value="#{bean.frequency}" required="true">
    <f:selectItems value="#{bean.frequencies}" />
    <f:ajax render="frequencyMessage" />
</h:selectOneMenu>
<h:message id="frequencyMessage" for="frequency" />
</code>```

The additional benefit is that the enduser has instant feedback and this is better for user experience.

Body:
I recognize this, I've reported this more than one year ago as JSF issue 1299. This is still not resolved since it has a low priority. This is not specific to all UIInput components, but to MenuRenderer which is responsible for rendering the HTML <select> elements. All other HTML input elements behave as you would expect, the submitted value will be redisplayed (well, which is actually nothing as well).

Since you're already on JSF 2.0, I suggest you to solve this with a little help of f:ajax so that the dropdown won't be re-rendered and thus keeps its selection.

<h:selectOneMenu id="frequency" value="#{bean.frequency}" required="true">
    <f:selectItems value="#{bean.frequencies}" />
    <f:ajax render="frequencyMessage" />
</h:selectOneMenu>
<h:message id="frequencyMessage" for="frequency" />

The additional benefit is that the enduser has instant feedback and this is better for user experience.


问:
how to hide local variables
In my code, sometimes there's a long function, to avoid messed up the local variables, i would use a pair of braces to embrace the details so the local variables will not be visible to the rest of the code, e.g.:

```<code>bool pricing_deals()
{
  //prepare deal type lookup table
  vector<DealType> deal_types; // deal type lookup table
  {
    vector<DealType> deal_types_TRF;
    vector<DealType> deal_types_DCI;
    ...
    // code that prepare deal_types by merging deal_types_TRF and deal_types_DCI etc
  }
  // from now on deal_types_TRF and deal_types_DCI are invisible

  //prepare ccy pair lookup table
  vector<CcyPair> ccy_pairs; // ccy pair lookup table
  {
    // code that prepare ccy_pairs;
  }
  // from now on local variables preparing ccy_pairs are invisible

  // real computation starts
  ...
}
</code>```

I wonder if this is a good practice, or there are other ways of doing so you would suggeset?

p.s. I prefer not to break it into smaller functions in this case, as the sub-logic is not likely to be reused by others, and refactoring will cause a lot of parameters to be passed over, which would increase the complexity.

答:
This is a good practice under some circumstances, if you can't split the function into multiple smaller functions, but you must be aware that when a local variable goes out of scope its destructor is called which may or may be not a problem, for example if you suppose something like:

```<code>#include <iostream>
#include <vector>
#include <string>

int main(int argc, const char* argv[])
{
  using namespace std;

  vector<string>::const_iterator it;

  {
    const vector<string> data = {"foo", "bar", "baz"};
    it = data.begin();
  }

  cout << *it << endl;

  return 0;
}
</code>```

Then here you store a const_iterator to a vector which is released when the scope is closed so you get undefined behavior. This doesn't mean your solution is not a good solution, it just means that you must take into account any specific drawback.

This is also good if you need to allocate many resources in multiple parts of a function so that you can allocate and release them gradually without any need of a memory spike.

Title: how to hide local variables

Body:
In my code, sometimes there's a long function, to avoid messed up the local variables, i would use a pair of braces to embrace the details so the local variables will not be visible to the rest of the code, e.g.:

bool pricing_deals()
{
  //prepare deal type lookup table
  vector<DealType> deal_types; // deal type lookup table
  {
    vector<DealType> deal_types_TRF;
    vector<DealType> deal_types_DCI;
    ...
    // code that prepare deal_types by merging deal_types_TRF and deal_types_DCI etc
  }
  // from now on deal_types_TRF and deal_types_DCI are invisible

  //prepare ccy pair lookup table
  vector<CcyPair> ccy_pairs; // ccy pair lookup table
  {
    // code that prepare ccy_pairs;
  }
  // from now on local variables preparing ccy_pairs are invisible

  // real computation starts
  ...
}

I wonder if this is a good practice, or there are other ways of doing so you would suggeset?

p.s. I prefer not to break it into smaller functions in this case, as the sub-logic is not likely to be reused by others, and refactoring will cause a lot of parameters to be passed over, which would increase the complexity.

Body:
This is a good practice under some circumstances, if you can't split the function into multiple smaller functions, but you must be aware that when a local variable goes out of scope its destructor is called which may or may be not a problem, for example if you suppose something like:

#include <iostream>
#include <vector>
#include <string>

int main(int argc, const char* argv[])
{
  using namespace std;

  vector<string>::const_iterator it;

  {
    const vector<string> data = {"foo", "bar", "baz"};
    it = data.begin();
  }

  cout << *it << endl;

  return 0;
}

Then here you store a const_iterator to a vector which is released when the scope is closed so you get undefined behavior. This doesn't mean your solution is not a good solution, it just means that you must take into account any specific drawback.

This is also good if you need to allocate many resources in multiple parts of a function so that you can allocate and release them gradually without any need of a memory spike.


问:
C++ Declare array of unspecified length with string elements
What I'm trying to do here is quite simple. But some way, some how I'm missing something. I'm trying to "pre-declare" an array with strictly string elements in such a way that I can update the array contents during a specific period (periodically). So here are the snippets:

```<code>string ShotBox[] = {}; //"Pre-Declare" array that could contain as many elements here
</code>```

Then I have a loop within my Update container. Snippet's:

```<code>for (int i = 0; i < sizeof(ShotBox) - 1; i++){
            std::string soa = sPath;
            std::string so = soa + ShotBox[i];
            char *cstr = new char[so.length() + 1];
            strcpy(cstr, so.c_str());
            scPath = cstr;
}
</code>```

All is fine with everything except the fact that whichever way I try to "pre-declare", I get a memory access violation. In this very exact snippets, the exact error is: an empty array is invalid for an array with unspecified bound.

I tried using "vector" but can't seem to work around it. What's the way to solve this? Please I don't want libraries. I need direct short methods or something of such.

答:
The problem of memory access violation itself is caused by your misunderstanding of sizeof operator. Specifically, sizeof(ShotBox) is the size (in bytes) of your array, not the ShotBox[] array size.

```<code>for (int i = 0; i < sizeof(ShotBox)/sizeof(std::string); i++) {
    ...
}
</code>```

Inside the for loop ShotBox[] elements aren't updated at all. The only thing that happens is concatenation of sPath with ShotBox[i] into a new C string 'cstr'. If your aim is to update ShotBox[i] element, just add the following assignment to the end of for loop:

```<code>for (int i = 0; i < N_SHOT_BOX; i++) {
    ...
    ShotBox[i] = so;
}
</code>```

It's much more convenient to use std::vector for working with collections of variable size:

```<code>#include <string>
#include <vector>
#include <memory.h>

int main() {
    std::vector<std::string> ShotBox{"str1", "str2", "str3"};

    for (int i = 0; i < ShotBox.size(); i++){
        std::string soa = sPath;
        std::string so = soa + ShotBox[i];
        char *cstr = new char[so.length() + 1];
        strcpy(cstr, so.c_str());
        ShotBox[i] = cstr;
    }

    return 0;
}
</code>```

Body:
What I'm trying to do here is quite simple. But some way, some how I'm missing something. I'm trying to "pre-declare" an array with strictly string elements in such a way that I can update the array contents during a specific period (periodically). So here are the snippets:

string ShotBox[] = {}; //"Pre-Declare" array that could contain as many elements here

Then I have a loop within my Update container. Snippet's:

for (int i = 0; i < sizeof(ShotBox) - 1; i++){
            std::string soa = sPath;
            std::string so = soa + ShotBox[i];
            char *cstr = new char[so.length() + 1];
            strcpy(cstr, so.c_str());
            scPath = cstr;
}

All is fine with everything except the fact that whichever way I try to "pre-declare", I get a memory access violation. In this very exact snippets, the exact error is: an empty array is invalid for an array with unspecified bound.

I tried using "vector" but can't seem to work around it. What's the way to solve this? Please I don't want libraries. I need direct short methods or something of such.

Body:
The problem of memory access violation itself is caused by your misunderstanding of sizeof operator. Specifically, sizeof(ShotBox) is the size (in bytes) of your array, not the ShotBox[] array size.

for (int i = 0; i < sizeof(ShotBox)/sizeof(std::string); i++) {
    ...
}

Inside the for loop ShotBox[] elements aren't updated at all. The only thing that happens is concatenation of sPath with ShotBox[i] into a new C string 'cstr'. If your aim is to update ShotBox[i] element, just add the following assignment to the end of for loop:

for (int i = 0; i < N_SHOT_BOX; i++) {
    ...
    ShotBox[i] = so;
}

It's much more convenient to use std::vector for working with collections of variable size:

#include <string>
#include <vector>
#include <memory.h>

int main() {
    std::vector<std::string> ShotBox{"str1", "str2", "str3"};

    for (int i = 0; i < ShotBox.size(); i++){
        std::string soa = sPath;
        std::string so = soa + ShotBox[i];
        char *cstr = new char[so.length() + 1];
        strcpy(cstr, so.c_str());
        ShotBox[i] = cstr;
    }

    return 0;
}


问:
how to create combinations of elements in a list in scala
I have a rdd of list of strings, like the following:

```<code> (['a','b','c'],['1','2','3','4'],['e','f'],...)
</code>```

now I want to get the list consists of all pairwise combinations in each innerlist, like the following:

```<code> (('a','b'),('a','c'),('b','c'),('1','2'),('1','3'),('1','4'),('2','3'),'('2','4'),('3','4'),('e','f'),...)
</code>```

How to do that?

答:
You can use flatMap with List.combinations:

```<code>val rdd = sc.parallelize(Seq(List("a", "b", "c"), List("1", "2", "3", "4"), List("e", "f")))
// rdd: org.apache.spark.rdd.RDD[List[String]] = ParallelCollectionRDD[0] at parallelize at <console>:24

rdd.flatMap(list => list.combinations(2)).collect()
// res1: Array[List[String]] = Array(List(a, b), List(a, c), List(b, c), List(1, 2), List(1, 3), List(1, 4), List(2, 3), List(2, 4), List(3, 4), List(e, f))
</code>```

Body:
I have a rdd of list of strings, like the following:

 (['a','b','c'],['1','2','3','4'],['e','f'],...)

now I want to get the list consists of all pairwise combinations in each innerlist, like the following:

 (('a','b'),('a','c'),('b','c'),('1','2'),('1','3'),('1','4'),('2','3'),'('2','4'),('3','4'),('e','f'),...)

How to do that?

Body:
You can use flatMap with List.combinations:

val rdd = sc.parallelize(Seq(List("a", "b", "c"), List("1", "2", "3", "4"), List("e", "f")))
// rdd: org.apache.spark.rdd.RDD[List[String]] = ParallelCollectionRDD[0] at parallelize at <console>:24

rdd.flatMap(list => list.combinations(2)).collect()
// res1: Array[List[String]] = Array(List(a, b), List(a, c), List(b, c), List(1, 2), List(1, 3), List(1, 4), List(2, 3), List(2, 4), List(3, 4), List(e, f))


问:
How to Pull all docker container images from docker repo at once?
I have a private docker repo in which i have 10 container images stored. I want to pull all images to a machine. is there a way i can pull all images from a repo with a single command? some command like

```<code>docker pull  xx.xx.com/reponame/*
</code>```

while researching I found ways to pull all tags of a single image; but no luck so far on all images

答:
Easy.

Install jq to parse JSON, edit the REGISTRY variable and run this script:

```<code>#!/bin/sh

REGISTRY="http://registry:5000"

for repo in $(curl -s $REGISTRY/v2/_catalog | jq -r '.repositories[]') ; do
    for tag in $(curl -s $REGISTRY/v2/$repo/tags/list | jq -r '.tags[]') ; do
        docker pull $REGISTRY/$repo:$tag
    done
done
</code>```

For details on the Docker Registry API:
https://github.com/docker/distribution/blob/master/docs/spec/api.md

Body:
I have a private docker repo in which i have 10 container images stored. I want to pull all images to a machine. is there a way i can pull all images from a repo with a single command? some command like

docker pull  xx.xx.com/reponame/*

while researching I found ways to pull all tags of a single image; but no luck so far on all images

Body:
Easy.

Install jq to parse JSON, edit the REGISTRY variable and run this script:

#!/bin/sh

REGISTRY="http://registry:5000"

for repo in $(curl -s $REGISTRY/v2/_catalog | jq -r '.repositories[]') ; do
    for tag in $(curl -s $REGISTRY/v2/$repo/tags/list | jq -r '.tags[]') ; do
        docker pull $REGISTRY/$repo:$tag
    done
done

For details on the Docker Registry API:
https://github.com/docker/distribution/blob/master/docs/spec/api.md


问:
Check if a number is int or float
Here's how I did it:

```<code>inNumber = somenumber
inNumberint = int(inNumber)
if inNumber == inNumberint:
    print "this number is an int"
else:
    print "this number is a float"
</code>```

Something like that.

Are there any nicer looking ways to do this?

答:
You can use modulo to determine if x is an integer numerically. The isinstance(x, int) method only determines if x is an integer by type:

```<code>def isInt(x):
    if x%1 == 0:
        print "X is an integer"
    else:
        print "X is not an integer"
</code>```

Title: Check if a number is int or float

Body:
Here's how I did it:

inNumber = somenumber
inNumberint = int(inNumber)
if inNumber == inNumberint:
    print "this number is an int"
else:
    print "this number is a float"

Something like that.

Are there any nicer looking ways to do this?

Body:
You can use modulo to determine if x is an integer numerically. The isinstance(x, int) method only determines if x is an integer by type:

def isInt(x):
    if x%1 == 0:
        print "X is an integer"
    else:
        print "X is not an integer"