问:
R - Inverse cumulative distribution method with given function
I have a given function (let's call it f(x)) and I used the Monte Carlo method to normalized it. I calculated  the probability density function and I got the cumulative distribution function from integrating that.

```<code>f = function(x) ...

plot(f,xlim = c(0, 5), ylim = c(0, 1),main="f(x)")

mc.integral = function(f, n.iter = 1000, interval){
  x = runif(n.iter, interval[1], interval[2])
  y = f(x)
  mean(y)*(interval[2] - interval[1])
}

MC = mc.integral(f, interval = c(0, 8))
print(MC)

densityFunction <- function(x){
  return ((f(x)/MC))
}

distributionFunction <- function(x){
  return  (integrate(densityFunction,0,x)$value)
}

vd <- Vectorize(distributionFunction)
plot(vd,xlim = c(0, 8), ylim = c(0, 1),ylab = "y",main="E(f(x))")
</code>```

Now my next task is to use the inverse transform method / inverse cumulative distribution method to generate samples and test it with the Kolmogorov-Smirnov Test, but I don't know how should I do in R.

Can you please give me some help?

答:
Well, this thread shows us how to generate a sample using the inverse transform method:

```<code>sample <- vd(runif(1000))

> head(sample)
[1] 0.28737403 0.59295499 0.30814305 0.27998306 0.07601228 0.52753327
</code>```

Therefore, generating 10 different random samples could be done with:

```<code>sample <- list()
for(i in 1:10){
  set.seed(i)
  sample[[i]] <- vd(runif(1000))
}
</code>```

Afterwards, loop ks.test over the list:

```<code>lapply(sample, function(x) ks.test(x, pnorm))
</code>```

will give you the output of a test vs. normality for each sample. Choose the size of your samples wisely, as most tests for normality are prone to be significant for large samples even with small differences (reference here).

Body:
I have a given function (let's call it f(x)) and I used the Monte Carlo method to normalized it. I calculated  the probability density function and I got the cumulative distribution function from integrating that.

f = function(x) ...

plot(f,xlim = c(0, 5), ylim = c(0, 1),main="f(x)")

mc.integral = function(f, n.iter = 1000, interval){
  x = runif(n.iter, interval[1], interval[2])
  y = f(x)
  mean(y)*(interval[2] - interval[1])
}

MC = mc.integral(f, interval = c(0, 8))
print(MC)

densityFunction <- function(x){
  return ((f(x)/MC))
}

distributionFunction <- function(x){
  return  (integrate(densityFunction,0,x)$value)
}

vd <- Vectorize(distributionFunction)
plot(vd,xlim = c(0, 8), ylim = c(0, 1),ylab = "y",main="E(f(x))")

Now my next task is to use the inverse transform method / inverse cumulative distribution method to generate samples and test it with the Kolmogorov-Smirnov Test, but I don't know how should I do in R.

Can you please give me some help?

Body:
Well, this thread shows us how to generate a sample using the inverse transform method:

sample <- vd(runif(1000))

> head(sample)
[1] 0.28737403 0.59295499 0.30814305 0.27998306 0.07601228 0.52753327

Therefore, generating 10 different random samples could be done with:

sample <- list()
for(i in 1:10){
  set.seed(i)
  sample[[i]] <- vd(runif(1000))
}

Afterwards, loop ks.test over the list:

lapply(sample, function(x) ks.test(x, pnorm))

will give you the output of a test vs. normality for each sample. Choose the size of your samples wisely, as most tests for normality are prone to be significant for large samples even with small differences (reference here).


来源: stackexchange

问:
compare string with startWith in scala
I want to compare a pattern in string

```<code>sealed trait Demo { def value: String }

   object Demo {
  case object TypeAB extends Demo {
    val value = "a:b"
  }
      .......other constants
}
 val test = Option("a:b:c")
val s =test.map(_.startsWith(Demo.TypeAB.value))
</code>```

I want to not use .value in Demo.TypeAB.value
Is there a better approach to achieve the above .I preferred to use startsWith

I tried but it didnot work

```<code> def unapply(arg: Demo): String= arg.value
</code>```

答:
You could add predicates to Demo that provide the tests you need:

```<code>sealed trait Demo {
  def value: String
  def startsWith(body: Option[String]): Boolean = body match {
    case Some(content) => content.startsWith(value)
    case _ => false
  }
}
</code>```

This allows you to hide the implementation details at the cost of a broader interface.

ContentLicense: CC BY-SA 3.0

Title: compare string with startWith in scala

Body:
I want to compare a pattern in string

sealed trait Demo { def value: String }

   object Demo {
  case object TypeAB extends Demo {
    val value = "a:b"
  }
      .......other constants
}
 val test = Option("a:b:c")
val s =test.map(_.startsWith(Demo.TypeAB.value))

I want to not use .value in Demo.TypeAB.value
Is there a better approach to achieve the above .I preferred to use startsWith

I tried but it didnot work

 def unapply(arg: Demo): String= arg.value

Body:
You could add predicates to Demo that provide the tests you need:

sealed trait Demo {
  def value: String
  def startsWith(body: Option[String]): Boolean = body match {
    case Some(content) => content.startsWith(value)
    case _ => false
  }
}

This allows you to hide the implementation details at the cost of a broader interface.


问:
php cannot find Class when using namespace
I'm trying to make a object of a class from another file. Both file is located in the same folder & I used 'namespace App' in the both files. In the login files I'm trying to get the class object but it couldn't find the class. Codes are given below.

Database Class : 'Database.php'

```<code><?php
    namespace App;

    require_once 'config.php';

class Database{

    private $db;

    public function __construct(){

        $this->db =  new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    }

    public function getConnection(){

        return $this->db;

    }
</code>```

login.php file :

```<code><?php

    namespace App;

    use App\Database;

    require_once 'config.php';

    $DB = new Database();

    $con = $DB->getConnection;
</code>```

When I execute login.php , it says Fatal error: Uncaught Error: Class 'App\Database' not found in login.php on line 10

答:
I think you missing to require database file. Also, call the method by the following way. You are calling a property getConnection that is not available.</p>

```<code><?php
namespace App;
require_once 'config.php';
require_once 'Database.php';

use App\Database;

$DB = new Database();
$con = $DB->getConnection();
</code>```

Body:
I'm trying to make a object of a class from another file. Both file is located in the same folder & I used 'namespace App' in the both files. In the login files I'm trying to get the class object but it couldn't find the class. Codes are given below.

Database Class : 'Database.php'

<?php
    namespace App;

    require_once 'config.php';

class Database{

    private $db;

    public function __construct(){

        $this->db =  new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    }

    public function getConnection(){

        return $this->db;

    }

login.php file :

<?php

    namespace App;

    use App\Database;

    require_once 'config.php';

    $DB = new Database();

    $con = $DB->getConnection;

When I execute login.php , it says Fatal error: Uncaught Error: Class 'App\Database' not found in login.php on line 10

Body:
I think you missing to require database file. Also, call the method by the following way. You are calling a property getConnection that is not available.

<?php
namespace App;
require_once 'config.php';
require_once 'Database.php';

use App\Database;

$DB = new Database();
$con = $DB->getConnection();


问:
Android Google Maps: disable dragging in MapFragment
Can I disable drag functionality when the user tries to drag the map with his fingers without   disturbing the Zoom in and Zoom out?

Any one please suggest an idea of doing this!
  Thanks for your Precious help!!

答:
for disable dragging in MapFragment this code :

```<code>googleMap.getUiSettings().setScrollGesturesEnabled(false);
</code>```

works as @tomrozb said.
but it dosn't disable map zoom by touch on map. for that use this code beside above code:

```<code>googleMap.getUiSettings().setZoomGesturesEnabled(false);
</code>```

Body:
for disable dragging in MapFragment this code :

googleMap.getUiSettings().setScrollGesturesEnabled(false);

works as @tomrozb said.
but it dosn't disable map zoom by touch on map. for that use this code beside above code:

googleMap.getUiSettings().setZoomGesturesEnabled(false);


问:
Find dict elems based on its key n-elemnt tuple's condition
I have a dictionary whose keys are tuples of length n.

For example, for n = 3:

```<code>{('I', 'like', 'you'): 14, ('you', 'like', 'it'): 12, ('he', 'likes', 'it'): 2}
</code>```

I can find all words for key tuples that end with a given word, like this:

```<code>word = 'it'
words = [rest[-1] for first, *rest in counted_ngrams if rest[-1] == word]
</code>```

But, how to make a dictionary of complete (tuple + number) elements from the original dictionary whose keys ends with a given word, e.g., 'it'?

答:
With a handy dictionary-comprehension like so:

```<code>a = {('I', 'like', 'you'): 14, ('you', 'like', 'it'): 12, ('he', 'likes', 'it'): 2}

b = {k: v for k, v in a.items() if k[-1] == 'it'}
print(b)  # -> {('you', 'like', 'it'): 12, ('he', 'likes', 'it'): 2}
</code>```

Checking for k[-1] instead of k[2] ensures the above works with tuples of any length (even inconsistent lengths).

Body:
I have a dictionary whose keys are tuples of length n.

For example, for n = 3:

{('I', 'like', 'you'): 14, ('you', 'like', 'it'): 12, ('he', 'likes', 'it'): 2}

I can find all words for key tuples that end with a given word, like this:

word = 'it'
words = [rest[-1] for first, *rest in counted_ngrams if rest[-1] == word]

But, how to make a dictionary of complete (tuple + number) elements from the original dictionary whose keys ends with a given word, e.g., 'it'?

Body:
With a handy dictionary-comprehension like so:

a = {('I', 'like', 'you'): 14, ('you', 'like', 'it'): 12, ('he', 'likes', 'it'): 2}

b = {k: v for k, v in a.items() if k[-1] == 'it'}
print(b)  # -> {('you', 'like', 'it'): 12, ('he', 'likes', 'it'): 2}

Checking for k[-1] instead of k[2] ensures the above works with tuples of any length (even inconsistent lengths).


问:
Heuristic to predict Name or Company

Problem

We are recieving strings and they may either represent a company name or a person's name. We need a heuristic to determine this.

Initial thoughts

Use an XML doc with either node Commercial String /Commercial or Personal String /Personal and score matching strings +1 (sorry dont know how to format XML in SO)

Cant just check for proper nouns. I.E. Bob's Company is a company where Bob Compton is a name

Need to return confidence level in some format. I can't think of how to do it as a percentage, all I can think to do is if it finds a match use an integer

Possible Commercial (all will be converted to lower case): co, co., inc, inc., etc (verbose versions of each)

I can get a English Name list from online

Question

Has anyone ran into this kind of domain problem before? What methods did you use? Any flashy way of solving this?

Thank You.

答:
I haven't done this before, but some other thoughts:

Check for non-proper nouns (e.g. "and", "the", "piping").  In fact, if you have an English dictionary and a names list, any word that is not a name could be a good pointer to a company name.

A big problem is that some companies are just named after a person(s).  "Fred Meyer", "J.C. Penney", and "Lockheed Martin" are examples of companies that look just like human names.  There's likely no really good way around this (probably nothing easy anyway).  If you can categorize first and last names, a double last name or last name only might be a good reason to lower the certainty.

I would agree with your integer idea.  Unless you can do some very broad and very thorough testing, your percentages would probably be meaningless.  I would probably run all the tests (returning name, company, or unknown) and compare the results, adding up an integer based on consistency in results.

ContentLicense: CC BY-SA 2.5

Title: Heuristic to predict Name or Company


答:
Does this counts as a better way:

```<code>sealed trait Demo {
  def value: String

  def startsWith(s: String): Boolean = s.startsWith(value)
}

object Demo {

  case object TypeAB extends Demo {
    val value = "a:b"
  }

}

val test = Option("a:b:c")
val s = test.map(Demo.TypeAB.startsWith(_))
println(s)
</code>```

or maybe you want to use implicits magic such as

```<code>sealed trait Demo {      def value: String    }

implicit class DemoStringOps(val s: String) extends AnyRef {
  def startsWith(d: Demo) = s.startsWith(d.value)
}

object Demo {

  case object TypeAB extends Demo {
    val value = "a:b"
  }

}

val test = Option("a:b:c")

val s = test.map(_.startsWith(Demo.TypeAB))
println(s)
</code>```

Title: compare string with startWith in scala

Body:
Does this counts as a better way:

sealed trait Demo {
  def value: String

  def startsWith(s: String): Boolean = s.startsWith(value)
}

object Demo {

  case object TypeAB extends Demo {
    val value = "a:b"
  }

}

val test = Option("a:b:c")
val s = test.map(Demo.TypeAB.startsWith(_))
println(s)

or maybe you want to use implicits magic such as

sealed trait Demo {      def value: String    }

implicit class DemoStringOps(val s: String) extends AnyRef {
  def startsWith(d: Demo) = s.startsWith(d.value)
}

object Demo {

  case object TypeAB extends Demo {
    val value = "a:b"
  }

}

val test = Option("a:b:c")

val s = test.map(_.startsWith(Demo.TypeAB))
println(s)


问:
Spring transactions - detecting rollback and commit
I have methods annotated @Transactional and I would like to detect rollbacks and commits.

Does exist any way or any Spring object which can check if transaction was commited or rollbacked?

答:
you can write a unit test cases which is using h2 in-memory database and it will acts like a real db. for example save(obj) and after get(obj).

Also you can write test case which is catch exception that is what you expect(probably when occur a rollback there is also a exception) with this format:
@Test(expected = Exception.class)
Testclass


问:
How do I access my struct's elements in different if statements?
Apologies if this is a really dumb question.

I have declared and initialised a struct array here (just above the for loop);

```<code>printf("\n>>>");
    scanf( "%s" , &CurrentCommand);

    if (strcmp(CurrentCommand, "bang") == 0)
    {
        Clear();
        printf("Enter the number of stars to be created: ");
        scanf("%d", &NumberOfStars);

        struct StarsStruct *Stars = malloc(sizeof(struct StarsStruct) * NumberOfStars);

        for (int i = 0; i < NumberOfStars; i++)
        {
            r1 = rand() % (60 + 1 - 0) + 0;
            r2 = rand() % (30 + 1 - 0) + 0;

            Stars[i].SerialNumber = i;
            Stars[i].x = r1;
            Stars[i].y = r2;

            Plot(r1, r2, '.');
        }

    }
</code>```

I have accessed the elements I need in the for loop, in the first IF statement, however I am no longer able to access them on my second IF loop, probably because "struct StarsStruct *Stars" was declared locally.

So how would I be able to access it in another if statement? Declaring it at the start doesn't work, because I guess creating the array with malloc has to be done in one go, with the declaration and initialisation.

To sum up, I want to access member of the Stars struct, in another IF statement I will create, Stars[1].SerialNumber and such. However I currently cannot.

答:
You need to define your variable further up where it will be visible where it is needed.  You'll just need to initialize it to NULL, then you can later assign the result of malloc where you need to.

```<code>// define up here and initialize to NULL
struct StarsStruct *Stars = NULL;

printf("\n>>>");
scanf( "%s" , &CurrentCommand);

if (strcmp(CurrentCommand, "bang") == 0)
{
    Clear();
    printf("Enter the number of stars to be created: ");
    scanf("%d", &NumberOfStars);

    // assign here
    Stars = malloc(sizeof(struct StarsStruct) * NumberOfStars);

    for (int i = 0; i < NumberOfStars; i++)
    {
        r1 = rand() % (60 + 1 - 0) + 0;
        r2 = rand() % (30 + 1 - 0) + 0;

        Stars[i].SerialNumber = i;
        Stars[i].x = r1;
        Stars[i].y = r2;

        Plot(r1, r2, '.');
    }

}
</code>```

Body:
Apologies if this is a really dumb question.

I have declared and initialised a struct array here (just above the for loop);

printf("\n>>>");
    scanf( "%s" , &CurrentCommand);

    if (strcmp(CurrentCommand, "bang") == 0)
    {
        Clear();
        printf("Enter the number of stars to be created: ");
        scanf("%d", &NumberOfStars);

        struct StarsStruct *Stars = malloc(sizeof(struct StarsStruct) * NumberOfStars);

        for (int i = 0; i < NumberOfStars; i++)
        {
            r1 = rand() % (60 + 1 - 0) + 0;
            r2 = rand() % (30 + 1 - 0) + 0;

            Stars[i].SerialNumber = i;
            Stars[i].x = r1;
            Stars[i].y = r2;

            Plot(r1, r2, '.');
        }

    }

I have accessed the elements I need in the for loop, in the first IF statement, however I am no longer able to access them on my second IF loop, probably because "struct StarsStruct *Stars" was declared locally.

So how would I be able to access it in another if statement? Declaring it at the start doesn't work, because I guess creating the array with malloc has to be done in one go, with the declaration and initialisation.

To sum up, I want to access member of the Stars struct, in another IF statement I will create, Stars[1].SerialNumber and such. However I currently cannot.

Body:
You need to define your variable further up where it will be visible where it is needed.  You'll just need to initialize it to NULL, then you can later assign the result of malloc where you need to.

// define up here and initialize to NULL
struct StarsStruct *Stars = NULL;

printf("\n>>>");
scanf( "%s" , &CurrentCommand);

if (strcmp(CurrentCommand, "bang") == 0)
{
    Clear();
    printf("Enter the number of stars to be created: ");
    scanf("%d", &NumberOfStars);

    // assign here
    Stars = malloc(sizeof(struct StarsStruct) * NumberOfStars);

    for (int i = 0; i < NumberOfStars; i++)
    {
        r1 = rand() % (60 + 1 - 0) + 0;
        r2 = rand() % (30 + 1 - 0) + 0;

        Stars[i].SerialNumber = i;
        Stars[i].x = r1;
        Stars[i].y = r2;

        Plot(r1, r2, '.');
    }

}


问:
How to execute 'msbuild' command from a batch file
I would like to create a batch file to make the builds from my VS project in on click. All the days I do the following steps:

Opens a cmd console as administrador

Go to the path of my project/solution (using the CD.., CD commands)

Write the following command to make the build:

msbuild mySolution.sln /p:configuration=debug

As commented before, I'd like to make all this process in one simply click. So, I'm trying to create a .bat file to do it.

This is the code of my batch file:

```<code>set location="C:\myPath\..\MyFolderSolution"
set pathMSBuild = "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe"

@echo off
cls

call %pathMSBuild%
cd %location%
msbuild.exe "lucre.sln" /p:configuration=debug
pause
</code>```

However, when I try to execute the batch file I get the following error:
'msbuild' is not recognized as an internal or external command, operable program or batch file.

Any clue or help to know if it is possible and if so, how to do it will be very appreciate

Regards!

答:
Both answers use hardcoded paths, which might not always work.
Use this instead:

```<code>@if exist "%VS100COMNTOOLS%vsvars32.bat" call "%VS100COMNTOOLS%vsvars32.bat"
</code>```

Change VS100 to any other version, you can also put these lines one by one to support many versions of VS simulteneously:

```<code>@if exist "%VS100COMNTOOLS%vsvars32.bat" call "%VS100COMNTOOLS%vsvars32.bat"
@if exist "%VS140COMNTOOLS%vsvars32.bat" call "%VS140COMNTOOLS%vsvars32.bat"
</code>```

If done this way, you no longer dependant on a specific version of .Net Framework or Visual Studio

Body:
I would like to create a batch file to make the builds from my VS project in on click. All the days I do the following steps:

Opens a cmd console as administrador

Go to the path of my project/solution (using the CD.., CD commands)

Write the following command to make the build:

msbuild mySolution.sln /p:configuration=debug

As commented before, I'd like to make all this process in one simply click. So, I'm trying to create a .bat file to do it.

This is the code of my batch file:

set location="C:\myPath\..\MyFolderSolution"
set pathMSBuild = "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe"

@echo off
cls

call %pathMSBuild%
cd %location%
msbuild.exe "lucre.sln" /p:configuration=debug
pause

However, when I try to execute the batch file I get the following error:
'msbuild' is not recognized as an internal or external command, operable program or batch file.

Any clue or help to know if it is possible and if so, how to do it will be very appreciate

Regards!

Body:
Both answers use hardcoded paths, which might not always work.
Use this instead:

@if exist "%VS100COMNTOOLS%vsvars32.bat" call "%VS100COMNTOOLS%vsvars32.bat"

Change VS100 to any other version, you can also put these lines one by one to support many versions of VS simulteneously:

@if exist "%VS100COMNTOOLS%vsvars32.bat" call "%VS100COMNTOOLS%vsvars32.bat"
@if exist "%VS140COMNTOOLS%vsvars32.bat" call "%VS140COMNTOOLS%vsvars32.bat"

If done this way, you no longer dependant on a specific version of .Net Framework or Visual Studio


问:
Cascading deletes in PostgreSQL
I have a database with a few dozen tables interlinked with foreign keys. Under normal circumstances, I want the default ON DELETE RESTRICT behavior for those constraints. But when trying to share a snapshot of the database with a consultant, I needed to remove some sensitive data. I wish that my memory of a DELETE FROM Table CASCADE command hadn't been pure hallucination.

What I ended out doing was dumping the database, writing a script to process the dump by adding ON DELETE CASCADE clauses too all the foreign key constraints, restoring from that, performing my deletes, dumping again, removing the ON DELETE CASCADE, and finally restoring again. That was easier than writing the deletion query I'd have needed to do this in SQL -- removing whole slices of the database isn't a normal operation, so the schema isn't exactly adapted to it.

Does anyone have a better solution for the next time something like this comes up?

答: @Tony: No, schemas can be useful, and indeed, we use them to partition data in our database. But I'm talking about trying to scrub sensitive data before letting a consultant have a copy of the db. I want that data gone.</p>

OwnerDisplayName: Please delete this account

Title: Cascading deletes in PostgreSQL


问:
Regex to pull out C function prototype declarations?
I'm somewhere on the learning curve when it comes to regular expressions, and I need to use them to automatically modify function prototypes in a bunch of C headers.  Does anyone know of a decent regular expression to find any and all function prototypes in a C header, while excluding everything else?

Edit: Three things that weren't clear initially:

I do not care about C++, only straight C.  This means no templates, etc. to worry about.

The solution must work with typedefs and structs, no limiting to only basic C types.

This is kind of a one-off thing.  It does not need to be pretty.  I do not care how much of a kludge it is as long as it works, but I don't want a complex, hard to implement solution.

答:
For a one-off exercise, you'd probably do best by starting simple and looking at the code you have to scan.  Pick the three worst headers, generate a regex or series of regexes that do the job.  You have to decide whether and how you are going deal with comments that contain function declarations (and, indeed, with function declarations that contain comments).  Dealing with:

```<code>extern void (*function(int, void (*)(int)))(int);
</code>```

(which could be the Standard C function signal()) is tough in a regex because of the nested parentheses.  If you don't have any such function prototypes, time spent working out how to deal with them is time wasted.  Similar comments apply to pointers to multi-dimensional arrays.  The chances are that you have stylistic conventions to simplify your life.  You may not use C99 (C++) comments; you don't need to code around them.   You probably don't put multiple declarations in a single line, either with or without a common type - so you don't have to deal with that.

```<code>extern int func1(int), func2(double); double func3(int);  // Nasty!
</code>```

OwnerDisplayName: dsimcha

LastEditorDisplayName: Chad Birch

Body:
For a one-off exercise, you'd probably do best by starting simple and looking at the code you have to scan.  Pick the three worst headers, generate a regex or series of regexes that do the job.  You have to decide whether and how you are going deal with comments that contain function declarations (and, indeed, with function declarations that contain comments).  Dealing with:

extern void (*function(int, void (*)(int)))(int);

(which could be the Standard C function signal()) is tough in a regex because of the nested parentheses.  If you don't have any such function prototypes, time spent working out how to deal with them is time wasted.  Similar comments apply to pointers to multi-dimensional arrays.  The chances are that you have stylistic conventions to simplify your life.  You may not use C99 (C++) comments; you don't need to code around them.   You probably don't put multiple declarations in a single line, either with or without a common type - so you don't have to deal with that.

extern int func1(int), func2(double); double func3(int);  // Nasty!

OwnerDisplayName: Jonathan Leffler


问:
Can a PDF Embed onmousedown Javascript Events?
My client has some web pages that have A tag links with onmousedown events on them. My tools are PHP, Linux, and the tools for PDF generation there like DomPDF and PHP PDF. Is there a way to put the links into a PDF with the onmousedown Javascript code still working? The onmousedown events change the href.

I mean, I hear that PDF files can have Javascript in them, but I don't know if that also means the onmousedown event can be included as well and still operate.

答:
Current stable releases of dompdf ignore JavaScript when rendering a document. The next release (0.6.0) will include the capability of including JavaScript in the rendered document, but the JavaScript has to be contained inside a script element that is in the body of the document. Because of this requirement you would have to write a function that locates your link and appends onmousedown events.

I don't know enough about using JavaScript in PDF document to say how easy it would be to write a script to do what you want.

ContentLicense: CC BY-SA 4.0


问:
Calculate the table's contentSize.height with custom cells of different types iphone
In my application , the tableview is having different types of custom cells with different heights. I want to put a view below this tableView, for which I need to calculate the table contentView height, how can I do it?

Earlier I used to do it like: (noOfRows * cell_height), but that was for static heights.

Thanx in advance.

答:
The header and footer of the section are not considered in the height of the table, consider this

```<code>CGSize sz = self.table.contentSize;
sz.height += self.table.contentInset.bottom +
             self.table.contentInset.top +
             self.table.numberOfSections * self.table.sectionHeaderHeight;
</code>```

Body:
The header and footer of the section are not considered in the height of the table, consider this

CGSize sz = self.table.contentSize;
sz.height += self.table.contentInset.bottom +
             self.table.contentInset.top +
             self.table.numberOfSections * self.table.sectionHeaderHeight;


问:
How to read a TIBCO message in Grails 3

I want to read the messages being sent by TIBCO and process them in my Grails 3 Application. I'm relatively new to Grails 3 and need some assistance in configuring JMS to read messages from the TIBCO topic/queue.
I visited the documentation site but couldn't follow the instructions completely to establish a working example.</p>

答:
Take a look at http://realizeideas.net/use-amazon-simple-message-queue-service-within-grails-mircoservices/ - this describes how to configure  Grails + JMS + Amazon SQS.
For TIBCO you will only need to change connection factory:

```<code>    TibjmsConnectionFactory connectionFactory = new TibjmsConnectionFactory(...//TIBCO properties)
</code>```

and add correct TIBCO dependencies in build.gradle

Title: How to read a TIBCO message in Grails 3

Body:
Take a look at http://realizeideas.net/use-amazon-simple-message-queue-service-within-grails-mircoservices/ - this describes how to configure  Grails + JMS + Amazon SQS.
For TIBCO you will only need to change connection factory:

    TibjmsConnectionFactory connectionFactory = new TibjmsConnectionFactory(...//TIBCO properties)

and add correct TIBCO dependencies in build.gradle


问:
Counting values from td's in jQuery

 I have a problem with jQuery script. I'm trying to make a simple counting loop, for each tr. I got a table like below, and I want to select the second td, multiply it by two and add to the third td and display the result in the fourth td.

https://codepen.io/adeowsky/pen/YEgVKG

I'm trying to make it with the for each loop like below ->

```<code><script>
(function($) {
    $('.sp-league-table tbody tr').each( function() {
        var pct = this.find('.data-pct').text();
        console.log(pct);
        //var pct = $('').hasClass('data-pct').text();
        //console.log(pct);
        var winy = $('.data-w').text();
        var losy = $('.data-l').text();

        /*var pkt = (winy*2) + (losy*2);
        $('.data-pct').text(pkt);*/
    });
})( jQuery );
</script>
</code>```

But it doesn't work for me, where is the reason?

答:
You are selecting all the elements with the class, not the one in the current row.</p>

```<code>var tr = $(this);
var pCell = tr.find(".data-pct")
var wCell = tr.find('.data-w')
var lCell = tr.find('.data-l')
</code>```

Title: Counting values from td's in jQuery

Body:
 I have a problem with jQuery script. I'm trying to make a simple counting loop, for each tr. I got a table like below, and I want to select the second td, multiply it by two and add to the third td and display the result in the fourth td.

https://codepen.io/adeowsky/pen/YEgVKG

I'm trying to make it with the for each loop like below ->

But it doesn't work for me, where is the reason?

Body:
You are selecting all the elements with the class, not the one in the current row.

var tr = $(this);
var pCell = tr.find(".data-pct")
var wCell = tr.find('.data-w')
var lCell = tr.find('.data-l')


问:
Calling getItem() on DynamoDB object from AWS Lambda, why doesn't my callback execute?
I'm trying to get an item from my DynamoDB database. The way my code is presently written, I fail to retrieve any data from DynamoDB. I must be doing something wrong, because as far as I can tell from my test, my callback is not being called.

I spent all day on this yesterday and have been tinkering with it unsuccessfully since I woke up this morning.

If anyone can provide insight into what I'm doing wrong here, I would be very grateful. Thanks to everyone in advance!

Final note: The timeout on the Lambda function itself is set to 5 minutes. So I don't think the Lambda function is timing out before the db query can return. When I run the function, it exits after only a moment.

```<code>const AWS = require('aws-sdk');

const dynamodb = new AWS.DynamoDB();
var response = null;
var test = false;

function getFromDB(callback) {
  const params = {
    TableName: process.env['DB_TABLE_NAME'] // evaluates to 'test-table',
    Key: {
      "id": {
        S: postId // evaluates to a big string, pulling it in from an SNS message. Verified it with console.log(). It stores the expected value.
      }
    }
  };
  dynamodb.getItem(params, function(err, data) {
    if (err) callback(data, true);           // an error occurred
    else     callback(data, true);           // successful response
  });
}

getFromDB((data, isCalled) => {
    response = data;
    test = isCalled;
});

console.log(data); // evaluates to null
console.log(test); // evaluates to false
</code>```

答:
Have you loaded the SDK? I can't see it in your code snippet

```<code>// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});
</code>```

EDIT: Included region

Body:
I'm trying to get an item from my DynamoDB database. The way my code is presently written, I fail to retrieve any data from DynamoDB. I must be doing something wrong, because as far as I can tell from my test, my callback is not being called.

I spent all day on this yesterday and have been tinkering with it unsuccessfully since I woke up this morning.

If anyone can provide insight into what I'm doing wrong here, I would be very grateful. Thanks to everyone in advance!

Final note: The timeout on the Lambda function itself is set to 5 minutes. So I don't think the Lambda function is timing out before the db query can return. When I run the function, it exits after only a moment.

const AWS = require('aws-sdk');

const dynamodb = new AWS.DynamoDB();
var response = null;
var test = false;

function getFromDB(callback) {
  const params = {
    TableName: process.env['DB_TABLE_NAME'] // evaluates to 'test-table',
    Key: {
      "id": {
        S: postId // evaluates to a big string, pulling it in from an SNS message. Verified it with console.log(). It stores the expected value.
      }
    }
  };
  dynamodb.getItem(params, function(err, data) {
    if (err) callback(data, true);           // an error occurred
    else     callback(data, true);           // successful response
  });
}

getFromDB((data, isCalled) => {
    response = data;
    test = isCalled;
});

console.log(data); // evaluates to null
console.log(test); // evaluates to false

Body:
Have you loaded the SDK? I can't see it in your code snippet

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});

EDIT: Included region


问:
Trying to rename a file in a folder (based on a string within the filename)
Hi there I am trying to create a Sub where I find a file in a folder with the name containing a specific phrase like "test_file" and rename it with a different name/extension. I have the following code that doesn't seem to work: (Also I don't know how to search for a specific string within a filename and execute the renaming according to that)

```<code>Sub ReName()

Dim myFile As String
Dim myPath As String
Dim mVal As String

mVal = "_12345678_" 'test string'

myPath = "C:\Users\bf91955\Desktop\testfolder\" 'folder path'
myFile = Dir(pathname & "*test_file*") 'real file name is 2222_test_test_file.xlsx'
myFile = myPath & myFile

NewName = "new_test_file & mVal & .xlsx" 'save it as .xlsx and with the new filename including myVal'

Name myFile As myPath & NewName 'rename

End Sub
</code>```

Any help would be appreciated!

答:
Have a look at the comments you had a couple of errors</p>

```<code>Sub ReName()
    Dim myFile As String
    Dim myPath As String
    Dim mVal As String

    mVal = "_12345678_" 'test string'

    myPath = "C:\Users\bf91955\Desktop\testfolder\" 'folder path'
    '' You weren't referencing MyPath here - guessing copy and paste error
    myFile = Dir(myPath & "*test_file*") 'real file name is 2222_test_test_file.xlsx'
    myFile = myPath & myFile

    '' This was passing the variable as part of the string
    newname = "new_test_file" & mVal & ".xlsx" 'save it as .xlsx and with the new filename including myVal'

    Name myFile As myPath & newname 'rename

End Sub
</code>```

Body:
Hi there I am trying to create a Sub where I find a file in a folder with the name containing a specific phrase like "test_file" and rename it with a different name/extension. I have the following code that doesn't seem to work: (Also I don't know how to search for a specific string within a filename and execute the renaming according to that)

