问:
Build action 'EmbeddedResource' is not supported by one or more of the project's targets
I am new to Xamarin platform, and am facing the error

Build action 'EmbeddedResource' is not supported by one or more of the project's targets. Am debugging in emulator 8.1 for windows phone, and my project is a Xamarin.form(portable).

答: Also was receiving this when the Windows path was over 260 characters with fully qualified file name.  Look in the output of the build and if you see a message about file length over 260, move your project to shorter directory path.  </p>


来源: stackexchange

问:
Upsert (update or insert) in Sybase ASE?
I'm writing an application to move data from Oracle to Sybase and need to perform update / insert operations. In Oracle, I'd use MERGE INTO, but it doesn't seem to be available in Sybase (not in ASE, anyway). I know this can be done with multiple statements, but for a couple of reasons, I'm really trying to get this into a single statement.

Any suggestions?

答:
Sybase and DB2 are very IEC/ISO/ANSI SQL Standrd-compliant.  MS a little less so.

Oracle is not very Standard-compliant at all (despite what the glossies say). More important, due to it limitations, the method they use to overcome them is to introduce Extensions to SQL (which are not required for the others DBMS, which do not have the limitations).  Nice way of making sure that customers do not migrate away.

So the best advice for you is to learn the SQL Standard way of doing whatever you were doing on the Oracle side.  And second (not first) learn about Sybases or DB2s (or whatever) Extensions.

"MERGE" and "UPSERT" do not exist in SQL, they exist in Oracle only.  The bottom line is, you have to UPDATE and INSERT in two separate operations.

In SQL, UPDATE and INSERT apply to a single table; you may have quite complex FROM clauses.

For "MERGE", that is simply an:

```<code>INSERT target ( column_list ) -- we do have defaults
SELECT ( column_list )
    FROM source
    WHERE primary_key NOT IN ( SELECT primary_key FROM target )
</code>```

Update is simply the complement:

```<code>UPDATE target SET ( target_column = source_column, ... )
    FROM source
    WHERE primary_key IN ( SELECT primary_key FROM target )
</code>```

In the UPDATE it is easy to merge the WHERE conditions and eliminate the Subquery (I am showing it to you for explanation).

As I understand it, Oracle is abyssmal at executing Subqueries (Standard SQL).  Which is why they have all these non-Standard "MERGE", etc., the purpose of which is to avoid the Standard Subquery syntax, which every other DBMS performs with ease.

ContentLicense: CC BY-SA 2.5

Body:
Sybase and DB2 are very IEC/ISO/ANSI SQL Standrd-compliant.  MS a little less so.

Oracle is not very Standard-compliant at all (despite what the glossies say). More important, due to it limitations, the method they use to overcome them is to introduce Extensions to SQL (which are not required for the others DBMS, which do not have the limitations).  Nice way of making sure that customers do not migrate away.

So the best advice for you is to learn the SQL Standard way of doing whatever you were doing on the Oracle side.  And second (not first) learn about Sybases or DB2s (or whatever) Extensions.

"MERGE" and "UPSERT" do not exist in SQL, they exist in Oracle only.  The bottom line is, you have to UPDATE and INSERT in two separate operations.

In SQL, UPDATE and INSERT apply to a single table; you may have quite complex FROM clauses.

For "MERGE", that is simply an:

INSERT target ( column_list ) -- we do have defaults
SELECT ( column_list )
    FROM source
    WHERE primary_key NOT IN ( SELECT primary_key FROM target )

Update is simply the complement:

UPDATE target SET ( target_column = source_column, ... )
    FROM source
    WHERE primary_key IN ( SELECT primary_key FROM target )

In the UPDATE it is easy to merge the WHERE conditions and eliminate the Subquery (I am showing it to you for explanation).

As I understand it, Oracle is abyssmal at executing Subqueries (Standard SQL).  Which is why they have all these non-Standard "MERGE", etc., the purpose of which is to avoid the Standard Subquery syntax, which every other DBMS performs with ease.

ContentLicense: CC BY-SA 3.0


问:
Why does my code produce the error: The statement did not return a result set
I am executing the following query from Microsoft SQL Server Studio, which works fine and displays results:

SELECT *
INTO   #temp_table
FROM   md_criteria_join
WHERE  user_name = 'tecgaw'

UPDATE #temp_table
SET    user_name = 'tec'
WHERE  user_name != 'tec'

SELECT *
FROM   md_criteria_join
WHERE  user_name = 'tec'
   AND view_name NOT IN (SELECT view_name
                         FROM   md_criteria_join
                         WHERE  user_name = 'tecgaw')
UNION
SELECT *
FROM   #temp_table
ORDER  BY view_name,
      user_name,
      crit_usage_seq,
      crit_join_seq
```

<p>However, if I execute the same query in Java, an Exception is thrown stating </p>

<blockquote>
  <p>The statement did not return a result set.</p>
</blockquote>

<p>Here's the Java code:</p>

<pre class="lang-java prettyprint-override"><code>statement = conn.getConnection().createStatement();
resultSet = stmt.executeQuery(sql.toString());
</code>```

Is that because I cannot do multiple SQL queries in one statement (I.e., Creating the #temp_table, updating it, and then using for it my select statement)?

答: in ms sql you also have to do set nocount on right at the beginning of the stored procedure along with terminating select / update/ insert block statement with ";"</p>

ContentLicense: CC BY-SA 4.0

Body:
I am executing the following query from Microsoft SQL Server Studio, which works fine and displays results:

SELECT *
INTO   #temp_table
FROM   md_criteria_join
WHERE  user_name = 'tecgaw'

UPDATE #temp_table
SET    user_name = 'tec'
WHERE  user_name != 'tec'

SELECT *
FROM   md_criteria_join
WHERE  user_name = 'tec'
   AND view_name NOT IN (SELECT view_name
                         FROM   md_criteria_join
                         WHERE  user_name = 'tecgaw')
UNION
SELECT *
FROM   #temp_table
ORDER  BY view_name,
      user_name,
      crit_usage_seq,
      crit_join_seq

However, if I execute the same query in Java, an Exception is thrown stating

The statement did not return a result set.

Here's the Java code:

statement = conn.getConnection().createStatement();
resultSet = stmt.executeQuery(sql.toString());

Is that because I cannot do multiple SQL queries in one statement (I.e., Creating the #temp_table, updating it, and then using for it my select statement)?


问:
Load Connection String from Config File in Azure Functions
In my Azure Function I am using a Library which establishes a connection to an SQL server via the ConnectionString from the ConfigurationManager like this:

```<code>var cs = System.Configuration.ConfigurationManager.ConnectionStrings["DbConString"].ConnectionString;
DbConnection connection = new SqlConnection(cs);
</code>```

Now when i set the connection string DbConString in the portal via the Application Settings everything is working fine. But for local development I use the azure-functions-cli and unfortunately I have no idea where i should place the connection string to have it loaded correctly via the ConfigurationManager.

I've tried to place it in the appsettings.json file but without success.

Edit:
My appsettings.json currently looks like this:

```<code>{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsDashboard": "",
    "MyServiceBusReader": "Endpoint=sb://xxxx=",
    "DbConStr1": "data source=(localdb)\\MSSQLLocalDB;initial catalog=MyDb;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework",
    "ConnectionStrings": {
      "DbConStr2": "data source=(localdb)\\MS..."
    }
  }
}
</code>```

But I am not able to access "DbConStr1" via the ConfigurationManager.
Adding "DbConStr2" within "ConnectionStrings" like described here leads to a compilation error. Maybe because I am not using .NET Core?

Edit2:
I messed up the nesting of "ConnectionStrings". It has to be on the same nesting level as "Values":

```<code>{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsDashboard": "",
    "MyServiceBusReader": "Endpoint=sb://xxxx="
  },
  "ConnectionStrings": {
    "DbConStr": "data source=(localdb)\\MS..."
  }
}
</code>```

答:
I had this same issue and am using .net standard (as opposed to core). I added my settings to the Application Settings section of my Azure function (in Azure Portal):-

I then downloaded a zip of the function:-

Included in this download is a copy of local.settings.json that includes my app settings in the correct json format.  I then access them via ConfigurationManager.Appsettings["mysetting"]

Body:
In my Azure Function I am using a Library which establishes a connection to an SQL server via the ConnectionString from the ConfigurationManager like this:

var cs = System.Configuration.ConfigurationManager.ConnectionStrings["DbConString"].ConnectionString;
DbConnection connection = new SqlConnection(cs);

Now when i set the connection string DbConString in the portal via the Application Settings everything is working fine. But for local development I use the azure-functions-cli and unfortunately I have no idea where i should place the connection string to have it loaded correctly via the ConfigurationManager.

I've tried to place it in the appsettings.json file but without success.

Edit:
My appsettings.json currently looks like this:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsDashboard": "",
    "MyServiceBusReader": "Endpoint=sb://xxxx=",
    "DbConStr1": "data source=(localdb)\\MSSQLLocalDB;initial catalog=MyDb;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework",
    "ConnectionStrings": {
      "DbConStr2": "data source=(localdb)\\MS..."
    }
  }
}

But I am not able to access "DbConStr1" via the ConfigurationManager.
Adding "DbConStr2" within "ConnectionStrings" like described here leads to a compilation error. Maybe because I am not using .NET Core?

Edit2:
I messed up the nesting of "ConnectionStrings". It has to be on the same nesting level as "Values":

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsDashboard": "",
    "MyServiceBusReader": "Endpoint=sb://xxxx="
  },
  "ConnectionStrings": {
    "DbConStr": "data source=(localdb)\\MS..."
  }
}


问:
How to perform multiple finds for regex containing group with multiple lines?

Platform: Java

Current pattern:(/[^:" ()]+\..[^: "()]+).*(\d.*?):(\d.*)?.*?((?:warning|error|note): .+)

Problem: for group 4, it only matches to the end of line. If I add DOTALL it finds only one set of groups with the description of the last find.

Input for which I want to find a match - the one that goes into pattern.compile(String):

```<code>Build failed: Command failed with exit code 1.
stderr: /sample/path/to/SampleFile.java:1: error: [PackageLocation] Expected package /sample/path/to/ to be declared in a directory ending with /sample/path/to, instead found /sample/path/To
package sample.path.to;
                   ^
    (see http://errorprone.info/bugpattern/PackageLocation)
/sample/path/to/SampleFile2.java:-1: note: Some input files use or override a deprecated API.

/sample/path/to/SampleFile2.java:-1:6 note: Recompile with -Xlint:deprecation for details.
</code>```

Expected output:

Find 0

group 1: /sample/path/to/SampleFile.java

group 2: 1

group 3: null

group 4: error: [PackageLocation] Expected package /sample/path/to/ to be declared in a directory ending with /sample/path/to, instead found /sample/path/To;
               ^