Sub ReName()

Dim myFile As String
Dim myPath As String
Dim mVal As String

mVal = "_12345678_" 'test string'

myPath = "C:\Users\bf91955\Desktop\testfolder\" 'folder path'
myFile = Dir(pathname & "*test_file*") 'real file name is 2222_test_test_file.xlsx'
myFile = myPath & myFile

NewName = "new_test_file & mVal & .xlsx" 'save it as .xlsx and with the new filename including myVal'

Name myFile As myPath & NewName 'rename

End Sub

Any help would be appreciated!

Body:
Have a look at the comments you had a couple of errors

Sub ReName()
    Dim myFile As String
    Dim myPath As String
    Dim mVal As String

    mVal = "_12345678_" 'test string'

    myPath = "C:\Users\bf91955\Desktop\testfolder\" 'folder path'
    '' You weren't referencing MyPath here - guessing copy and paste error
    myFile = Dir(myPath & "*test_file*") 'real file name is 2222_test_test_file.xlsx'
    myFile = myPath & myFile

    '' This was passing the variable as part of the string
    newname = "new_test_file" & mVal & ".xlsx" 'save it as .xlsx and with the new filename including myVal'

    Name myFile As myPath & newname 'rename

End Sub


问:
Regular expression to select strings with a character appearing on odd occurences
I'm trying to create a regex that will select words where the quote character appears on odd occurences. And I'm stuck...

Let's say I have these 4 strings :

hello'

pl'pl'op

'heger

qwe'rty

I should get this list in return :

hello'

'heger

qwe'rty

I'm running around in circles and I don't even know if it is possible to do that in a regex. I'm not so good in regex.

Should I just loop on each characters of all the strings, count the amount of quotes and do a modulo operation to check if the number is odd?

答:
Try this:

```<code>([^']*'[^']*'[^'])*[^']*'[^']*
</code>```

The idea is to capture in the group an even (possibly 0) number of quotes, and the text between them, and then one more quote.

Body:
Try this:

([^']*'[^']*'[^'])*[^']*'[^']*

The idea is to capture in the group an even (possibly 0) number of quotes, and the text between them, and then one more quote.


问:
Should I build tensorflow_serving module every time using TFServing?
I installed and tried to serve Inception model with TFServing successfully. After that I try to apply it on my own model.
But when I looked into source code of the example client, it depend on tensorflow_serving module which was built by bazel. So here comes the problem, should I copy recursively whole tensorflow_serving directory beneath serving/ to my repo and build it additionally, or just copy the file in bazel-bin directory. In my opinion, I would choose first way, however that means I would spend a lot of time building the module each time. Seems not to be a great way. Could someone offer me a better way to do this?

答:
First, install Bazel.

Then, clone the TF Serving repository:

```<code>mkdir $HOME/gitroot
cd $HOME/gitroot
git clone https://github.com/tensorflow/serving tensorflow-serving
</code>```

Finally, build the example app:

```<code>cd $HOME/gitroot/tensorflow-serving
bazel build --verbose_failures //tensorflow_serving/example:inception_client
</code>```

Bazel takes care of building the dependencies, you don't need to copy anything.

Body:
First, install Bazel.

Then, clone the TF Serving repository:

mkdir $HOME/gitroot
cd $HOME/gitroot
git clone https://github.com/tensorflow/serving tensorflow-serving

Finally, build the example app:

cd $HOME/gitroot/tensorflow-serving
bazel build --verbose_failures //tensorflow_serving/example:inception_client

Bazel takes care of building the dependencies, you don't need to copy anything.


问:
ASP.Net Treeview control and tag property for each node
if tree node does not have tag property like windows treeview control then i just want to know how could i attach the tag property with each tree node. is it possible if yes then please help me with code sample.

thanks

答:
If the information that you want to persist can be represented as a string then you can use the Value property of the TreeNode object:

Gets or sets a non-displayed value
  used to store any additional data
  about the node, such as data used for
  handling postback events.


问:
How Can I Disable Authentication in Django REST Framework
I'm working on a store site, where every user is going to be anonymous (well, until it's time to pay at least), and I'm trying to use Django REST Framework to serve the product API, but it keeps complaining about:

```<code>"detail": "Authentication credentials were not provided."
</code>```

I found some settings related to authentication, but I couldn't find anything like ENABLE_AUTHENTICATION = True. How do I simply disable authentication, and let any visitor to the site access the API?

答:
You can also apply it on one specific endpoint by applying it on class or method. Just need to apply django rest framework AllowAny permission to the specific method or class.

views.py

```<code>from rest_framework.permissions import AllowAny

from .serializers import CategorySerializer
from catalogue.models import Category

@permission_classes((AllowAny, ))
class CategoryList(generics.ListAPIView):
    serializer_class = serializers.CategorySerializer
    queryset = Category.objects.all()
</code>```

You can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.

Body:
I'm working on a store site, where every user is going to be anonymous (well, until it's time to pay at least), and I'm trying to use Django REST Framework to serve the product API, but it keeps complaining about:

"detail": "Authentication credentials were not provided."

I found some settings related to authentication, but I couldn't find anything like ENABLE_AUTHENTICATION = True. How do I simply disable authentication, and let any visitor to the site access the API?

Body:
You can also apply it on one specific endpoint by applying it on class or method. Just need to apply django rest framework AllowAny permission to the specific method or class.

views.py

from rest_framework.permissions import AllowAny

from .serializers import CategorySerializer
from catalogue.models import Category

@permission_classes((AllowAny, ))
class CategoryList(generics.ListAPIView):
    serializer_class = serializers.CategorySerializer
    queryset = Category.objects.all()

You can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.


问:
Webpack: include specific file instead of package.json specified?
I have a webpack configuration:

```<code>var path = require("path");

module.exports = {
  entry: {
    app: [
      './src/index.js'
    ]
  },

  output: {
    path: path.resolve(__dirname + '/dist'),
    filename: '[name].js',
  },

  module: {
    rules: [
      {
        test: /\.(css|scss)$/,
        use: [
          'style-loader',
          'css-loader',
        ]
      },
      {
        test:    /\.js$/,
        exclude: /node_modules/,
      },
      {
        test:    /\.html$/,
        exclude: /node_modules/,
        loader:  'file-loader?name=[name].[ext]',
      },
      {
        test:    /\.elm$/,
        exclude: [/elm-stuff/, /node_modules/],
        loader:  'elm-webpack-loader?verbose=true&warn=true',
          options: {debug: true, warn: true},
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader?limit=10000&mimetype=application/font-woff',
      },
      {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader',
      },
    ],

    noParse: /\.elm$/,
  },

  devServer: {
    inline: true,
    stats: { colors: true },
  },

};
</code>```

I have a few questions:

According to me the above config says that it should not be looking
for js files in node_modules. However it is still bundling
./node_modules/dexie/dist/dexie.es.js when I call require ("dexie"). (I am just doing this to experiment and understand webpack).

I would rather like to call dexie.js instead of dexie.es.js. How do
I make this happen. I know I can set the  mainFields property.
However how do I do this on a prelibrary basis instead of globally.

答:
Not sure if I understand your requirement fully, but an option is to set up aliases in the webpack resolve</p>

```<code>module.exports = {
  entry: {
    ...
  },

  output: {
    ...
  },

  module: {
    rules: [
      ...
    ],

    noParse: /\.elm$/,
  },

  resolve: {
    alias: {
      dixie: 'node_modules/dexie/dist/dexie.js'
    }
  },

  devServer: {
    ...
  },

};
</code>```

Body:
I have a webpack configuration:

var path = require("path");