(see http://errorprone.info/bugpattern/PackageLocation)

Find 1

group 1: /sample/path/to/SampleFile2.java

group 2: 1

group 3: null

group 4: note: Some input files use or override a deprecated API.

Find 2

group 1: /sample/path/to/SampleFile2.java

group 2: 1

group 3: 6

group 4: note: Recompile with -Xlint:deprecation for details.

答:
Code

Making some slight modifications to your regex, you can use this.

See regex in use here

```<code>(/[^:" ()]+\..[^: "()]+):-?(\d.*?):(\d.*)?.*?((?:warning|error|note): (?:(?![\r\n]{2})[\s\S])+)
                        ^^^                                           ^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

Explanation

Instead of counting on the end of the line to determine the end of the match, I decided to use a double newline character (since this seems to be a common delimiter between the 3 lines). I'll focus on explaining the parts I added/modified.

I changed .* to :-?

While this may be a small change, it could potentially help you to not catch incorrect parts of the string in the future.

(?:(?![\r\n]{2})[\s\S])+ Match the following one or more times (tempered greedy token)

(?![\r\n]{2}) Negative lookahead ensuring what follows is not exactly two newline characters

[\s\S] Match any character (including newline characters)

Body:
Platform: Java

Current pattern:(/[^:" ()]+\..[^: "()]+).*(\d.*?):(\d.*)?.*?((?:warning|error|note): .+)

Problem: for group 4, it only matches to the end of line. If I add DOTALL it finds only one set of groups with the description of the last find.

Input for which I want to find a match - the one that goes into pattern.compile(String):

Build failed: Command failed with exit code 1.
stderr: /sample/path/to/SampleFile.java:1: error: [PackageLocation] Expected package /sample/path/to/ to be declared in a directory ending with /sample/path/to, instead found /sample/path/To
package sample.path.to;
                   ^
    (see http://errorprone.info/bugpattern/PackageLocation)
/sample/path/to/SampleFile2.java:-1: note: Some input files use or override a deprecated API.

/sample/path/to/SampleFile2.java:-1:6 note: Recompile with -Xlint:deprecation for details.

Expected output:

Find 0

group 1: /sample/path/to/SampleFile.java

group 2: 1

group 3: null

group 4: error: [PackageLocation] Expected package /sample/path/to/ to be declared in a directory ending with /sample/path/to, instead found /sample/path/To;
               ^
(see http://errorprone.info/bugpattern/PackageLocation)

Find 1

group 1: /sample/path/to/SampleFile2.java

group 2: 1

group 3: null

group 4: note: Some input files use or override a deprecated API.

Find 2

group 1: /sample/path/to/SampleFile2.java

group 2: 1

group 3: 6

group 4: note: Recompile with -Xlint:deprecation for details.

Body:
Code

Making some slight modifications to your regex, you can use this.

See regex in use here

(/[^:" ()]+\..[^: "()]+):-?(\d.*?):(\d.*)?.*?((?:warning|error|note): (?:(?![\r\n]{2})[\s\S])+)
                        ^^^                                           ^^^^^^^^^^^^^^^^^^^^^^^^

Explanation

Instead of counting on the end of the line to determine the end of the match, I decided to use a double newline character (since this seems to be a common delimiter between the 3 lines). I'll focus on explaining the parts I added/modified.

I changed .* to :-?

While this may be a small change, it could potentially help you to not catch incorrect parts of the string in the future.

(?:(?![\r\n]{2})[\s\S])+ Match the following one or more times (tempered greedy token)

(?![\r\n]{2}) Negative lookahead ensuring what follows is not exactly two newline characters

[\s\S] Match any character (including newline characters)


问:
What is Amazon Web Services RDS month-to-date usage?
I have one RDS instance on AWS under the free tier, and I've been monitoring the resources I'm using. Under the free tier, I have 20 GB-Mo of RDS - Storage and 750 Hrs of RDS - Instance. I have just one RDS instance, but my Month-end forecasted usage surpasses the free tier limits, even if I'm not even using it (the RDS Instance is active, but I'm not effectively using it for anything yet).

Since I have just one RDS instance active, it doesn't make sense that I'm surpassing RDS instance free tier usage, I think. I just wanted to clarify if those two services (RDS-Storage and RDS-Instance) actually mean what I think (RDS-Storage is the amount of actual storage I'm using from my RDS database and RDS-Instance is the amount of time the instance has been running since the start of the month, right?).

Am I missing anything? (I know that I'm not giving much information, but I'm new to AWS and I don't know which kind of information would be useful)

答:
AWS only can answer this question and here is their explanation.

The "Forecast" function is designed to be a rough prediction of your
  monthly AWS usage, based on your month-to-date charges.

Although most AWS services bill on-demand, meaning your overall bill
  steadily increases over the course of a month, some services or
  features bill a larger amount once, usually on or near the first of
  the month.

This might cause your forecasted usage to appear higher than you
  expect at the beginning of a month, because your average daily cost is
  higher at the beginning of the month than it will be over the course
  of that month. As the month progresses, your usage should normalize,
  and the forecast will be a more accurate prediction of your final
  monthly bill.

More can be read from :

https://aws.amazon.com/premiumsupport/knowledge-center/high-aws-cost-forecast/

http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-forecast.html


问:
Stop Python Gtk.Application using Ctrl+C
I am creating an application. Previously, I were using Gtk.Main() to start my application, and created some hooks to stop the application from the command line using Ctrl+C. Now, I have migrated the application to a more "standard" Gtk.Application, but can't get it to stop using Ctrl+C.

This is a very simple Gtk.Application, that when is run from the command line, it can't be stopped using Ctrl+C:

```<code>from gi.repository import Gtk
import sys

# a Gtk ApplicationWindow

class MyWindow(Gtk.ApplicationWindow):
    # constructor: the title is "Welcome to GNOME" and the window belongs
    # to the application app

    def __init__(self, app):
        Gtk.Window.__init__(self, title="Welcome to GNOME", application=app)

class MyApplication(Gtk.Application):
    # constructor of the Gtk Application

    def __init__(self):
        Gtk.Application.__init__(self)

    # create and activate a MyWindow, with self (the MyApplication) as
    # application the window belongs to.
    # Note that the function in C activate() becomes do_activate() in Python
    def do_activate(self):
        win = MyWindow(self)
        # show the window and all its content
        # this line could go in the constructor of MyWindow as well
        win.show_all()

    # start up the application
    # Note that the function in C startup() becomes do_startup() in Python
    def do_startup(self):
        Gtk.Application.do_startup(self)

# create and run the application, exit with the value returned by
# running the program
app = MyApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)
</code>```

答:
```<code>import signal
from gi.repository import GLib

...

GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, app.quit)
</code>```

Body:
I am creating an application. Previously, I were using Gtk.Main() to start my application, and created some hooks to stop the application from the command line using Ctrl+C. Now, I have migrated the application to a more "standard" Gtk.Application, but can't get it to stop using Ctrl+C.

This is a very simple Gtk.Application, that when is run from the command line, it can't be stopped using Ctrl+C:

from gi.repository import Gtk
import sys

# a Gtk ApplicationWindow

class MyWindow(Gtk.ApplicationWindow):
    # constructor: the title is "Welcome to GNOME" and the window belongs
    # to the application app

    def __init__(self, app):
        Gtk.Window.__init__(self, title="Welcome to GNOME", application=app)

class MyApplication(Gtk.Application):
    # constructor of the Gtk Application

    def __init__(self):
        Gtk.Application.__init__(self)

    # create and activate a MyWindow, with self (the MyApplication) as
    # application the window belongs to.
    # Note that the function in C activate() becomes do_activate() in Python
    def do_activate(self):
        win = MyWindow(self)
        # show the window and all its content
        # this line could go in the constructor of MyWindow as well
        win.show_all()

    # start up the application
    # Note that the function in C startup() becomes do_startup() in Python
    def do_startup(self):
        Gtk.Application.do_startup(self)

# create and run the application, exit with the value returned by
# running the program
app = MyApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)


问:
All content is unclickable inside bootrstrap `row`
I create cards on API response with this function:

```<code>function createCard(name, img, description) {
$('#result').append(`
  <div class="col-md-4 col-sm-6 col-xs-12">
    <div class="card" style="height: 200px; border: 2px solid black; border-radius: 5px; overflow: hidden; padding: 15px; margin: 15px 0;">
      <div class="card-content" style="height: 100%; overflow: hidden;">
        <div class="star" style="height: 1.6em;">
          <span class="glyphicon glyphicon-star-empty pull-right"></span>
        </div>
        <div class="row">
          <div class="image col-xs-4" style="margin-top: 10px;">
            <figure style="height: 120px;">
              <img src=${img} alt="" style="max-width: 100%; max-height: 100%;">
            </figure>
          </div>
          <div class="description col-xs-8">
            <h4>${name}</h4>
            <p>${description}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
  `);
}
</code>```

And here is the result block:

```<code><div id="result" class="row"></div>
</code>```

And here is the jquery event handler:

```<code>$('.star').on('click', function() {
  console.log("!")
});
</code>```

The problem is that there's no console log not only with star block but with any other inside the result block while it's ok with the result itself.

By the way, it's absolutely fine to apply hover pseudo class styling on star element which works just perfectly good. So, I can see how a glyphicon changes it's color on hover but it doesn't respond on click event.

So, my question is why all the content inside bootstrap row class is unclickable?

答:
Your content is loaded dynamically. So you need to delegate the events to a static parent.

```<code>$(document).on('click', '.star', function() {
  console.log("!")
});
</code>```

As above example, please use a static parent and not document. Use document when there's no static parent.

$(function() {
  $(document).on('click', '.star', function() {
    console.log("!")
  });
});

function createCard (name, img, description) {
  $('#result').append(`

${name}

${description}

  `);
}

createCard ("Hello World 1!", "//placehold.it/100", "Hello World 1!");
createCard ("Hello World 2!", "//placehold.it/100", "Hello World 2!");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result" class="row"></div></code>```

The console.log works when I click on the above snippet:

Body:
I create cards on API response with this function:

function createCard(name, img, description) {
$('#result').append(`

${name}

${description}

  `);
}

And here is the result block:

And here is the jquery event handler:

$('.star').on('click', function() {
  console.log("!")
});

The problem is that there's no console log not only with star block but with any other inside the result block while it's ok with the result itself.

By the way, it's absolutely fine to apply hover pseudo class styling on star element which works just perfectly good. So, I can see how a glyphicon changes it's color on hover but it doesn't respond on click event.

So, my question is why all the content inside bootstrap row class is unclickable?

Body:
Your content is loaded dynamically. So you need to delegate the events to a static parent.

$(document).on('click', '.star', function() {
  console.log("!")
});

As above example, please use a static parent and not document. Use document when there's no static parent.

$(function() {
  $(document).on('click', '.star', function() {
    console.log("!")
  });
});

function createCard (name, img, description) {
  $('#result').append(`
  <div class="col-md-4 col-sm-6 col-xs-12">
    <div class="card" style="height: 200px; border: 2px solid black; border-radius: 5px; overflow: hidden; padding: 15px; margin: 15px 0;">
      <div class="card-content" style="height: 100%; overflow: hidden;">
        <div class="star" style="height: 1.6em;">
          <span class="glyphicon glyphicon-star-empty pull-right"></span>
        </div>
        <div class="row">
          <div class="image col-xs-4" style="margin-top: 10px;">
            <figure style="height: 120px;">
              <img src=${img} alt="" style="max-width: 100%; max-height: 100%;">
            </figure>
          </div>
          <div class="description col-xs-8">
            <h4>${name}</h4>
            <p>${description}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
  `);
}

createCard ("Hello World 1!", "//placehold.it/100", "Hello World 1!");
createCard ("Hello World 2!", "//placehold.it/100", "Hello World 2!");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result" class="row"></div>

The console.log works when I click on the above snippet:


问:
When does Perl ref($something) return "ARRAY(0x913310)"?
I have some complex Perl code that tests the value of $val = ref($something). Unfortunately my code fails, because there is a situation where $val is "ARRAY(0x913310)" and not "ARRAY" (according to the Perl debugger).

Reading the documentation of ref(), such a value is not listed as one of the possible return values. Also, when trying to reproduce interactively in the debugger, I only see valid return values.

Could this be a bug in the Perl base?
I'm using Perl 5.10.0 from SLES 11 SP 4 on x86_64...

答:
When $something is an object of class ARRAY(0x913310).

```<code>$ perl -E'
   my $class = "".[];
   say $class;
   my $o = bless({}, $class);
   say ref($o);
'
ARRAY(0x115e360)
ARRAY(0x115e360)
</code>```

Body:
When $something is an object of class ARRAY(0x913310).

$ perl -E'
   my $class = "".[];
   say $class;
   my $o = bless({}, $class);
   say ref($o);
'
ARRAY(0x115e360)
ARRAY(0x115e360)


问:
How to configure node.js (express.js) app behind proxy?
My node.js app (using express.js) needs to send https requests through my company's proxy.

I tried the following commands to add the proxy but it doesn't work :

```<code>sudo npm config set proxy http://proxyIP:proxyPORT
sudo npm config set https-proxy https://proxyIP:proxyPORT
</code>```

I'm still having a timeout :

```<code>Error: connect ETIMEDOUT 194.3.8.11:443
at Object.exports._errnoException (util.js:907:11)
at exports._exceptionWithHostPort (util.js:930:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1081:14)
</code>```

Any help please ?
Many thanks

答:
Problem Solved.

I used the package global-tunnel
PS : this package depends on tunnel package that you must update to version >=0.0.5

Body:
My node.js app (using express.js) needs to send https requests through my company's proxy.

I tried the following commands to add the proxy but it doesn't work :

sudo npm config set proxy http://proxyIP:proxyPORT
sudo npm config set https-proxy https://proxyIP:proxyPORT

I'm still having a timeout :

Error: connect ETIMEDOUT 194.3.8.11:443
at Object.exports._errnoException (util.js:907:11)
at exports._exceptionWithHostPort (util.js:930:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1081:14)

Any help please ?
Many thanks


问:
Ecto query Postgres JSON Array for a value
I have the following schema, which is a JSONB field for a post table, which will save all tags used.

```<code>schema "posts" do
  ...
  field :tags, {:array, :string}
  ...
end
</code>```

And it has an array of "tags" as "strings". I'd like to search for a string value inside of this array. I tried:

```<code>def search_by_tag(query, tag) do
  from p in query,
    where: fragment("? @> ?", p.tags, ^tag)
end
</code>```

But without success, what I'm looking for is a way to search through the JSONB array and found a value if the values exists. Also it should keep the function for the query compatible with non JSONB queries to continue doing like:

```<code>Blog.Post |> Blog.Post.search_by_tag("tag1") |> Blog.User.active()
</code>```

答:
@> function expects the second operant to be array, so:

```<code>def search_by_tag(query, tag) do
  tags = [tag]
  from p in query,
    where: fragment("? @> ?", p.tags, ^tags)
end
</code>```

Also ecto syntax support such cases by it self:

```<code>def search_by_tag(query, tag) do
  from p in query,
    where: tag in p.tags
end
</code>```

Also for composable queries Blog.Post.search_by_tag("tag1") |> Blog.User.active(), you might consider to use "pipe-based syntax"

Body:
I have the following schema, which is a JSONB field for a post table, which will save all tags used.

schema "posts" do
  ...
  field :tags, {:array, :string}
  ...
end

And it has an array of "tags" as "strings". I'd like to search for a string value inside of this array. I tried:

def search_by_tag(query, tag) do
  from p in query,
    where: fragment("? @> ?", p.tags, ^tag)
end

But without success, what I'm looking for is a way to search through the JSONB array and found a value if the values exists. Also it should keep the function for the query compatible with non JSONB queries to continue doing like:

Blog.Post |> Blog.Post.search_by_tag("tag1") |> Blog.User.active()

Body:
@> function expects the second operant to be array, so:

def search_by_tag(query, tag) do
  tags = [tag]
  from p in query,
    where: fragment("? @> ?", p.tags, ^tags)
end

Also ecto syntax support such cases by it self:

def search_by_tag(query, tag) do
  from p in query,
    where: tag in p.tags
end

Also for composable queries Blog.Post.search_by_tag("tag1") |> Blog.User.active(), you might consider to use "pipe-based syntax"


问:
How to perform fortify scan on different pl/sql files
I am trying to do fortify scan on sql and oracle files from c# code. i have some folder which contains different oracle script files with extensions such as .pls, .pkb & .ddl etc.

Following are the commands i am executing to scan all files.

Command1: sourceanalyzer -b test –clean
Command2:
a) sourceanalyzer -b test -Dcom.fortify.sca.fileextensions.class=PLSQL C:\RapidWorkspace\TFS2\MFG-FDL-16_45418-20171114181758\PROD\RELEASE\**\*.*

b) sourceanalyzer -b test -Dcom.fortify.sca.fileextensions.pls=PLSQL C:\RapidWorkspace\TFS2\MFG-FDL-16_45418-20171114181758\PROD\RELEASE\**\*.*

Command3: sourceanalyzer -b test -scan -verbose -f Results.fpr

Command2 -> a)  here i am able to scan .pls files. Even though its present in the folder i am searching.
Command2 -> b) This command will only scan .pls files but not .pkb or other oracle files.

Please help me to find a command which can scan all different oracle extension files at once.

Thanks in Advance,
Asma

答:
The best thing to do would be to modify the fortify-sca.properties file to add in the new file extensions.

Default Location: C:\Program Files\HPE_Security\Fortify_SCA_and_Apps_17.10\Core\config\fortify-sca.properties

There are several places you need to modify:

1) Add in filename extentions to map to your PLSQL files, you can see existing ones around line 63:

```<code>com.fortify.sca.fileextensions.pks        = PLSQL
com.fortify.sca.fileextensions.pkh        = PLSQL
com.fortify.sca.fileextensions.pkb        = PLSQL
</code>```

Add in your file extensions below this line, for example:

```<code>com.fortify.sca.fileextensions.pls        = PLSQL
com.fortify.sca.fileextensions.ddl        = PLSQL
</code>```

2) Any file extensions you added, you need to add them to the com.fortify.sca.DefaultFileTypes list that is around line 26.  (This is the list that is used when doing the wild card search **/*)

3) If you are always going to be scanning PLSQL (and not TSQL) and you are on windows then you can change the default SQL type to PLSQL.

This is around line 127, name com.fortify.sca.SqlLanguage and change the TSQL to PLSQL.

If you will be switching between TSQL and PLSQL on SQL files that end in the .sql file extension then add one of these commands to your translate commands:

```<code>-Dcom.fortify.sca.fileextensions.sql=PLSQL
-Dcom.fortify.sca.fileextensions.sql=TSQL
</code>```

Examples (taken from sourceanalyzer -h):

```<code>sourceanalyzer -b mybuild -Dcom.fortify.sca.fileextensions.sql=PLSQL *.sql
sourceanalyzer -b mybuild -Dcom.fortify.sca.fileextensions.sql=TSQL *.sql
</code>```

Then you can run the following commands

```<code>sourceanalyzer -b test -clean

sourceanalyzer -b test C:\RapidWorkspace\TFS2\MFG-FDL-16_45418-20171114181758\PROD\RELEASE\**\*.*
</code>```

Then run sourceanalyzer -b test -show-files  This will show you the files that sourceanalyzer translated.  Ideally, your PLSQL files will be in this list.

Another command to check is sourceanalyzer -b test -show-build-warnings  This will show any issues sourceanalyzer had in translating the files.

Body:
The best thing to do would be to modify the fortify-sca.properties file to add in the new file extensions.

Default Location: C:\Program Files\HPE_Security\Fortify_SCA_and_Apps_17.10\Core\config\fortify-sca.properties

There are several places you need to modify:

1) Add in filename extentions to map to your PLSQL files, you can see existing ones around line 63:

com.fortify.sca.fileextensions.pks        = PLSQL
com.fortify.sca.fileextensions.pkh        = PLSQL
com.fortify.sca.fileextensions.pkb        = PLSQL

Add in your file extensions below this line, for example:

com.fortify.sca.fileextensions.pls        = PLSQL
com.fortify.sca.fileextensions.ddl        = PLSQL

2) Any file extensions you added, you need to add them to the com.fortify.sca.DefaultFileTypes list that is around line 26.  (This is the list that is used when doing the wild card search **/*)

3) If you are always going to be scanning PLSQL (and not TSQL) and you are on windows then you can change the default SQL type to PLSQL.

This is around line 127, name com.fortify.sca.SqlLanguage and change the TSQL to PLSQL.

If you will be switching between TSQL and PLSQL on SQL files that end in the .sql file extension then add one of these commands to your translate commands:

-Dcom.fortify.sca.fileextensions.sql=PLSQL
-Dcom.fortify.sca.fileextensions.sql=TSQL

Examples (taken from sourceanalyzer -h):

sourceanalyzer -b mybuild -Dcom.fortify.sca.fileextensions.sql=PLSQL *.sql
sourceanalyzer -b mybuild -Dcom.fortify.sca.fileextensions.sql=TSQL *.sql

Then you can run the following commands

sourceanalyzer -b test -clean

sourceanalyzer -b test C:\RapidWorkspace\TFS2\MFG-FDL-16_45418-20171114181758\PROD\RELEASE\**\*.*