module.exports = {
  entry: {
    app: [
      './src/index.js'
    ]
  },

  output: {
    path: path.resolve(__dirname + '/dist'),
    filename: '[name].js',
  },

  module: {
    rules: [
      {
        test: /\.(css|scss)$/,
        use: [
          'style-loader',
          'css-loader',
        ]
      },
      {
        test:    /\.js$/,
        exclude: /node_modules/,
      },
      {
        test:    /\.html$/,
        exclude: /node_modules/,
        loader:  'file-loader?name=[name].[ext]',
      },
      {
        test:    /\.elm$/,
        exclude: [/elm-stuff/, /node_modules/],
        loader:  'elm-webpack-loader?verbose=true&warn=true',
          options: {debug: true, warn: true},
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader?limit=10000&mimetype=application/font-woff',
      },
      {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader',
      },
    ],

    noParse: /\.elm$/,
  },

  devServer: {
    inline: true,
    stats: { colors: true },
  },

};

I have a few questions:

According to me the above config says that it should not be looking
for js files in node_modules. However it is still bundling
./node_modules/dexie/dist/dexie.es.js when I call require ("dexie"). (I am just doing this to experiment and understand webpack).

I would rather like to call dexie.js instead of dexie.es.js. How do
I make this happen. I know I can set the  mainFields property.
However how do I do this on a prelibrary basis instead of globally.

Body:
Not sure if I understand your requirement fully, but an option is to set up aliases in the webpack resolve

module.exports = {
  entry: {
    ...
  },

  output: {
    ...
  },

  module: {
    rules: [
      ...
    ],

    noParse: /\.elm$/,
  },

  resolve: {
    alias: {
      dixie: 'node_modules/dexie/dist/dexie.js'
    }
  },

  devServer: {
    ...
  },

};


问:
How to conditionally convert Array to object
Not just converting from array to object in javascript, I want to omit the specific fields and convert them into the object.

Here is my input data.

```<code>taggedItems = [
    {id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
    {id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
    {id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},

]
</code>```

Here expected output

```<code>taggedOUtput = {
    0: {id:0, left:100, top:100, thumbSize:100},
    1: {id:1, left:150, top:150, thumbSize:100},
    2: {id:2, left:200, top:200, thumbSize:100},
}
</code>```

How do we conditionally convert Array to object

答:
You could use reduce and the attributes from the original to create a new object as so:

const taggedItems = [
  {id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
  {id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
  {id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},
];

const newTaggedItems = taggedItems.reduce((prev, {id, left, top, thumbSize}) => ({
  ...prev,
  [id]: { id, left, top, thumbSize }
}), {});

console.log(newTaggedItems);```

Body:
Not just converting from array to object in javascript, I want to omit the specific fields and convert them into the object.

Here is my input data.

taggedItems = [
    {id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
    {id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
    {id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},

]

Here expected output

taggedOUtput = {
    0: {id:0, left:100, top:100, thumbSize:100},
    1: {id:1, left:150, top:150, thumbSize:100},
    2: {id:2, left:200, top:200, thumbSize:100},
}

How do we conditionally convert Array to object


问:
Can someone help me do these combo boxes correctly? I am very lost
Need help with this program. Everything I do seems to not work, it just shows me the same thing, even if I don't have any errors. The people on cheg sent me their modifications of the code and they still didn't work.

Your are headed off on a world-wide trip and need a program to help figure out how much things in other countries cost in dollars. You plan to visit Canada, several countries in Europe, Japan, Australia, India, and Mexico so your program must work for the currencies in those countries. The files CurrencyConverter.java and RatePanel.java contain a skeleton of a program to do this conversion. Complete it as follows:
CurrencyPanel currently contains only two components -- a JLabel for the title and a JLabel to display the result of the calculations. It also contains two parallel arrays -- one is an array of currency names (an array of strings) and the other an array of corresponding exchange rates (the value of one unit of the currency in U.S. Dollars). Compile and run the program to see what it looks like (not much!!).
Add a combo box to let the user select the currency. The argument to the constructor should be the array of names of the currencies. Note that the first currency name is actually an instruction to the user so there is no need to have an additional label.
Modify actionPerformed in ComboListener so that index is set to be the index of the selected item.
Test what you have so far. It should show what one unit of the given currency is in U.S. dollars.
Now add a text field (and label) so the user can enter the cost of an item in the selected currency. You need to update the ComboListener so that it gets this value from the textfield and computes and displays the equivalent amount in dollars.
Test your program.
Modify the layout to create a more attractive GUI (suggestion: use a box layout).

```<code>    // ******************************************************************
    //   RatePanel.java
    //
    //   Panel for a program that converts different currencies to
    //   U.S. Dollars
    // ******************************************************************

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class RatePanel extends JPanel
    {
        private JComboBox currencyCombo;

        private double[] rate;          // exchange rates
        private String[] currencyName;
        private JLabel result;

        // ------------------------------------------------------------
       //  Sets up a panel to convert cost from one of 6 currencies
       //  into U.S. Dollars. The panel contains a heading, a text
       //  field for the cost of the item, a combo box for selecting
       //  the currency, and a label to display the result.
       // ------------------------------------------------------------
       public RatePanel ()
       {
            JLabel title = new JLabel ("How much is that in dollars?");
            title.setAlignmentX (Component.CENTER_ALIGNMENT);
            title.setFont (new Font ("Helvetica", Font.BOLD, 20));

            // Set up the arrays for the currency conversions
            currencyName = new String[] {"Select the currency..",
                                         "European Euro", "Canadian Dollar",
                                         "Japanese Yen", "Australian Dollar",
                                         "Indian Rupee", "Mexican Peso"};
            rate = new double [] {0.0, 0.948968, 0.646920,
                                   0.00803616, 0.562082,
                                   0.0204441, 0.103735};

           result = new JLabel (" U.S. Dollars ????? ");

           add (title);

           add (result);

       }

         // ******************************************************
        //   Represents an action listener for the combo box.
        // ******************************************************
       private class ComboListener implements ActionListener
       {
           // --------------------------------------------------
           //   Determines which currency has been selected and
           //   the value in that currency then computes and
           //   displays the value in U.S. Dollars.
           // --------------------------------------------------
           public void actionPerformed (ActionEvent event)
           {
                int index = 0;
                result.setText ("1 " + currencyName[index] +
                               " = " + rate[index] + " U.S. Dollars");
           }
       }
    }
</code>```

Main program

```<code>      // *****************************************************************
      // File name: CurrencyConverter.java
      // Name:
      // Purpose: Computes the dollar value of the cost of an item in
      // another currency
      // *****************************************************************

    import java.awt.*;
    import javax.swing.*;
    public class CurrencyConverter
    {
         public static void main(String[] args)
    {
        JFrame frame = new JFrame("Currency Converter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        RatePanel ratePanel = new RatePanel();
        frame.getContentPane().add(ratePanel);
        frame.pack();
        frame.setVisible(true);

     }
   }
</code>```

答:
Just get the corresponding value in the rate array, based on the getSelectedIndex from the jComboBox.

Premises:

You have a jTextField where the user enters the amount required

You have a dropdown menu of currencies

You have a button that the user can click

You have another jTextField where the result is displayed

Once your button's ActionPerformed method can view your rate array:

```<code>double[] rate = new double[]{0.948968, 0.646920,
            0.562082, 0.0204441};
</code>```

Then do your calculations similar to:

```<code>double result = Double.parseDouble(jTextField2.getText()) * rate[jComboBox1.getSelectedIndex()];
</code>```

And print it (I rounded it to 2 decimal places for convenience) in the jTextField:

```<code>jTextField1.setText("Result: "+(String.format("%.2f", result)));
</code>```

Input:

55.23

Output:*

Dropdown1 - 52.41

Dropdown2 - 35.73

Dropdown3 - 31.04

Dropdown4 - 1.13

*This is just based on the values in the rate array in this example

Body:
Need help with this program. Everything I do seems to not work, it just shows me the same thing, even if I don't have any errors. The people on cheg sent me their modifications of the code and they still didn't work.

Your are headed off on a world-wide trip and need a program to help figure out how much things in other countries cost in dollars. You plan to visit Canada, several countries in Europe, Japan, Australia, India, and Mexico so your program must work for the currencies in those countries. The files CurrencyConverter.java and RatePanel.java contain a skeleton of a program to do this conversion. Complete it as follows:
CurrencyPanel currently contains only two components -- a JLabel for the title and a JLabel to display the result of the calculations. It also contains two parallel arrays -- one is an array of currency names (an array of strings) and the other an array of corresponding exchange rates (the value of one unit of the currency in U.S. Dollars). Compile and run the program to see what it looks like (not much!!).
Add a combo box to let the user select the currency. The argument to the constructor should be the array of names of the currencies. Note that the first currency name is actually an instruction to the user so there is no need to have an additional label.
Modify actionPerformed in ComboListener so that index is set to be the index of the selected item.
Test what you have so far. It should show what one unit of the given currency is in U.S. dollars.
Now add a text field (and label) so the user can enter the cost of an item in the selected currency. You need to update the ComboListener so that it gets this value from the textfield and computes and displays the equivalent amount in dollars.
Test your program.
Modify the layout to create a more attractive GUI (suggestion: use a box layout).

    // ******************************************************************
    //   RatePanel.java
    //
    //   Panel for a program that converts different currencies to
    //   U.S. Dollars
    // ******************************************************************

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class RatePanel extends JPanel
    {
        private JComboBox currencyCombo;

        private double[] rate;          // exchange rates
        private String[] currencyName;
        private JLabel result;

        // ------------------------------------------------------------
       //  Sets up a panel to convert cost from one of 6 currencies
       //  into U.S. Dollars. The panel contains a heading, a text
       //  field for the cost of the item, a combo box for selecting
       //  the currency, and a label to display the result.
       // ------------------------------------------------------------
       public RatePanel ()
       {
            JLabel title = new JLabel ("How much is that in dollars?");
            title.setAlignmentX (Component.CENTER_ALIGNMENT);
            title.setFont (new Font ("Helvetica", Font.BOLD, 20));

            // Set up the arrays for the currency conversions
            currencyName = new String[] {"Select the currency..",
                                         "European Euro", "Canadian Dollar",
                                         "Japanese Yen", "Australian Dollar",
                                         "Indian Rupee", "Mexican Peso"};
            rate = new double [] {0.0, 0.948968, 0.646920,
                                   0.00803616, 0.562082,
                                   0.0204441, 0.103735};

           result = new JLabel (" U.S. Dollars ????? ");

           add (title);

           add (result);

       }

         // ******************************************************
        //   Represents an action listener for the combo box.
        // ******************************************************
       private class ComboListener implements ActionListener
       {
           // --------------------------------------------------
           //   Determines which currency has been selected and
           //   the value in that currency then computes and
           //   displays the value in U.S. Dollars.
           // --------------------------------------------------
           public void actionPerformed (ActionEvent event)
           {
                int index = 0;
                result.setText ("1 " + currencyName[index] +
                               " = " + rate[index] + " U.S. Dollars");
           }
       }
    }

Main program

      // *****************************************************************
      // File name: CurrencyConverter.java
      // Name:
      // Purpose: Computes the dollar value of the cost of an item in
      // another currency
      // *****************************************************************

    import java.awt.*;
    import javax.swing.*;
    public class CurrencyConverter
    {
         public static void main(String[] args)
    {
        JFrame frame = new JFrame("Currency Converter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        RatePanel ratePanel = new RatePanel();
        frame.getContentPane().add(ratePanel);
        frame.pack();
        frame.setVisible(true);

     }
   }

Body:
Just get the corresponding value in the rate array, based on the getSelectedIndex from the jComboBox.

Premises:

You have a jTextField where the user enters the amount required

You have a dropdown menu of currencies

You have a button that the user can click

You have another jTextField where the result is displayed

Once your button's ActionPerformed method can view your rate array:

double[] rate = new double[]{0.948968, 0.646920,
            0.562082, 0.0204441};

Then do your calculations similar to:

double result = Double.parseDouble(jTextField2.getText()) * rate[jComboBox1.getSelectedIndex()];

And print it (I rounded it to 2 decimal places for convenience) in the jTextField:

jTextField1.setText("Result: "+(String.format("%.2f", result)));

Input:

55.23

Output:*

Dropdown1 - 52.41

Dropdown2 - 35.73

Dropdown3 - 31.04

Dropdown4 - 1.13

*This is just based on the values in the rate array in this example


问:
Swift - the completion ends before the animation does
I currently have the problem that the completion of the animation function ends before the animation itself does.

The array progressBar[] includes multiple UIProgressViews. When one is finished animating I want the next one to start animating and so on. But right now they all start at once.

How can I fix this?

```<code>@objc func updateProgress() {

        if self.index < self.images.count {
            progressBar[index].setProgress(0.01, animated: false)
            group.enter()

            DispatchQueue.main.async {
                UIView.animate(withDuration: 5, delay: 0.0, options: .curveLinear, animations: {
                    self.progressBar[self.index].setProgress(1.0, animated: true)
                }, completion: { (finished: Bool) in
                    if finished == true {
                        self.group.leave()
                    }
                })
            }
            group.notify(queue: .main) {
                self.index += 1
                self.updateProgress()
            }
        }
    }
</code>```

答:
The problem is that UIView.animate() can only be used on animatable properties, and progress is not an animatable property. "Animatable" here means "externally animatable by Core Animation." UIProgressView does its own internal animations, and that conflicts with external animations. This is UIProgressView being a bit over-smart, but we can work around it.

UIProgressView does use Core Animation, and so will fire CATransaction completion blocks. It does not, however, honor the duration of the current CATransaction, which I find confusing since it does honor the duration of the current UIView animation. I'm not actually certain how both of these are true (I would think that the UIView animation duration would be implemented on the transaction), but it seems to be the case.

Given that, the way to do what you're trying looks like this:

```<code>func updateProgress() {
    if self.index < self.images.count {
        progressBar[index].setProgress(0.01, animated: false)

        CATransaction.begin()
        CATransaction.setCompletionBlock {
            self.index += 1
            self.updateProgress()
        }
        UIView.animate(withDuration: 5, delay: 0, options: .curveLinear,
                       animations: {
                        self.progressBar[self.index].setProgress(1.0, animated: true)
        })
        CATransaction.commit()
    }
}
</code>```

I'm creating a nested transaction here (with begin/commit) just in case there is some other completion block created during this transaction. That's pretty unlikely, and the code "works" without calling begin/commit, but this way is a little safer than messing with the default transaction.

Body:
I currently have the problem that the completion of the animation function ends before the animation itself does.

The array progressBar[] includes multiple UIProgressViews. When one is finished animating I want the next one to start animating and so on. But right now they all start at once.

How can I fix this?

@objc func updateProgress() {

        if self.index < self.images.count {
            progressBar[index].setProgress(0.01, animated: false)
            group.enter()

            DispatchQueue.main.async {
                UIView.animate(withDuration: 5, delay: 0.0, options: .curveLinear, animations: {
                    self.progressBar[self.index].setProgress(1.0, animated: true)
                }, completion: { (finished: Bool) in
                    if finished == true {
                        self.group.leave()
                    }
                })
            }
            group.notify(queue: .main) {
                self.index += 1
                self.updateProgress()
            }
        }
    }

Body:
The problem is that UIView.animate() can only be used on animatable properties, and progress is not an animatable property. "Animatable" here means "externally animatable by Core Animation." UIProgressView does its own internal animations, and that conflicts with external animations. This is UIProgressView being a bit over-smart, but we can work around it.

UIProgressView does use Core Animation, and so will fire CATransaction completion blocks. It does not, however, honor the duration of the current CATransaction, which I find confusing since it does honor the duration of the current UIView animation. I'm not actually certain how both of these are true (I would think that the UIView animation duration would be implemented on the transaction), but it seems to be the case.

Given that, the way to do what you're trying looks like this:

func updateProgress() {
    if self.index < self.images.count {
        progressBar[index].setProgress(0.01, animated: false)

        CATransaction.begin()
        CATransaction.setCompletionBlock {
            self.index += 1
            self.updateProgress()
        }
        UIView.animate(withDuration: 5, delay: 0, options: .curveLinear,
                       animations: {
                        self.progressBar[self.index].setProgress(1.0, animated: true)
        })
        CATransaction.commit()
    }
}

I'm creating a nested transaction here (with begin/commit) just in case there is some other completion block created during this transaction. That's pretty unlikely, and the code "works" without calling begin/commit, but this way is a little safer than messing with the default transaction.


问:
How can I speed up INNODB queries comparable to MYISAM performance?
I have recently switched my database tables from MYISAM to INNODB and experience bad timeouts with queries, mostly inserts. One function I use previously took <2 seconds to insert, delete and update a large collection of records across ~30 MYISAM tables, but now that they are INNODB, the function causes a PHP timeout.

The timeout was set to 60 seconds. I have optimised my script enough that now, even though there are still many queries, they are combined together (multiple inserts, multiple deletes, etc) and the script now takes ~25 seconds, which is a substantial increase from what appeared to be at least 60 seconds.

This duration is still over 10x quicker when previously using MYISAM, is there any mistakes I could be making in the way I process these queries? Or are there any settings that could assist in the performance? Currently the MySQL is using the default settings of installation.

The queries are nothing special, DELETE ... WHERE ... simple logic, same with the INSERT and UPDATE queries.

答:
Hard to say without knowing too much about your environment, but this might be more of a database tuning problem. InnoDB can be VERY slow on budget hardware where every write forces a true flush. (This affects writes, not reads.)

For instance, you may want to read up on options like:

```<code>innodb_flush_log_at_trx_commit=2
sync_binlog=0
</code>```

By avoiding the flushes you may be able to speed up your application considerably, but at the cost of potential data loss if the server crashes.

If data loss is something you absolutely cannot live with, then the other option is to use better hardware.

Body:
Hard to say without knowing too much about your environment, but this might be more of a database tuning problem. InnoDB can be VERY slow on budget hardware where every write forces a true flush. (This affects writes, not reads.)

For instance, you may want to read up on options like:

innodb_flush_log_at_trx_commit=2
sync_binlog=0

By avoiding the flushes you may be able to speed up your application considerably, but at the cost of potential data loss if the server crashes.

If data loss is something you absolutely cannot live with, then the other option is to use better hardware.


问:
Merging files on S3 Amazon
I have an application where i want to merge two files present on s3 into the third file. I thought of using the Copy Object using multipart upload. Below is the code.

```<code>       AmazonS3Config config = new AmazonS3Config();
        AmazonS3 s3Client = new AmazonS3Client(accessKeyID, secretAccessKey, config);

        // List to store upload part responses.
        List<UploadPartResponse> uploadResponses =
            new List<UploadPartResponse>();

        List<CopyPartResponse> copyResponses =
                  new List<CopyPartResponse>();
        InitiateMultipartUploadRequest initiateRequest =
               new InitiateMultipartUploadRequest()
                .WithBucketName(targetBucket)
                .WithKey(targetObjectKey);

        InitiateMultipartUploadResponse initResponse =
            s3Client.InitiateMultipartUpload(initiateRequest);
        String uploadId = initResponse.UploadId;

        try
        {
            // Get object size.
            GetObjectMetadataRequest metadataRequest = new GetObjectMetadataRequest();
            metadataRequest.BucketName = sourceBucket;
            metadataRequest.Key = sourceObjectKey1;

            GetObjectMetadataResponse metadataResponse = s3Client.GetObjectMetadata(metadataRequest);
            long objectSize1 = metadataResponse.ContentLength; // in bytes

            // Get object size.
            GetObjectMetadataRequest metadataRequest2 = new GetObjectMetadataRequest();
            metadataRequest2.BucketName = sourceBucket;
            metadataRequest2.Key = sourceObjectKey2;

            GetObjectMetadataResponse metadataResponse2 = s3Client.GetObjectMetadata(metadataRequest2);
            long objectSize2 = metadataResponse2.ContentLength; // in bytes

            long bytePosition = 0;

            CopyPartRequest copyRequest1 = new CopyPartRequest()
               .WithDestinationBucket(targetBucket)
               .WithDestinationKey(targetObjectKey)
               .WithSourceBucket(sourceBucket)
               .WithSourceKey(sourceObjectKey1)
               .WithUploadID(uploadId)
               .WithFirstByte(bytePosition)
               .WithLastByte( objectSize1 - 1 )
               .WithPartNumber(1);

            copyResponses.Add(s3Client.CopyPart(copyRequest1));

            CopyPartRequest copyRequest2 = new CopyPartRequest()
               .WithDestinationBucket(targetBucket)
               .WithDestinationKey(targetObjectKey)
               .WithSourceBucket(sourceBucket)
               .WithSourceKey(sourceObjectKey2)
               .WithUploadID(uploadId)
               .WithFirstByte(bytePosition)
               .WithLastByte(objectSize2 - 1)
               .WithPartNumber(2);

            copyResponses.Add(s3Client.CopyPart(copyRequest2));

            ////
            CompleteMultipartUploadRequest completeRequest =
                  new CompleteMultipartUploadRequest()
                     .WithBucketName(targetBucket)
                     .WithKey(targetObjectKey)
                     .WithUploadId(initResponse.UploadId)
                     .WithPartETags(GetETags(copyResponses));

            CompleteMultipartUploadResponse completeUploadResponse =
                s3Client.CompleteMultipartUpload(completeRequest);

        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
</code>```

But it is throwing exception at the last line CompleteMultipartUpload. Below is the S3 exception: Your proposed upload is smaller than the minimum allowed size

Where as if i only upload copyRequest1 it works fine.

Any help is appreciated!!

Regards,
Haseena

答: It is not possible to merge uploaded files using S3 API, so I am using FTP to download and Merge.</p>

Title: Merging files on S3 Amazon

Body:
I have an application where i want to merge two files present on s3 into the third file. I thought of using the Copy Object using multipart upload. Below is the code.

       AmazonS3Config config = new AmazonS3Config();
        AmazonS3 s3Client = new AmazonS3Client(accessKeyID, secretAccessKey, config);

        // List to store upload part responses.
        List<UploadPartResponse> uploadResponses =
            new List<UploadPartResponse>();

        List<CopyPartResponse> copyResponses =
                  new List<CopyPartResponse>();
        InitiateMultipartUploadRequest initiateRequest =
               new InitiateMultipartUploadRequest()
                .WithBucketName(targetBucket)
                .WithKey(targetObjectKey);

        InitiateMultipartUploadResponse initResponse =
            s3Client.InitiateMultipartUpload(initiateRequest);
        String uploadId = initResponse.UploadId;

        try
        {
            // Get object size.
            GetObjectMetadataRequest metadataRequest = new GetObjectMetadataRequest();
            metadataRequest.BucketName = sourceBucket;
            metadataRequest.Key = sourceObjectKey1;

            GetObjectMetadataResponse metadataResponse = s3Client.GetObjectMetadata(metadataRequest);
            long objectSize1 = metadataResponse.ContentLength; // in bytes

            // Get object size.
            GetObjectMetadataRequest metadataRequest2 = new GetObjectMetadataRequest();
            metadataRequest2.BucketName = sourceBucket;
            metadataRequest2.Key = sourceObjectKey2;

            GetObjectMetadataResponse metadataResponse2 = s3Client.GetObjectMetadata(metadataRequest2);
            long objectSize2 = metadataResponse2.ContentLength; // in bytes

            long bytePosition = 0;

            CopyPartRequest copyRequest1 = new CopyPartRequest()
               .WithDestinationBucket(targetBucket)
               .WithDestinationKey(targetObjectKey)
               .WithSourceBucket(sourceBucket)
               .WithSourceKey(sourceObjectKey1)
               .WithUploadID(uploadId)
               .WithFirstByte(bytePosition)
               .WithLastByte( objectSize1 - 1 )
               .WithPartNumber(1);

            copyResponses.Add(s3Client.CopyPart(copyRequest1));

            CopyPartRequest copyRequest2 = new CopyPartRequest()
               .WithDestinationBucket(targetBucket)
               .WithDestinationKey(targetObjectKey)
               .WithSourceBucket(sourceBucket)
               .WithSourceKey(sourceObjectKey2)
               .WithUploadID(uploadId)
               .WithFirstByte(bytePosition)
               .WithLastByte(objectSize2 - 1)
               .WithPartNumber(2);

            copyResponses.Add(s3Client.CopyPart(copyRequest2));

            ////
            CompleteMultipartUploadRequest completeRequest =
                  new CompleteMultipartUploadRequest()
                     .WithBucketName(targetBucket)
                     .WithKey(targetObjectKey)
                     .WithUploadId(initResponse.UploadId)
                     .WithPartETags(GetETags(copyResponses));

            CompleteMultipartUploadResponse completeUploadResponse =
                s3Client.CompleteMultipartUpload(completeRequest);

        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

But it is throwing exception at the last line CompleteMultipartUpload. Below is the S3 exception: Your proposed upload is smaller than the minimum allowed size

Where as if i only upload copyRequest1 it works fine.

Any help is appreciated!!

Regards,
Haseena


问:
How to pass variable from one frame to another in Animate cc with JS

Hi all, I wanted to reference a variable from one frame in the current frame with Animate CC with JS.

For example, below are the codes of a frame:

var p1=new Object();
p1.classes = middle;

Then I wanted to use p1 in another frame and I tried the following codes:

alert("this p1 classes is: ", p1.classes);

But an error of "Uncaught ReferenceError: p_p is not defined" is shown in the console

So, may I know how to pass one variable to another frame in Animate CC with js please? Thanks for any help.

答:
The problem in declaring your variables and/or objects inside a frame, is that the scope is restricted to that frame, preventing your variables and/or objects to be used in other frames:

Frames code

```<code>// Frame 0
this.frame_0 = function() {
    /* The p1 object can only be used in this frame. */
    var p1 = new Object();

    /* Let's use something more appropiate for your alert box.
       In this case is a string as a property of your object. */
    p1.classes = "middle";
}

// Frame 1
this.frame_1 = function() {
    /*  As a string is being used as a property of your object,
        I changed a little bit of your code, to display that string in the alert box.
        This will give you an error (p1 not defined),
        because the p1 object can't be used in this frame. */
    alert("this p1 classes is: " + p1.classes);

    /* Stop the timeline */
    this.stop();
}
</code>```

To avoid that behaviour, you need to change the scope. There are two ways, depending on what scope you want to use:

Option 1: Clip-level scope

The scope is restricted to the current Movieclip, meaning that your variable or object can be used in any frame of that MovieClip.

```<code>this.p1 = new Object();
this.p1.classes = "middle";
</code>```

Frames code

```<code>// Frame 0
this.frame_0 = function() {
    this.p1 = new Object();
    this.p1.classes = "middle";
}

// Frame 1
this.frame_1 = function() {
    alert("this p1 classes is: " + this.p1.classes);

    this.stop();
}
</code>```

Option 2: Global scope

By not declaring your variable or object, the scope has no restrictions. It can be used in any frame of any MovieClip.

```<code>p1 = new Object();
p1.classes = "middle";
</code>```

Frames code

```<code>// Frame 0
this.frame_0 = function() {
    p1 = new Object();
    p1.classes = "middle";
}

// Frame 1
this.frame_1 = function() {
    alert("this p1 classes is: " + p1.classes);

    this.stop();
}
</code>```

Side note: Object creation

If you are creating a object, for performance and simplicity, it's better to use an object literal instead of new Object().

```<code>// Option 1
this.p1 = {classes:"middle"};

// Option 2
p1 = {classes:"middle"};
</code>```

Body:
The problem in declaring your variables and/or objects inside a frame, is that the scope is restricted to that frame, preventing your variables and/or objects to be used in other frames:

Frames code

// Frame 0
this.frame_0 = function() {
    /* The p1 object can only be used in this frame. */
    var p1 = new Object();

    /* Let's use something more appropiate for your alert box.
       In this case is a string as a property of your object. */
    p1.classes = "middle";
}

// Frame 1
this.frame_1 = function() {
    /*  As a string is being used as a property of your object,
        I changed a little bit of your code, to display that string in the alert box.
        This will give you an error (p1 not defined),
        because the p1 object can't be used in this frame. */
    alert("this p1 classes is: " + p1.classes);

    /* Stop the timeline */
    this.stop();
}

To avoid that behaviour, you need to change the scope. There are two ways, depending on what scope you want to use:

Option 1: Clip-level scope

The scope is restricted to the current Movieclip, meaning that your variable or object can be used in any frame of that MovieClip.

this.p1 = new Object();
this.p1.classes = "middle";

Frames code

// Frame 0
this.frame_0 = function() {
    this.p1 = new Object();
    this.p1.classes = "middle";
}

// Frame 1
this.frame_1 = function() {
    alert("this p1 classes is: " + this.p1.classes);

    this.stop();
}

Option 2: Global scope

By not declaring your variable or object, the scope has no restrictions. It can be used in any frame of any MovieClip.

p1 = new Object();
p1.classes = "middle";

Frames code

// Frame 0
this.frame_0 = function() {
    p1 = new Object();
    p1.classes = "middle";
}

// Frame 1
this.frame_1 = function() {
    alert("this p1 classes is: " + p1.classes);

    this.stop();
}

Side note: Object creation

If you are creating a object, for performance and simplicity, it's better to use an object literal instead of new Object().

// Option 1
this.p1 = {classes:"middle"};

// Option 2
p1 = {classes:"middle"};


问:
How to get files contained in a path
In the following path:

```<code>app/test/vehicle/
</code>```

there are several .js file. Is there any way in Javascript where I can get the number of .js file contains in the above-mentioned path?

I am using webStorm environment

答:
Yes, using node:

```<code>const fs = require('fs');
const dir = './directory';

fs.readdir(dir, (err, files) => {
  console.log(files.length);
});
</code>```

https://stackoverflow.com/a/43747896/3650835

Title: How to get files contained in a path

Body:
In the following path:

app/test/vehicle/

there are several .js file. Is there any way in Javascript where I can get the number of .js file contains in the above-mentioned path?

I am using webStorm environment

Body:
Yes, using node:

const fs = require('fs');
const dir = './directory';

fs.readdir(dir, (err, files) => {
  console.log(files.length);
});

https://stackoverflow.com/a/43747896/3650835


问:
Need a formula to get total LUN size using lunSizeLow and lunSizeHigh SNMP objects
I have 2 SNMP Objects/OIDs. Below are the details:

Object1:

```<code>Name: lunSizeLow

OID: 1.3.6.1.4.1.43906.1.4.3.2.3.1.9

Description: `LUN` size in bytes - low order bytes
</code>```

Object2:

```<code>Name: lunSizeHigh

OID: 1.3.6.1.4.1.43906.1.4.3.2.3.1.10

Description: `LUN` size in bytes - high order bytes
</code>```

My requirement:

I want to monitor LUN size through some script. But i didn't found any SNMP object, which can give total LUN size directly. I found 2 separate objects (lunSizeLow and lunSizeHigh) to get LUN total size, so i need a formula to get total LUN size using these 2 low order and high order SNMP objects (lunSizeLow and lunSizeHigh).

I gone through many articles over internet and i found couple of formulas in community.hpe.com.

But I'm not sure which one is correct.

Formula 1:

Max unsigned number that can be stored in 32bits counter is 4294967295.

Total size would be: LOW_ORDER_BYTES + HIGH_ORDER_BYTES * 4294967296

Formula 2:

Total size in GB is LOW_ORDER_BYTES / 1073741824 + HIGH_ORDER_BYTES * 4

Could any one help me to get correct formula.

答:
Most languages will have the bit-shift operator, allowin you to do something similar to the below (pseudo-Java):

```<code>long myBigInteger = lunSizeHigh
myBigInteger << 32 # Shifts the high bits 32 positions to the left, into the high half of the long
myBigInteger = myBigInteger + lunSizeLow
</code>```

This has two advantages over multiplying:

Bit shifting is often faster than multiplication, even though most compilers would optimize that particular multiplication into a bit shift anyway.

It is easier to read the code and understand why this would provide the correct answer, given the description from the MIB. Magic numbers should be avoided where possible.

That aside, putting some numbers into the Windows Calculator (using Programmer Mode) and trying formula 1, we can see that it works.

Now, you don't specify what language or environment you're working in, and in some languages you won't have any number type that supports the size of numbers you want to manipulate. (Same reason that this number had to be split into two counters to begin with - it's larger than the largest number representation available on some (primitive) platforms.) If you want to do it using multiplication, you'll have to make sure your implementation language can do better.

Body:
I have 2 SNMP Objects/OIDs. Below are the details:

Object1:

Name: lunSizeLow

OID: 1.3.6.1.4.1.43906.1.4.3.2.3.1.9

Description: `LUN` size in bytes - low order bytes

Object2:

Name: lunSizeHigh

OID: 1.3.6.1.4.1.43906.1.4.3.2.3.1.10

Description: `LUN` size in bytes - high order bytes

My requirement:

I want to monitor LUN size through some script. But i didn't found any SNMP object, which can give total LUN size directly. I found 2 separate objects (lunSizeLow and lunSizeHigh) to get LUN total size, so i need a formula to get total LUN size using these 2 low order and high order SNMP objects (lunSizeLow and lunSizeHigh).

I gone through many articles over internet and i found couple of formulas in community.hpe.com.

But I'm not sure which one is correct.

Formula 1:

Max unsigned number that can be stored in 32bits counter is 4294967295.

Total size would be: LOW_ORDER_BYTES + HIGH_ORDER_BYTES * 4294967296

Formula 2:

Total size in GB is LOW_ORDER_BYTES / 1073741824 + HIGH_ORDER_BYTES * 4

Could any one help me to get correct formula.

Body:
Most languages will have the bit-shift operator, allowin you to do something similar to the below (pseudo-Java):

long myBigInteger = lunSizeHigh
myBigInteger << 32 # Shifts the high bits 32 positions to the left, into the high half of the long
myBigInteger = myBigInteger + lunSizeLow

This has two advantages over multiplying:

Bit shifting is often faster than multiplication, even though most compilers would optimize that particular multiplication into a bit shift anyway.

It is easier to read the code and understand why this would provide the correct answer, given the description from the MIB. Magic numbers should be avoided where possible.

That aside, putting some numbers into the Windows Calculator (using Programmer Mode) and trying formula 1, we can see that it works.

Now, you don't specify what language or environment you're working in, and in some languages you won't have any number type that supports the size of numbers you want to manipulate. (Same reason that this number had to be split into two counters to begin with - it's larger than the largest number representation available on some (primitive) platforms.) If you want to do it using multiplication, you'll have to make sure your implementation language can do better.


问:
log4net is not logging to log file or console (external log4net.config file)
I created a a file called log4net.config in my project and added the following configuration:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="console" />
      <appender-ref ref="RollingFileAppender" />
    </root>
    <appender name="console" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="${LOCALAPPDATA}\MyApp\LogFile.log" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5level [%d{yyyy-MM-dd hh:mm:ss}] [%thread] (Line:%line) %M: - %m%n" />
      </layout>
    </appender>
  </log4net>
</configuration>
</code>```

After that, I added the line below to my AssemblyInfo.cs file:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

In the application, I have the following static class:

```<code>public static class Logger
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static void LogInfo(string msg)
        {
            log.Info(msg);
        }

        public static void LogDebug(string msg)
        {
            log.Debug(msg);
        }

        public static void LogWarn(string msg, Exception e)
        {
            log.Warn(msg, e);
        }

        public static void LogError(string msg, Exception e)
        {
            log.Error(msg, e);
        }
    }
</code>```

Then I'm trying to log somewhere in the application in another class using Logger.LogDebug("Error logger working.");

However, I can't see any log file being created or written to it. What am I doing wrong?

UPDATE:

I also added the following in my app.config file but I see nothing at all on my Output console...

```<code><appSettings>
    <add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</code>```

答:
If you have the log4net configuration in a log4net logging configuration file, you do not have to add the configuration of the web.config (configuration tag and sections). Just add the log4net tags:</p>

```<code><log4net>
<root>
  <level value="ALL" />
  <appender-ref ref="console" />
  <appender-ref ref="RollingFileAppender" />
</root>
<appender name="console" type="log4net.Appender.ConsoleAppender">
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %level %logger - %message%newline" />
  </layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
  <param name="File" value="${LOCALAPPDATA}\MyApp\LogFile.log" />
  <param name="AppendToFile" value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="10MB" />
  <staticLogFileName value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <param name="ConversionPattern" value="%-5level [%d{yyyy-MM-dd hh:mm:ss}] [%thread] (Line:%line) %M: - %m%n" />
  </layout>
</appender>
</log4net>
</code>```

Body:
I created a a file called log4net.config in my project and added the following configuration:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="console" />
      <appender-ref ref="RollingFileAppender" />
    </root>
    <appender name="console" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="${LOCALAPPDATA}\MyApp\LogFile.log" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5level [%d{yyyy-MM-dd hh:mm:ss}] [%thread] (Line:%line) %M: - %m%n" />
      </layout>
    </appender>
  </log4net>
</configuration>

After that, I added the line below to my AssemblyInfo.cs file:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

In the application, I have the following static class:

public static class Logger
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static void LogInfo(string msg)
        {
            log.Info(msg);
        }

        public static void LogDebug(string msg)
        {
            log.Debug(msg);
        }

        public static void LogWarn(string msg, Exception e)
        {
            log.Warn(msg, e);
        }

        public static void LogError(string msg, Exception e)
        {
            log.Error(msg, e);
        }
    }

Then I'm trying to log somewhere in the application in another class using Logger.LogDebug("Error logger working.");

However, I can't see any log file being created or written to it. What am I doing wrong?

UPDATE:

I also added the following in my app.config file but I see nothing at all on my Output console...

<appSettings>
    <add key="log4net.Internal.Debug" value="true"/>
</appSettings>

Body:
If you have the log4net configuration in a log4net logging configuration file, you do not have to add the configuration of the web.config (configuration tag and sections). Just add the log4net tags:

<log4net>
<root>
  <level value="ALL" />
  <appender-ref ref="console" />
  <appender-ref ref="RollingFileAppender" />
</root>
<appender name="console" type="log4net.Appender.ConsoleAppender">
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %level %logger - %message%newline" />
  </layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
  <param name="File" value="${LOCALAPPDATA}\MyApp\LogFile.log" />
  <param name="AppendToFile" value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="10MB" />
  <staticLogFileName value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <param name="ConversionPattern" value="%-5level [%d{yyyy-MM-dd hh:mm:ss}] [%thread] (Line:%line) %M: - %m%n" />
  </layout>
</appender>
</log4net>


答:
Since javascript doesn't have local filesystem access when run in the browser, there is no way to access local files from javascript. If you are asking about accessing all files hosted on a cdn or something similar in that directory, there is still no way to tell which requests will return a 20x.

If you are using nodejs, use the fs.readdir function:

```<code>const fs = require('fs');

fs.readdir('app/test/vehicle/', (err, files) => {
  files.forEach(file => { console.log(file);} );
})
</code>```

Title: How to get files contained in a path

Body:
Since javascript doesn't have local filesystem access when run in the browser, there is no way to access local files from javascript. If you are asking about accessing all files hosted on a cdn or something similar in that directory, there is still no way to tell which requests will return a 20x.

If you are using nodejs, use the fs.readdir function:

const fs = require('fs');

fs.readdir('app/test/vehicle/', (err, files) => {
  files.forEach(file => { console.log(file);} );
})


问:
When I try to install body parser with npm, I get npm does not support Node.js v9.2.0
Console error:</p>

```<code>npm WARN npm npm does not support Node.js v9.2.0
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8.
npm WARN npm You can find the latest version at https://nodejs.org/
WARNING: You are likely using a version of node-tar or npm that is incompatible with this version of Node.js.
Please use either the version of npm that is bundled with Node.js, or a version of npm (> 5.5.1 or < 5.4.0) or node-tar (> 4.0.1) that is compatible with Node.js 9 and above.
C:\Program Files\nodejs\node.exe: src\node_zlib.cc:437: Assertion `args.Length() == 7 && "init(windowBits, level, memLevel, strategy, writeResult, writeCallback," " dictionary)"' failed.
</code>```

答:
Uninstall previous version of Node as well as deleting %AppData%\npm and %AppData%\npm-cache. Then install Node 9.0.0 and you should be fine.

Warning: You will have to install all global packages again after doing npm cache clear.

Body:
Console error:

npm WARN npm npm does not support Node.js v9.2.0
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8.
npm WARN npm You can find the latest version at https://nodejs.org/
WARNING: You are likely using a version of node-tar or npm that is incompatible with this version of Node.js.
Please use either the version of npm that is bundled with Node.js, or a version of npm (> 5.5.1 or < 5.4.0) or node-tar (> 4.0.1) that is compatible with Node.js 9 and above.
C:\Program Files\nodejs\node.exe: src\node_zlib.cc:437: Assertion `args.Length() == 7 && "init(windowBits, level, memLevel, strategy, writeResult, writeCallback," " dictionary)"' failed.