Then run sourceanalyzer -b test -show-files  This will show you the files that sourceanalyzer translated.  Ideally, your PLSQL files will be in this list.

Another command to check is sourceanalyzer -b test -show-build-warnings  This will show any issues sourceanalyzer had in translating the files.


问:
Cosmos DB with multiple partition keys
We're looking at potentially using a single Cosmos DB collection to hold multiple document types in a multi-tenanted environment using a tenant ID as the partition key. The path to tenant id may change in each document type and I am therefore looking at various was of exposing the partition key to Cosmos DB to enable correct partitioning / querying.

I have noticed that the Paths property of DocumentCollection.PartitionKey is a collection and was therefore wondering whether it is possible to pass multiple paths during the creation of a document collection and what the behaviour of this might be. Ideally, I would like Cosmos to scan each of these paths and use the first value or aggregate of values as the partition key but cannot find any documentation suggesting that this is indeed the behaviour.

The MSDN documentation for this property is pretty useless and none of the associated documentation seems to answer the question. Does anyone know about or previously used multiple partition key paths in a collection?

To be clear, I'm looking for links to additional documentation about and/or direct experience of the Cosmos DB's behaviour when specifying multiple partition keys in the PartitionKey.Paths collection when creating a DocumentCollection.

This question has also been posted in the Azure Community Support forums.

Thanks, Ian

答:
The best way to do this is to assign a generic partition key like “pk”, then assign this value based on each of your object types. You can for example, manage this during serialization by having different properties for each class to be serialized to “pk”.

The reason partition key is an array in DocumentCollection.PartitionKey is to allow us to introduce compound partition keys, where the combination of multiple properties like (“firstName”, “lastName”) form the partition key. This is a little different from what you need.

Title: Cosmos DB with multiple partition keys


问:
Network- Create edges between one node and a list of nodes
I am brand new to networkx and can't figure out how read my specific formatting of data.

I have some data that looks like (node, list of nodes that it's connected to), like so:

```<code>('person 1', 'person 2, person 3, person 4')
</code>```

I want to add edges so that they look like this:

```<code>('person 1', 'person 2')
('person 1', 'person 3')
('person 1', 'person 4')
</code>```

Is there a way to specify the first node, and iterate over a list to get the rest of the nodes? In my csv file, one column is the primary node, and the second column is a list of nodes it's connected to, but I can't figure out for the life of me how to add them all at once.

答:
Although there's no bultin method, you can use Python slices and list comprehension to add them in one line.

```<code>import networkx as nx

G = nx.Graph()
nodes = list("ABCD")
G.add_nodes_from(nodes)
G.add_edges_from([(nodes[0],node) for node in nodes[1:]])
</code>```

nodes[1:] is a list with the first item skipped

Body:
I am brand new to networkx and can't figure out how read my specific formatting of data.

I have some data that looks like (node, list of nodes that it's connected to), like so:

('person 1', 'person 2, person 3, person 4')

I want to add edges so that they look like this:

('person 1', 'person 2')
('person 1', 'person 3')
('person 1', 'person 4')

Is there a way to specify the first node, and iterate over a list to get the rest of the nodes? In my csv file, one column is the primary node, and the second column is a list of nodes it's connected to, but I can't figure out for the life of me how to add them all at once.

Body:
Although there's no bultin method, you can use Python slices and list comprehension to add them in one line.

import networkx as nx

G = nx.Graph()
nodes = list("ABCD")
G.add_nodes_from(nodes)
G.add_edges_from([(nodes[0],node) for node in nodes[1:]])

nodes[1:] is a list with the first item skipped


问:
how to serialize class to database instead of file system c#
we can easily serialize class to flat file but if i want to serialize class to database then how could i do it and if it is possible then how can i deserialize data from db to class.
please give a sample code in c#.

thanks

答:
When serializing an object, it is often done to a stream.  You can serialize to a memory stream, then read the bytes back and put them into a database.

What serialization code do you have currently?  It would be better to tell you how to modify it than to just give you the full code.


问:
R ggplot2 : continuous x + colors
I'm trying to create a boxplot using ggplot2 with :

X as a continuous variable

Colors for different groups

Here is an example :

```<code>    x <- sample(c(1,2,5),300,replace = TRUE)
    y <- sapply(x,function(mu) rnorm(1,mean = mu))
    color <- sample(c("color 1","color 2"),300,replace = TRUE)
    data <- data.frame(x, y, color)
</code>```

I can either have colors and x as a factor :

```<code>   ggplot(data = data) + geom_boxplot(aes(x = factor(x),y = y,col = color))
</code>```

or x as a continuous variable and no colors :

```<code>  ggplot(data = data) + geom_boxplot(aes(x = x,y = y,group = x))
</code>```

But not both.
Does somebody know how to do this ?
Thanks

答:
I think you need one more column for group, which is the combination of color and x. For example, how about simply paste()ing them?

set.seed(1)
x <- sample(c(1,2,5),300,replace = TRUE)
y <- sapply(x,function(mu) rnorm(1,mean = mu))
color <- sample(c("color 1","color 2"),300,replace = TRUE)
data <- data.frame(x, y, color)

library(ggplot2)

ggplot(data = data) +
  geom_boxplot(aes(x = x, y = y, col = color, group = paste(color, x)))
```

Title: R ggplot2 : continuous x + colors

Body:
I'm trying to create a boxplot using ggplot2 with :

X as a continuous variable

Colors for different groups

Here is an example :

    x <- sample(c(1,2,5),300,replace = TRUE)
    y <- sapply(x,function(mu) rnorm(1,mean = mu))
    color <- sample(c("color 1","color 2"),300,replace = TRUE)
    data <- data.frame(x, y, color)

I can either have colors and x as a factor :

   ggplot(data = data) + geom_boxplot(aes(x = factor(x),y = y,col = color))

or x as a continuous variable and no colors :

  ggplot(data = data) + geom_boxplot(aes(x = x,y = y,group = x))

But not both.
Does somebody know how to do this ?
Thanks


问:
Getting unhandled IOException on globally defined variable - JAVA
How can one stop the IOException question being raised on something as such:

```<code>public class ExampleClass {

   String path = "path to directory";
   Path filePath = Paths.get(path);
   BasicFileAttributes Attr = Files.readAttributes(filePath, BasicFileAttributes.class);

   ...

}
</code>```

I receive a warning from IntelliJ stating Unhandled exception: java.io.IOException on the last line BasicFileAttributes inAttr = Files.readAttributes(filePathIn, BasicFileAttributes.class);

If I put these declarations within a method that throws an IOException, the warning does go away... But I am wanting this declared as a global variable... Am I missing something?

答:
You can circumvent that by initializing Attr inside the constructor (wrapped in a try-catch block).</p>

```<code>public ExampleClass(){
    try {
            Attr = Files.readAttributes(Paths.get(""), BasicFileAttributes.class);
    } catch (IOException e) {
            e.printStackTrace();
    }
}
</code>```

Body:
How can one stop the IOException question being raised on something as such:

public class ExampleClass {

   String path = "path to directory";
   Path filePath = Paths.get(path);
   BasicFileAttributes Attr = Files.readAttributes(filePath, BasicFileAttributes.class);

   ...

}

I receive a warning from IntelliJ stating Unhandled exception: java.io.IOException on the last line BasicFileAttributes inAttr = Files.readAttributes(filePathIn, BasicFileAttributes.class);

If I put these declarations within a method that throws an IOException, the warning does go away... But I am wanting this declared as a global variable... Am I missing something?

Body:
You can circumvent that by initializing Attr inside the constructor (wrapped in a try-catch block).

public ExampleClass(){
    try {
            Attr = Files.readAttributes(Paths.get(""), BasicFileAttributes.class);
    } catch (IOException e) {
            e.printStackTrace();
    }
}


问:
Getting a Ruby "KeyError: key not found: 102" error when trying to maximize browser window using Selenium Webdriver v3.70
I've recently upgraded my Selenium Webdriver version to 3.70 and when I try to maximize the browser window, I get this error:

KeyError: key not found: 102

Maximizing the window beforehand (on the previous version) seemed to be working absolutely fine, I'm not sure if it's just a coincidence though as it isn't a standard type of Selenium error.

Here's my code:

```<code>  profile = Selenium::WebDriver::Chrome::Profile.new
  $driver = Selenium::WebDriver.for :chrome, :profile => profile
  $driver.manage.window.maximize
</code>```

Anyone else having this problem? Also worth noting I'm using Ruby v2.3.1, so perhaps that needs updating? I just didn't want to make loads of drastic updates, but wanted the latest Selenium Webdriver version. I also don't know whether it's chromedriver related, but last updated this to the latest version on 19/09/17.

Thanks in advance,
Dan

答:
Upgrade chromedriver to 2.33.

On Mac you can upgrade it via brew brew upgrade chromedriver

Body:
I've recently upgraded my Selenium Webdriver version to 3.70 and when I try to maximize the browser window, I get this error:

KeyError: key not found: 102

Maximizing the window beforehand (on the previous version) seemed to be working absolutely fine, I'm not sure if it's just a coincidence though as it isn't a standard type of Selenium error.

Here's my code:

  profile = Selenium::WebDriver::Chrome::Profile.new
  $driver = Selenium::WebDriver.for :chrome, :profile => profile
  $driver.manage.window.maximize

Anyone else having this problem? Also worth noting I'm using Ruby v2.3.1, so perhaps that needs updating? I just didn't want to make loads of drastic updates, but wanted the latest Selenium Webdriver version. I also don't know whether it's chromedriver related, but last updated this to the latest version on 19/09/17.

Thanks in advance,
Dan


问:
How to execute delete raw query in codeigniter
I have sql query for delete multiple record from database </p>

```<code>$sql="delete from users where id IN(4,5,6..)";
</code>```

<p>How to run this query in codeigniter </p>

答:
Per the documents, you can use the query builder, or you can run a direct query on the database.

The query() function returns a database result object when “read” type
  queries are run, which you can use to show your results. When “write”
  type queries are run it simply returns TRUE or FALSE depending on
  success or failure. When retrieving data you will typically assign the
  query to your own variable, like this:

```<code>$query = $this->db->query('delete from users where id IN(4,5,6..)');
</code>```

Or you can use the query builder class which allows you to do the following:

```<code>$this->db->where_in('id', array(4,5,6));
$this->db->delete('users');
</code>```

Body:
I have sql query for delete multiple record from database

$sql="delete from users where id IN(4,5,6..)";

How to run this query in codeigniter

Body:
Per the documents, you can use the query builder, or you can run a direct query on the database.

The query() function returns a database result object when “read” type
  queries are run, which you can use to show your results. When “write”
  type queries are run it simply returns TRUE or FALSE depending on
  success or failure. When retrieving data you will typically assign the
  query to your own variable, like this:

$query = $this->db->query('delete from users where id IN(4,5,6..)');

Or you can use the query builder class which allows you to do the following:

$this->db->where_in('id', array(4,5,6));
$this->db->delete('users');


问:
angular-translate not working but not errors
I've just installed angular-translate, but the webpage after this doesn't work.

Here you can find my code:

```<code>app.js

angular
.module('frontEndApp', [
    'ngAnimate',
    'ngAria',
    'ngCookies',
    'ngMessages',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
    'ngStorage',
    'ngResource',
    'angular-translate'
])
.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl',
            controllerAs: 'main'
        })
</code>```

Index.html.

```<code>  <script src="bower_components/angular-translate/angular-translate.js"></script>
<!-- endbower -->
<!-- endbuild -->

<!-- build:js({.tmp,app}) scripts/scripts.js -->
<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
<script src="scripts/controllers/about.js"></script>
<script src="scripts/controllers/prueba/pruebaController.js"></script>
<script src="scripts/controllers/loginController.js"></script>
<script src="scripts/controllers/department/departmentController.js"></script>
<script src="config/appConstants.js"></script>
<script src="config/languajes.js"></script>
</code>```

languajes.js

```<code>'user strict';

var app = angular.module('frontEndApp', ['pascalprecht.translate']);

app.config(['$translateProvider', function ($translateProvider) {

    $translateProvider.translations('en', {
        code: 'Code',
        department: 'Deparment',
        description: 'Description',
        boss: 'Boss',
        project: 'Project'
    });

    $translateProvider.translations('es', {
        code: 'Código',
        department: 'Deparmento',
        description: 'Descripción',
        boss: 'Jefe',
        project: 'Proyecto'
    });

    $translateProvider.preferredLanguage('en');
    // $translateProvider.useSanitizeValueStrategy('escapeParamenters');
}]);

    app.config(['$locationProvider', function ($locationProvider) {
      $locationProvider.html5Mode(true);
    }]);

    app.controller('Ctrl', function ($scope, $translate) {
        $scope.changeLanguage = function (key) {
        $translate.use(key);
      };
    });
</code>```

bower.json

```<code> {
"name": "front-end",
"version": "0.0.0",
"dependencies": {
"angular": "^1.6.6",
"bootstrap-sass-official": "^3.2.0",
"angular-animate": "^1.6.6",
"angular-aria": "^1.6.6",
"angular-cookies": "^1.6.6",
"angular-messages": "^1.6.6",
"angular-resource": "^1.6.6",
"angular-route": "^1.6.6",
"angular-sanitize": "^1.6.6",
"angular-touch": "^1.6.6",
"bootstrap-sass": "bootstrap-sass-official#^3.3.7",
"ngstorage": "^0.3.11",
"angular-translate": "^2.16.0"
},
"devDependencies": {
"angular-mocks": "^1.6.6",
"angularLocalStorage": "ngStorage#^0.3.2"
},
"appPath": "app",
"moduleName": "frontEndApp",
"overrides": {
"bootstrap": {
  "main": [
    "less/bootstrap.less",
    "dist/css/bootstrap.css",
    "dist/js/bootstrap.js"
    ]
   }
 }
}
</code>```

The problem is the system works fine, but when I insert the script

all is gone, the webpage is blank only the header appears.

I have tried several solutions but I have no idea.

https://docs.angularjs.org/error/$injector/nomod?p0=pascalprecht.translate

https://angular-translate.github.io/docs/#/guide

答:
This is the solution.
use strict;

```<code>/**
 * @ngdoc overview
 * @name frontEndApp
 * @description
 * # frontEndApp
 *
 * Main module of the application.
 */

angular
.module('frontEndApp', [
    'ngAnimate',
    'ngAria',
    'ngCookies',
    'ngMessages',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
    'ngStorage',
    'ngResource',
    'pascalprecht.translate'
]).config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl',
            controllerAs: 'main'
        })
        .when('/about', {
            templateUrl: 'views/about.html',
            controller: 'AboutCtrl',
            controllerAs: 'about'
        })
        .when('/prueba', {
            templateUrl: 'views/prueba/prueba.html',
            controller: 'pruebaController',
            controllerAs: 'prueba'
        })
        .when('/login', {
            templateUrl: 'views/login/login.html',
            controller: 'loginController',
            controllerAs: 'login'
        })
        .when('/department', {
            templateUrl: 'views/department/department.html',
            controller: 'departmentController',
            controllerAs: 'departmentController',
            data: {
                title: 'department',
                section: 'department'
            }
        })
        .otherwise({
            redirectTo: '/'
        });
}).config(['$translateProvider', function ($translateProvider) {

    $translateProvider.translations('en', {
        code: 'Code',
        department: 'Deparment',
        description: 'Description',
        boss: 'Boss',
        project: 'Project'
    });

    $translateProvider.translations('es', {
        code: 'Código',
        department: 'Deparmento',
        description: 'Descripción',
        boss: 'Jefe',
        project: 'Proyecto'
    });

    $translateProvider.preferredLanguage('en');
    // $translateProvider.useSanitizeValueStrategy('escapeParamenters');
}]);
</code>```

Body:
I've just installed angular-translate, but the webpage after this doesn't work.

Here you can find my code:

app.js

angular
.module('frontEndApp', [
    'ngAnimate',
    'ngAria',
    'ngCookies',
    'ngMessages',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
    'ngStorage',
    'ngResource',
    'angular-translate'
])
.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl',
            controllerAs: 'main'
        })

Index.html.

languajes.js

'user strict';

var app = angular.module('frontEndApp', ['pascalprecht.translate']);

app.config(['$translateProvider', function ($translateProvider) {

    $translateProvider.translations('en', {
        code: 'Code',
        department: 'Deparment',
        description: 'Description',
        boss: 'Boss',
        project: 'Project'
    });

    $translateProvider.translations('es', {
        code: 'Código',
        department: 'Deparmento',
        description: 'Descripción',
        boss: 'Jefe',
        project: 'Proyecto'
    });

    $translateProvider.preferredLanguage('en');
    // $translateProvider.useSanitizeValueStrategy('escapeParamenters');
}]);

    app.config(['$locationProvider', function ($locationProvider) {
      $locationProvider.html5Mode(true);
    }]);

    app.controller('Ctrl', function ($scope, $translate) {
        $scope.changeLanguage = function (key) {
        $translate.use(key);
      };
    });

bower.json

 {
"name": "front-end",
"version": "0.0.0",
"dependencies": {
"angular": "^1.6.6",
"bootstrap-sass-official": "^3.2.0",
"angular-animate": "^1.6.6",
"angular-aria": "^1.6.6",
"angular-cookies": "^1.6.6",
"angular-messages": "^1.6.6",
"angular-resource": "^1.6.6",
"angular-route": "^1.6.6",
"angular-sanitize": "^1.6.6",
"angular-touch": "^1.6.6",
"bootstrap-sass": "bootstrap-sass-official#^3.3.7",
"ngstorage": "^0.3.11",
"angular-translate": "^2.16.0"
},
"devDependencies": {
"angular-mocks": "^1.6.6",
"angularLocalStorage": "ngStorage#^0.3.2"
},
"appPath": "app",
"moduleName": "frontEndApp",
"overrides": {
"bootstrap": {
  "main": [
    "less/bootstrap.less",
    "dist/css/bootstrap.css",
    "dist/js/bootstrap.js"
    ]
   }
 }
}

The problem is the system works fine, but when I insert the script

all is gone, the webpage is blank only the header appears.

I have tried several solutions but I have no idea.

https://docs.angularjs.org/error/$injector/nomod?p0=pascalprecht.translate

https://angular-translate.github.io/docs/#/guide

Body:
This is the solution.
use strict;

/**
 * @ngdoc overview
 * @name frontEndApp
 * @description
 * # frontEndApp
 *
 * Main module of the application.
 */

angular
.module('frontEndApp', [
    'ngAnimate',
    'ngAria',
    'ngCookies',
    'ngMessages',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
    'ngStorage',
    'ngResource',
    'pascalprecht.translate'
]).config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl',
            controllerAs: 'main'
        })
        .when('/about', {
            templateUrl: 'views/about.html',
            controller: 'AboutCtrl',
            controllerAs: 'about'
        })
        .when('/prueba', {
            templateUrl: 'views/prueba/prueba.html',
            controller: 'pruebaController',
            controllerAs: 'prueba'
        })
        .when('/login', {
            templateUrl: 'views/login/login.html',
            controller: 'loginController',
            controllerAs: 'login'
        })
        .when('/department', {
            templateUrl: 'views/department/department.html',
            controller: 'departmentController',
            controllerAs: 'departmentController',
            data: {
                title: 'department',
                section: 'department'
            }
        })
        .otherwise({
            redirectTo: '/'
        });
}).config(['$translateProvider', function ($translateProvider) {

    $translateProvider.translations('en', {
        code: 'Code',
        department: 'Deparment',
        description: 'Description',
        boss: 'Boss',
        project: 'Project'
    });

    $translateProvider.translations('es', {
        code: 'Código',
        department: 'Deparmento',
        description: 'Descripción',
        boss: 'Jefe',
        project: 'Proyecto'
    });

    $translateProvider.preferredLanguage('en');
    // $translateProvider.useSanitizeValueStrategy('escapeParamenters');
}]);


问:
Find corresponding row or get next row in SQL
I have a table:

```<code>id value1 value2
1  1      6
2  8      10
3  14     20
</code>```

Then I have a number, let's say x=7.

My query should find out id for which x falls between value1 and value2. If x does not fall in any range, use next id. In my case x=7 I'd get id=2.

My guess it could be done somehow using windowing functions in PostgreSQL, but maybe there is a simpler solution?

答:
I am assuming you actually want a list of possible results (if x matches more than one line, you want them all; else just the last one). In light of this, I thought of the following solution:

```<code>SELECT    CASE
        WHEN
            (
            SELECT    COUNT(*)
            FROM      table
            WHERE       x > value1
                    AND x < value2
            ) > 0
        THEN
            (
            SELECT    id
            FROM      table
            WHERE       x > value1
                    AND x < value2
            )
        ELSE
            (
            SELECT    MAX(id)
            FROM      table
            )
        END AS my_ids
</code>```

Body:
I have a table:

id value1 value2
1  1      6
2  8      10
3  14     20

Then I have a number, let's say x=7.

My query should find out id for which x falls between value1 and value2. If x does not fall in any range, use next id. In my case x=7 I'd get id=2.

My guess it could be done somehow using windowing functions in PostgreSQL, but maybe there is a simpler solution?

Body:
I am assuming you actually want a list of possible results (if x matches more than one line, you want them all; else just the last one). In light of this, I thought of the following solution:

SELECT    CASE
        WHEN
            (
            SELECT    COUNT(*)
            FROM      table
            WHERE       x > value1
                    AND x < value2
            ) > 0
        THEN
            (
            SELECT    id
            FROM      table
            WHERE       x > value1
                    AND x < value2
            )
        ELSE
            (
            SELECT    MAX(id)
            FROM      table
            )
        END AS my_ids


问:
Why do (disabled) buttons with color:inherit not follow disabled style?
As seen in this fiddle, a property of color: inherit on button prevents a disabled button appearing as disabled.

I thought specificity would mean that disabled buttons still appeared disabled. How does this override the user-agent styling and how would it be possible to make them appear enabled again? Manually assigning a color to button:disabled {color:GreyText} does not work.

https://jsfiddle.net/zzhLhkjx/

Compare this to https://jsfiddle.net/g46kg6ev/ which shows a disabled button with greyed out text. Just specifying color to inherit stops that behaviour.

答:
As I understand it, any author defined styles will over-qualify any user-agent style regardless of specificity - since author styles always carry more weight than user-agent styles.

JSFiddle demonstration to rule out any specificity doubts

More on user-agent stylesheet weight from an answer (What is user agent stylesheet) by @JukkaK.Korpela

"User agent style sheets are overridden by anything that you set in
  your own style sheet. They are just the rock bottom: in the absence of
  any style sheets provided by the page or by the user, the browser
  still has to render the content somehow, and the user agent style
  sheet just describes this."


问:
aurelia: variable is not getting printed in custom component
weather.ts file

```<code>import {bindable} from 'aurelia-framework';

export class Weather {
  cityName: string = 'Hilsinki';
  constructor() {
    this.cityName = 'Hilsinki';
  }
}
</code>```

weather.html file

```<code><template>
        City XName: ${cityName}
</template>
</code>```

When I print the component in any file, the cityName variable is not getting printed. I am trying this for last three days 12 hours a day.

Any kind of help is appreciated

UPDATE:
Utilizing the component in welcome.html

```<code><template>
    <require from = "./components/weather.html"></require>
    <weather view-model="Weather"></weather>
</template>
</code>```

also imported the component in welcome.ts as

```<code>import { Weather } from './components/weather';
</code>```

答:
You didn't require the viewmodel, only the view.

```<code><require from = "./components/weather.html"></require>
</code>```

If you want both the view and the viewmodel, require it like this instead:

```<code><require from = "./components/weather"></require>
</code>```

Body:
weather.ts file

import {bindable} from 'aurelia-framework';

export class Weather {
  cityName: string = 'Hilsinki';
  constructor() {
    this.cityName = 'Hilsinki';
  }
}

weather.html file

<template>
        City XName: ${cityName}
</template>

When I print the component in any file, the cityName variable is not getting printed. I am trying this for last three days 12 hours a day.

Any kind of help is appreciated

UPDATE:
Utilizing the component in welcome.html

<template>
    <require from = "./components/weather.html"></require>
    <weather view-model="Weather"></weather>
</template>

also imported the component in welcome.ts as

import { Weather } from './components/weather';

Body:
You didn't require the viewmodel, only the view.

<require from = "./components/weather.html"></require>

If you want both the view and the viewmodel, require it like this instead:

<require from = "./components/weather"></require>


问:
Why is not the compiler giving error?
I am using the following sample program in C++

```<code>#include<iostream>
#include<ctime>
#include<cstdlib>

using namespace std;

namespace mine{
    template<class T>
    inline void swap(T &a, T &b){
        char c= a; //This should not have compiled
        a=b;
        b=c;
    }

}
int main(){
    int a,b;
    cout<< "Enter two values: ";
    cin>>a>>b;
    mine::swap(a,b); //type variable T is instantiated as in
    cout << a <<' '<<b << endl;
}
</code>```

I am expecting the compiler to throw an error in the swap function, because c is declared as a char, but assigned a variable of generic type variable T. Not only that, when invoking swap, T is instantiated as int. However, not only is g++ not giving any error, the program works perfectly. Why is this the case?

答:
C++ gives you the ability to shoot yourself in the foot.

The fact remains that any integral type is convertible to a char with implementation defined behaviour.

The compiler is assuming you know what you are doing, that's all.

auto c = a; would be the best replacement these days. Prior to C++11 you could have written T C = a; (you still can of course.) Although since C++11 you ought to use std::move when swapping, see how std::swap is implemented on your platform. (Reference How does the standard library implement std::swap?)

gcc will warn you of this if you specify -Wconversion on the command line.

Title: Why is not the compiler giving error?

Body:
I am using the following sample program in C++

#include<iostream>
#include<ctime>
#include<cstdlib>

using namespace std;

namespace mine{
    template<class T>
    inline void swap(T &a, T &b){
        char c= a; //This should not have compiled
        a=b;
        b=c;
    }

}
int main(){
    int a,b;
    cout<< "Enter two values: ";
    cin>>a>>b;
    mine::swap(a,b); //type variable T is instantiated as in
    cout << a <<' '<<b << endl;
}

I am expecting the compiler to throw an error in the swap function, because c is declared as a char, but assigned a variable of generic type variable T. Not only that, when invoking swap, T is instantiated as int. However, not only is g++ not giving any error, the program works perfectly. Why is this the case?


问:
Cant get CSS property from child?
I have this HTML code here :

```<code> <div id="ctr" class="faden-slider-container">
    <div class="conteneur-image" ></div>
    <div class="conteneur-image" ></div>
    <div class="conteneur-image" ></div>
</div>
</code>```

And I am trying to get the CSS property of the second div which class' name is conteneur-image but I get nothing :

```<code>app.controller("slideCtrl",function ($scope) {
    alert("hello")

    var tab = new Array();
    var elements = new Array();

    for(var i = 0; i<3 ; i++){
        elements[i] = document.getElementById("ctr").children[i]
    }

    var style = window.getComputedStyle(elements[1])
    var message = style.getPropertyCSSValue("background").cssText()

    alert("CSS Value is  : "+message)
})
</code>```

答:
Using jquery,you can get your 2nd HTML element this way:

```<code>var element = $("#ctr").children().eq(1);
</code>```

Then if you want to make some transformation, like applying style:

```<code>element.css("background-color", "blue")
</code>```

Here is a snippet:

var element = $("#ctr").children().eq(1);

    element.css("background-color", "blue")```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ctr" class="faden-slider-container">
    <div class="conteneur-image" >one</div>
    <div class="conteneur-image" >second</div>
    <div class="conteneur-image" >third</div>
</div></code>```

Title: Cant get CSS property from child?

Body:
I have this HTML code here :

And I am trying to get the CSS property of the second div which class' name is conteneur-image but I get nothing :

app.controller("slideCtrl",function ($scope) {
    alert("hello")

    var tab = new Array();
    var elements = new Array();

    for(var i = 0; i<3 ; i++){
        elements[i] = document.getElementById("ctr").children[i]
    }

    var style = window.getComputedStyle(elements[1])
    var message = style.getPropertyCSSValue("background").cssText()

    alert("CSS Value is  : "+message)
})

Body:
Using jquery,you can get your 2nd HTML element this way:

var element = $("#ctr").children().eq(1);

Then if you want to make some transformation, like applying style:

element.css("background-color", "blue")

Here is a snippet:

var element = $("#ctr").children().eq(1);

    element.css("background-color", "blue")

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ctr" class="faden-slider-container">
    <div class="conteneur-image" >one</div>
    <div class="conteneur-image" >second</div>
    <div class="conteneur-image" >third</div>
</div>


问:
PagerAdapter() cannot be applied to android.app FragmentManager
I tried to create a ViewPager in Android Studio.
I get the error:

```<code>PagerAdapter() cannot be applied to android.app FragmentManager
</code>```

at the line super(fm);

Here is my code for the adapter. Do I need to change anything?

```<code>package com.example.admin.usthweather;

import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.view.View;

/**
 * Created by Admin on 11/15/2017.
 */

public class HomeFragmentAdapter extends PagerAdapter {
  private final int PAGE_COUNT = 3;
  private String titles[] = new String[] {"Hanoi","Paris", "Saigon"};

  public HomeFragmentAdapter(FragmentManager fm){
    super(fm);
  }

  @Override
  public int getCount() {
    return PAGE_COUNT;
  }

  // Override
  public Fragment getItem(int page) {
// returns an instance of Fragment corresponding to the specified page
    Fragment frag=null;
    switch (page){
      case 0:
        frag=new Hanoi();
        break;
      case 1:
        frag=new Paris();
        break;
      case 2:
        frag=new Saigon();
        break;
    }
    return frag;
  }

  @Override
  public boolean isViewFromObject(View view, Object object) {
    return false;
  }
}
</code>```

答:
fm in super(fm); is wrong. Therefore none of this is necessary:

```<code>public HomeFragmentAdapter(FragmentManager fm){
    super(fm);
}
</code>```

However, I suspect that you did not want to subclass PagerAdapter, but either   or FragmentStatePagerAdapter. As the docs say:

Base class providing the adapter to populate pages inside of a ViewPager. You will most likely want to use a more specific implementation of this, such as FragmentPagerAdapter or FragmentStatePagerAdapter.

Instead of providing a View recycling mechanism directly ViewPager uses callbacks to indicate the steps taken during an update.

Body:
I tried to create a ViewPager in Android Studio.
I get the error:

PagerAdapter() cannot be applied to android.app FragmentManager

at the line super(fm);

Here is my code for the adapter. Do I need to change anything?

package com.example.admin.usthweather;

import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.view.View;

/**
 * Created by Admin on 11/15/2017.
 */

public class HomeFragmentAdapter extends PagerAdapter {
  private final int PAGE_COUNT = 3;
  private String titles[] = new String[] {"Hanoi","Paris", "Saigon"};

  public HomeFragmentAdapter(FragmentManager fm){
    super(fm);
  }

  @Override
  public int getCount() {
    return PAGE_COUNT;
  }

  // Override
  public Fragment getItem(int page) {
// returns an instance of Fragment corresponding to the specified page
    Fragment frag=null;
    switch (page){
      case 0:
        frag=new Hanoi();
        break;
      case 1:
        frag=new Paris();
        break;
      case 2:
        frag=new Saigon();
        break;
    }
    return frag;
  }

  @Override
  public boolean isViewFromObject(View view, Object object) {
    return false;
  }
}

Body:
fm in super(fm); is wrong. Therefore none of this is necessary:

public HomeFragmentAdapter(FragmentManager fm){
    super(fm);
}

However, I suspect that you did not want to subclass PagerAdapter, but either   or FragmentStatePagerAdapter. As the docs say:

Base class providing the adapter to populate pages inside of a ViewPager. You will most likely want to use a more specific implementation of this, such as FragmentPagerAdapter or FragmentStatePagerAdapter.

Instead of providing a View recycling mechanism directly ViewPager uses callbacks to indicate the steps taken during an update.


问:
Microsoft.Interop.Security.AzRoles in Server 2008/Windows 7
I am trying to follow these instructions on how to use AD LDS for both Membership and Roles for an application.  I've almost got it all set, but the ending code calls for the "IAzApplication2" object from Microsoft.Interop.Security.AzRoles.

I can see how to install it in Server 2003, but I cannot find out how to install it and/or implement it in Server 2008. In fact, my server doesn't seem to be able to reference the Microsoft.Interop Namespace at all.

Can someone point me in the right direction on how to get to the IAzApplication2(+) object?  Am I missing a file?

答: I think the answer you're looking for is here: Where is microsoft.interop.security.azroles on Server 2008 R2?  (but to save you clicking, it's in the GAC in 32-bit and 64-bit forms).</p>


问:
HTTP error 403 if POST is not used
I am trying to send protobuf data via REST from c# winform application. When I use the HTTP request with POST method( as shown in code below) it works perfect and returns "OK" status.

```<code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://xxxxx.execute-api.eu-west-1.amazonaws.com/test/input");
request.Headers["Authorization"] = "xxxyyyzzz"
request.Method = "POST";
request.ContentType = "application/octet-stream";
byte[] bytes = System.IO.File.ReadAllBytes("C:\\MyProtobuf.proto");
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
                MessageBox.Show(myHttpWebResponse .StatusCode.ToString());
myHttpWebResponse .Close();
</code>```

But if I simply want to check if website is alive or not using below code it gives me 403. Forbidden error.

```<code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://xxxxx.execute-api.eu-west-1.amazonaws.com/test/input");
request.Headers["Authorization"] = "xxxyyyzzz";
HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
MessageBox.Show(myHttpWebResponse .StatusCode.ToString());
myHttpWebResponse .Close();
</code>```

what could be the possible reason for this error ?

答: your services serves POST method verb so you must call this service with post method, otherwise you should change your service methods to support get method.</p>

Title: HTTP error 403 if POST is not used

Body:
I am trying to send protobuf data via REST from c# winform application. When I use the HTTP request with POST method( as shown in code below) it works perfect and returns "OK" status.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://xxxxx.execute-api.eu-west-1.amazonaws.com/test/input");
request.Headers["Authorization"] = "xxxyyyzzz"
request.Method = "POST";
request.ContentType = "application/octet-stream";
byte[] bytes = System.IO.File.ReadAllBytes("C:\\MyProtobuf.proto");
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
                MessageBox.Show(myHttpWebResponse .StatusCode.ToString());
myHttpWebResponse .Close();

But if I simply want to check if website is alive or not using below code it gives me 403. Forbidden error.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://xxxxx.execute-api.eu-west-1.amazonaws.com/test/input");
request.Headers["Authorization"] = "xxxyyyzzz";
HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
MessageBox.Show(myHttpWebResponse .StatusCode.ToString());
myHttpWebResponse .Close();

what could be the possible reason for this error ?


问:
How can I check if an array contains a specific value in php?
I have a PHP variable of type Array and I would like find out if it contains a specific value and let the user know that it is there. This is my array:

```<code>Array ( [0] => kitchen [1] => bedroom [2] => living_room [3] => dining_room)
</code>```

and I would like do something like:

```<code>if(Array contains 'kitchen') {echo 'this array contains kitchen';}
</code>```

What is the best way to do the above?

答:
Following is how you can do this:

```<code><?php
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('kitchen', $rooms)){
    echo 'this array contains kitchen';
}
</code>```

Make sure that you search for kitchen and not Kitchen. This function is case sensitive. So, the below function simply won't work:

```<code>$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('KITCHEN', $rooms)){
    echo 'this array contains kitchen';
}
</code>```

If you rather want a quick way to make this search case insensitive, have a look at the proposed solution in this reply: https://stackoverflow.com/a/30555568/8661779

Source: http://dwellupper.io/post/50/understanding-php-in-array-function-with-examples

Body:
I have a PHP variable of type Array and I would like find out if it contains a specific value and let the user know that it is there. This is my array:

Array ( [0] => kitchen [1] => bedroom [2] => living_room [3] => dining_room)

and I would like do something like:

if(Array contains 'kitchen') {echo 'this array contains kitchen';}

What is the best way to do the above?

Body:
Following is how you can do this:

<?php
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('kitchen', $rooms)){
    echo 'this array contains kitchen';
}

Make sure that you search for kitchen and not Kitchen. This function is case sensitive. So, the below function simply won't work:

$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('KITCHEN', $rooms)){
    echo 'this array contains kitchen';
}

If you rather want a quick way to make this search case insensitive, have a look at the proposed solution in this reply: https://stackoverflow.com/a/30555568/8661779

Source: http://dwellupper.io/post/50/understanding-php-in-array-function-with-examples


问:
How to get tab active on page load -laravel
How can i get my first selected when i land on the page? When i land on the page, i have to select a tab before but is there a way i can have the first tab already selected when i land on the page?

when i load the page, i have my tabs showing but none of them are active until i click on them. Is there a way i can have the first tab active as the page loads.

HTML

```<code><div class="row">
        <div class="col-md-9">

          <div  class="nav-tabs-custom">

            <ul class="nav nav-tabs">
            @foreach($hotels as $hotel)

               <li ><a href="#tab_{{ $hotel->id }}" data-toggle="tab" >{!!$hotel->name!!}</a></li>
               @endforeach

            </ul>
            <div class="tab-content">
            @foreach($hotels as $hotel)

              <div class="tab-pane active" id="tab_{{ $hotel->id }}">

              @foreach($hotel->waiters as $waiter)

            <label class="mylabel" >  {{$waiter->name}} </label>

             </div>
            @endforeach
              </div>

            </div>

          </div>

        </div>
</code>```

答:
This is actually not realted to php or laravel, this question is more related to css-bootstrap and jquery.You can add below js to your code and remove active active class from hardcoded blade-html, I think this is a more proper solution :

```<code>$(document).ready(function(){
  $('.tab-pane').each(function(tab,index){
    if(index==0){
     tab.addClass('active');
    }
  });
 });
</code>```

Body:
How can i get my first selected when i land on the page? When i land on the page, i have to select a tab before but is there a way i can have the first tab already selected when i land on the page?

when i load the page, i have my tabs showing but none of them are active until i click on them. Is there a way i can have the first tab active as the page loads.

HTML

            @foreach($hotels as $hotel)

id }}" data-toggle="tab" >{!!$hotel->name!!}

               @endforeach

            @foreach($hotels as $hotel)

id }}">

              @foreach($hotel->waiters as $waiter)

              {{$waiter->name}}

            @endforeach

Body:
This is actually not realted to php or laravel, this question is more related to css-bootstrap and jquery.You can add below js to your code and remove active active class from hardcoded blade-html, I think this is a more proper solution :

$(document).ready(function(){
  $('.tab-pane').each(function(tab,index){
    if(index==0){
     tab.addClass('active');
    }
  });
 });


问:
Array as URL get parameter: URL-length restricton
As mentioned in this thread an URL has a length restriction. But what do I do when I have to submit an array of values via get parameters and can't ensure that the url doesn't exceed max length?

I know I could POST the request, but I want users to be able to bookmark/ cache the link.

答:
The only possible solution would be to reduce the length of the URL as much as you can.

And if you can't reduce the amount of information that you need to transmit, try reducing the length of your GET parameters


问:
Delphi multiline regex
I have some non-regression test code in Delphi that calls an external diff tool. Then my code loads the diff results and should remove acceptable differences, such as dates in the compared results. I'm trying to do this with a multiline TRegEx.Replace , but no match is found ...

https://regex101.com/r/QBZuws/2 shows the pattern I came up with and a sample test diff file. I need to delete the matching "pararaphs" of 3 lines

Here is my code :

```<code>function FilterDiff(AText:string):string;
var
  LStr:string;
  Regex: TRegEx;
begin
  // AText:=StringReplace(AText,#13+#10,'\n',[rfReplaceAll]); // doesn't help ...
  LStr := '\d\d.\d\d.20\d\d \d\d:\d\d:\d\d'; // regex for date and time
  LStr := '@@.*@@\n-'+LStr+'\n\+'+LStr; // regex for paragraphs to remove
  Regex := TRegEx.Create(LStr, [roMultiLine]);
  Result := Regex.Replace(AText,'');
end;

procedure TReportTest.NonRegression;
var
  LDiff : TStringList;
  // others removed for clarity
begin
  // removed section code that call an external tool and produces diff.txt file
  LDiff := TStringList.Create;
  LDiff.LoadFromFile('diff.txt');
  Status(FilterDiff(LDiff.Text)); // show the diffs in DUnit GUI for now
  LDiff.Free;
end;
</code>```

Besides, while tracing TRegEx.Replace down to

```<code>System.RegularExpressionsAPI.pcre_exec($4D72A50,nil,'--- '#$D#$A'+++ '#$D#$A'@@ -86 +86 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A'@@ -400 +400 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A,132,0,1024,$7D56800,300)
System.RegularExpressionsCore.TPerlRegEx.Match
System.RegularExpressionsCore.TPerlRegEx.ReplaceAll
System.RegularExpressions.TRegEx.Replace(???,???)
TestReportAuto.FilterDiff('--- '#$D#$A'+++ '#$D#$A'@@ -86 +86 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A'@@ -400 +400 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A)
</code>```

I was surprised to see quotes before and after each newline #$D#$A in the debugger, but they don't look "real" ... or are they ?

答:
Well, I just noticed the \n in regex matches only LF, not CR+LF, so I added

```<code>AText:=StringReplace(AText,#13+#10,#10,[rfReplaceAll]); // \n matches only LF !
</code>```

at the beginning of my function and it's much better now...
Sometimes writing down a problem helps ...

Title: Delphi multiline regex

Body:
I have some non-regression test code in Delphi that calls an external diff tool. Then my code loads the diff results and should remove acceptable differences, such as dates in the compared results. I'm trying to do this with a multiline TRegEx.Replace , but no match is found ...

https://regex101.com/r/QBZuws/2 shows the pattern I came up with and a sample test diff file. I need to delete the matching "pararaphs" of 3 lines

Here is my code :

function FilterDiff(AText:string):string;
var
  LStr:string;
  Regex: TRegEx;
begin
  // AText:=StringReplace(AText,#13+#10,'\n',[rfReplaceAll]); // doesn't help ...
  LStr := '\d\d.\d\d.20\d\d \d\d:\d\d:\d\d'; // regex for date and time
  LStr := '@@.*@@\n-'+LStr+'\n\+'+LStr; // regex for paragraphs to remove
  Regex := TRegEx.Create(LStr, [roMultiLine]);
  Result := Regex.Replace(AText,'');
end;

procedure TReportTest.NonRegression;
var
  LDiff : TStringList;
  // others removed for clarity
begin
  // removed section code that call an external tool and produces diff.txt file
  LDiff := TStringList.Create;
  LDiff.LoadFromFile('diff.txt');
  Status(FilterDiff(LDiff.Text)); // show the diffs in DUnit GUI for now
  LDiff.Free;
end;

Besides, while tracing TRegEx.Replace down to

System.RegularExpressionsAPI.pcre_exec($4D72A50,nil,'--- '#$D#$A'+++ '#$D#$A'@@ -86 +86 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A'@@ -400 +400 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A,132,0,1024,$7D56800,300)
System.RegularExpressionsCore.TPerlRegEx.Match
System.RegularExpressionsCore.TPerlRegEx.ReplaceAll
System.RegularExpressions.TRegEx.Replace(???,???)
TestReportAuto.FilterDiff('--- '#$D#$A'+++ '#$D#$A'@@ -86 +86 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A'@@ -400 +400 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A)

I was surprised to see quotes before and after each newline #$D#$A in the debugger, but they don't look "real" ... or are they ?

Body:
Well, I just noticed the \n in regex matches only LF, not CR+LF, so I added

AText:=StringReplace(AText,#13+#10,#10,[rfReplaceAll]); // \n matches only LF !

at the beginning of my function and it's much better now...
Sometimes writing down a problem helps ...


问:
TCL to JSON: use of json::write aligned method
I am facing problem to aligned the json data into a single line while using json::write.

for example, tcl dict is

```<code>set arr {a b c d}
</code>```

conversion into json

```<code>foreach {key value} $arr {
    puts [json::write string {*}$value]
}
</code>```

output:

```<code>{
   "a" : "b",
   "c" : "d"
}
</code>```

where to use [json:write aligned] to convert above output into {"a" : "b", "c" : "d"}.

答:
You want to alter the indented flag:

```<code>% package req json::write
1.0.3
% set arr {a b c d}
a b c d

% json::write indented
1
% json::write  object {*}$arr
{
    "a" : b,
    "c" : d
}

% json::write indented false
false
% json::write  object {*}$arr
{"a":b,"c":d}
</code>```

Hmm, I see the values aren't quoted...

```<code>% for {set i 1} {$i < [llength $arr]} {incr i 2} {lset arr $i [json::write string [lindex $arr $i]]}
% set arr
a {"b"} c {"d"}
% json::write object {*}$arr
{"a":"b","c":"d"}
</code>```

or, thanks to Johannes, skip the for loop

```<code>json::write object {*}[dict map {key val} $arr {json::write string $val}]
</code>```

Body:
I am facing problem to aligned the json data into a single line while using json::write.

for example, tcl dict is

set arr {a b c d}

conversion into json

foreach {key value} $arr {
    puts [json::write string {*}$value]
}

output:

{
   "a" : "b",
   "c" : "d"
}

where to use [json:write aligned] to convert above output into {"a" : "b", "c" : "d"}.

Body:
You want to alter the indented flag:

% package req json::write
1.0.3
% set arr {a b c d}
a b c d

% json::write indented
1
% json::write  object {*}$arr
{
    "a" : b,
    "c" : d
}

% json::write indented false
false
% json::write  object {*}$arr
{"a":b,"c":d}

Hmm, I see the values aren't quoted...

% for {set i 1} {$i < [llength $arr]} {incr i 2} {lset arr $i [json::write string [lindex $arr $i]]}
% set arr
a {"b"} c {"d"}
% json::write object {*}$arr
{"a":"b","c":"d"}

or, thanks to Johannes, skip the for loop

json::write object {*}[dict map {key val} $arr {json::write string $val}]


问:
Easiest way to construct @RabbitListener at runtime
What would be the easiest way to construct this at runtime?

```<code>@RabbitListener(bindings = @QueueBinding(
    value = @Queue(value = "providedAtRuntime", durable = "true"),
    exchange = @Exchange(value = "providedAtRuntime", ignoreDeclarationExceptions = "true"),
    key = "providedAtRuntime"), containerFactory = "cFac")
public class RabbitProcessor {
    @RabbitHandler
    public void receive (String smth){
        System.out.println(smth);
    }
}
</code>```

I would like to define the listener, but provide exchange, queue name and binding at runtime. Also this listener should not start automatically, but when called by start() method. At same time it should auto-declare bindings and queues etc. When called stop(), it should just stop consuming.

答:
I think it's not possible with annotations, but you can create a custom SimpleMessageListenerContainer.

here is a simple solution:

```<code>public static AbstractMessageListenerContainer startListening(RabbitAdmin rabbitAdmin, Queue queue, Exchange exchange, String key, MessageListener messageListener) {
    rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(key).noargs());
    SimpleMessageListenerContainer listener = new SimpleMessageListenerContainer(rabbitAdmin.getRabbitTemplate().getConnectionFactory());
    listener.addQueues(queue);
    listener.setMessageListener(messageListener);
    listener.start();

    return listener;
}
</code>```

and you can call it as:

```<code>ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);

 ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class);
 RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
 AbstractMessageListenerContainer container = startListening(rabbitAdmin, rabbitAdmin.declareQueue(),
         new DirectExchange("amq.direct"), "testRoute", message -> {
             System.out.println(new String(message.getBody()));
         });
</code>```

And you can

AbstractMessageListenerContainer.destroy() or AbstractMessageListenerContainer.stop() it.

Tested with spring boot 1.5.8.RELEASE and RabbitMQ 3.6.10

Body:
What would be the easiest way to construct this at runtime?

@RabbitListener(bindings = @QueueBinding(
    value = @Queue(value = "providedAtRuntime", durable = "true"),
    exchange = @Exchange(value = "providedAtRuntime", ignoreDeclarationExceptions = "true"),
    key = "providedAtRuntime"), containerFactory = "cFac")
public class RabbitProcessor {
    @RabbitHandler
    public void receive (String smth){
        System.out.println(smth);
    }
}

I would like to define the listener, but provide exchange, queue name and binding at runtime. Also this listener should not start automatically, but when called by start() method. At same time it should auto-declare bindings and queues etc. When called stop(), it should just stop consuming.

Body:
I think it's not possible with annotations, but you can create a custom SimpleMessageListenerContainer.

here is a simple solution:

public static AbstractMessageListenerContainer startListening(RabbitAdmin rabbitAdmin, Queue queue, Exchange exchange, String key, MessageListener messageListener) {
    rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(key).noargs());
    SimpleMessageListenerContainer listener = new SimpleMessageListenerContainer(rabbitAdmin.getRabbitTemplate().getConnectionFactory());
    listener.addQueues(queue);
    listener.setMessageListener(messageListener);
    listener.start();

    return listener;
}

and you can call it as:

ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);

 ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class);
 RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
 AbstractMessageListenerContainer container = startListening(rabbitAdmin, rabbitAdmin.declareQueue(),
         new DirectExchange("amq.direct"), "testRoute", message -> {
             System.out.println(new String(message.getBody()));
         });

And you can

AbstractMessageListenerContainer.destroy() or AbstractMessageListenerContainer.stop() it.

Tested with spring boot 1.5.8.RELEASE and RabbitMQ 3.6.10


问:
Kendo ui /GANTT, Turn off popup window
Guys are you able to help me to hide/disable just a popup box when double click on tasks?
http://demos.telerik.com/php-ui/gantt/index

I could add->editable(false); just below:

```<code>// gantt
$gantt = new \Kendo\UI\Gantt('gantt');
$gantt->dataSource($tasks)
      ->dependencies($dependencies)
      ->height(650)
      ->addView(
          '',
          array('type' => 'week', 'selected' => false),
          'month'
      )
      ->addColumn($idColumn, $titleColumn, $startColumn, $endColumn)
      ->showWorkHours(false)
      ->showWorkDays(true)
      ->snap(false)
      ->editable(false);
</code>```

But then I cannot edit anything.
Any clue? Thanks.

答:
I don't see any methods to diable it directly, but you could do a workaroud using the edit method, which attaches a js event on the double click according to the documentation.
I think, if you add something simple like this, it should work:

```<code>function(e) {
    e.preventDefault();
}
</code>```

If not, you could do something similar to prevent the event from firing.

Title: Kendo ui /GANTT, Turn off popup window

Body:
Guys are you able to help me to hide/disable just a popup box when double click on tasks?
http://demos.telerik.com/php-ui/gantt/index

I could add->editable(false); just below:

// gantt
$gantt = new \Kendo\UI\Gantt('gantt');
$gantt->dataSource($tasks)
      ->dependencies($dependencies)
      ->height(650)
      ->addView(
          '',
          array('type' => 'week', 'selected' => false),
          'month'
      )
      ->addColumn($idColumn, $titleColumn, $startColumn, $endColumn)
      ->showWorkHours(false)
      ->showWorkDays(true)
      ->snap(false)
      ->editable(false);

But then I cannot edit anything.
Any clue? Thanks.

Body:
I don't see any methods to diable it directly, but you could do a workaroud using the edit method, which attaches a js event on the double click according to the documentation.
I think, if you add something simple like this, it should work:

function(e) {
    e.preventDefault();
}

If not, you could do something similar to prevent the event from firing.


答:
Couple of issues there.

getPropertyCSSValue is obsolete and may not work in browsers anymore

id is a selector, not a valid css property

Use getPropertyValue instead,

```<code>var message = style.getPropertyCSSValue("background");
</code>```

Demo

var style = window.getComputedStyle(document.getElementById("ctr").children[1])
var message = style.getPropertyValue("background");

console.log("CSS Value is  : " + message)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="ctr" class="faden-slider-container">
  <div class="conteneur-image"></div>
  <div class="conteneur-image"></div>
  <div class="conteneur-image"></div>
</div></code>```

Title: Cant get CSS property from child?

Body:
I have this HTML code here :

And I am trying to get the CSS property of the second div which class' name is conteneur-image but I get nothing :

app.controller("slideCtrl",function ($scope) {
    alert("hello")

    var tab = new Array();
    var elements = new Array();

    for(var i = 0; i<3 ; i++){
        elements[i] = document.getElementById("ctr").children[i]
    }

    var style = window.getComputedStyle(elements[1])
    var message = style.getPropertyCSSValue("background").cssText()

    alert("CSS Value is  : "+message)
})

Body:
Couple of issues there.

getPropertyCSSValue is obsolete and may not work in browsers anymore

id is a selector, not a valid css property

Use getPropertyValue instead,

var message = style.getPropertyCSSValue("background");

Demo

var style = window.getComputedStyle(document.getElementById("ctr").children[1])
var message = style.getPropertyValue("background");

console.log("CSS Value is  : " + message)

<div id="ctr" class="faden-slider-container">
  <div class="conteneur-image"></div>
  <div class="conteneur-image"></div>
  <div class="conteneur-image"></div>
</div>