答:
This can be done by adding the following code

```<code>$.ajax({
                type: "GET",
                url: "your url",
                data: "",
                success: function () {
                        setInterval(functionName,timeInMilliseconds);
        }
  functionName=function(){
//your code comes here which you want to get refreshed
}
</code>```

Using this code after a flag which will test with an if condition that the  product count is updated or not. Cheers.

Title: echo php variable with jquery ajax

Body:
I'm making my first website and I've encountered a problem with AJAX. I have tried and searched a lot of things but I'm missing something, please help me on this one. I have products' count and it works fine, but I need to refresh page everytime when I add new product to cart to see difference, so I need to use AJAX on my php variable. Please help me write AJAX code. I really appreciate it, thanks a lot and have a good day!

PHP Code:

<?php
 $cart = new cart();
 $products = $cart->getCart();
 $sum = 0;
 foreach($products as $product){
     $sum += $product->count;
 }
 echo $sum;
?>

Body:
This can be done by adding the following code

$.ajax({
                type: "GET",
                url: "your url",
                data: "",
                success: function () {
                        setInterval(functionName,timeInMilliseconds);
        }
  functionName=function(){
//your code comes here which you want to get refreshed
}

Using this code after a flag which will test with an if condition that the  product count is updated or not. Cheers.


来源: stackexchange

问:
Distinct is not working?
```<code>  $data = Districts::distinct()->whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->select('region', 'district')->get();
</code>```

I have this query, but problem is that distinct not working. I get for example three records for same thing. Any suggestion?

答:
use this to get one

```<code>$data = Districts::select([ DB::raw('DISTINCT(district)'),'region'])->whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->first();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Distinct is not working?

Body:
  $data = Districts::distinct()->whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->select('region', 'district')->get();

I have this query, but problem is that distinct not working. I get for example three records for same thing. Any suggestion?

Body:
use this to get one

$data = Districts::select([ DB::raw('DISTINCT(district)'),'region'])->whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->first();


问:
How to access individual elements in a line in an RDD of type [String, (Int, Int, Int)]?
I have an RDD that is like this:

```<code>Array((math,(2,3,4)),(economics,(4,5,6)))
</code>```

I want to access the integer elements and add them column wise. I tried with

```<code>var sum = rdd.map( (x,y) => (x._0+y._0,x._1+y._1,x._2+y._2)
</code>```

but this doesn't work. What am I doing wrong? Is there some built-in function that does this?

答:
You can get rid of the string column if you don't need it and then reduce the RDD by the elements:

val sum = rdd.map(_._2).reduce {
  case ((a, b, c), (d, e, f)) => (a + d, b + e, c + f)
}
```

Body:
I have an RDD that is like this:

Array((math,(2,3,4)),(economics,(4,5,6)))

I want to access the integer elements and add them column wise. I tried with

var sum = rdd.map( (x,y) => (x._0+y._0,x._1+y._1,x._2+y._2)

but this doesn't work. What am I doing wrong? Is there some built-in function that does this?


问:
Logging Payload of POSTs to Tomcat
I've managed to enable access logging in Tomcat by editing the conf/server.xml and uncommenting the entry for the org.apache.catalina.valves.AccessLogValve Valve. I'd like to be able to dump the contents of POST's payload. It doesn't seem like any of the options in the pattern will do this. Is there a built in way to do this? Do I use the AccessLogValve?</p>

答:
See RequestDumperValve or RequestDumperFilter here:
http://tomcat.apache.org/tomcat-5.5-doc/config/valve.html#Request_Dumper_Valve
it does what you want.</p>

ContentLicense: CC BY-SA 2.5

Title: Logging Payload of POSTs to Tomcat


问:
What can be the cause for error while building ASP.NET web application?
While I build my solution it shows following error:

'System.Web.HttpRequest' does not contain a definition for 'RequestContext' and no extension method 'RequestContext' accepting a first argument of type 'System.Web.HttpRequest' could be found (are you missing a using directive or an assembly reference?)

What dll or reference I am missing!

Code:

```<code> public void ProcessRequest(HttpContext context)
    {
        try
        {
            HttpRequest request = context.Request;
            string methodName = "";
            if (request.RequestContext.RouteData.Values["methodName"] != null)
            {
                methodName = request.RequestContext.RouteData.Values["methodName"].ToString();
            }
            else
            {
                methodName = request.RawUrl.Substring(request.RawUrl.LastIndexOf("/") + 1);
            }

            //if form post was made way to get values
            //context.Request.Form["firstName"]; //parameter key
            string json = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
            JavaScriptSerializer jss = new JavaScriptSerializer();
            ServiceProcesser process = new ServiceProcesser(typeof(AspxCommerce.AdminNotification.AdminNotificationController), json, methodName);
            var response = process.Invoke();

            if (response != null)
            {
                context.Response.ContentType = "application/json";
                context.Response.Write(jss.Serialize(new { d = response }));
            }
            else
            {
                context.Response.ContentType = "application/json";
                context.Response.Write(jss.Serialize(new { d = "" }));
            }
        }
        catch (Exception ex)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            context.Response.ContentType = "application/json";
            var resp = new { d = ex.Message.ToString() };
            context.Response.Write(jss.Serialize(resp));
        }
    }
</code>```

For full source you can explore my github repo:
https://github.com/Milstein/Ratamata

答:
I had a similar issue. In my case it was due to the wrong assembly that has been referred (yes, a silly mistake..) .
Which was *C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Web.Http.dll*.

Then I installed Microsoft.AspNet.WebApi.Core package using Install-Package Microsoft.AspNet.WebApi.Core command.

Then it will refer *~\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll*.

Body:
While I build my solution it shows following error:

'System.Web.HttpRequest' does not contain a definition for 'RequestContext' and no extension method 'RequestContext' accepting a first argument of type 'System.Web.HttpRequest' could be found (are you missing a using directive or an assembly reference?)

What dll or reference I am missing!

Code:

 public void ProcessRequest(HttpContext context)
    {
        try
        {
            HttpRequest request = context.Request;
            string methodName = "";
            if (request.RequestContext.RouteData.Values["methodName"] != null)
            {
                methodName = request.RequestContext.RouteData.Values["methodName"].ToString();
            }
            else
            {
                methodName = request.RawUrl.Substring(request.RawUrl.LastIndexOf("/") + 1);
            }

            //if form post was made way to get values
            //context.Request.Form["firstName"]; //parameter key
            string json = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
            JavaScriptSerializer jss = new JavaScriptSerializer();
            ServiceProcesser process = new ServiceProcesser(typeof(AspxCommerce.AdminNotification.AdminNotificationController), json, methodName);
            var response = process.Invoke();

            if (response != null)
            {
                context.Response.ContentType = "application/json";
                context.Response.Write(jss.Serialize(new { d = response }));
            }
            else
            {
                context.Response.ContentType = "application/json";
                context.Response.Write(jss.Serialize(new { d = "" }));
            }
        }
        catch (Exception ex)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            context.Response.ContentType = "application/json";
            var resp = new { d = ex.Message.ToString() };
            context.Response.Write(jss.Serialize(resp));
        }
    }

For full source you can explore my github repo:
https://github.com/Milstein/Ratamata


问:
JavaScript, iterate class and on click show hidden tr
No jQuery.

I want to loop through unknown amount of table rows with the same class and add a click event that will change the class of hidden table row that is right bellow the one i clicked. All i managed to do is open all hidden rows on click..

Here is a fiddle with my current progres: jsfiddle.net

An my js code, that obviously doesn't work...

```<code>var x = document.querySelectorAll('.table');
var y = document.querySelectorAll(".content");

for (var i = 0; i < x.length; i++) {
  x[i].addEventListener('click', function(event) {
    for (var j = 0; j < y.length; j++) {
      if (i === j) {
        y[j].style.display = "block";
      }
    }
  });
}
</code>```

EDIT:

Also i saw that it is bad to make functions inside loops. Would appreciate some feedback on that as well...

答:
Try with nextElementSibling function

Demo fiddle

var x = document.querySelectorAll('.table');

for (var i = 0; i < x.length; i++) {
    x[i].addEventListener('click', function(event) {
       this.nextElementSibling.style.display='block';
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table tr td {
  border: 2px solid #000;
}

table {
  width: 500px;
  height: 40px;
}

.content {
  display: none;
  width: 100px;
}

.table:hover {
  background-color: red;
}

.content.visible {
  display: table-cell;
}</code>```

          Tabela

          Visible

          Hidden 1

          Visible

          Hidden 2

          Visible

          Hidden 3

          Visible

          Hidden 4

```
</div>
</div>
</p>

<p><strong>or</strong> If you need like <strong><code>toggle  effect</code></strong> (reclick to hide) use this js code</p>

```var x = document.querySelectorAll('.table');

for (var i = 0; i < x.length; i++) {
    x[i].addEventListener('click', function(event) {
    var a = this.nextElementSibling.style.display;
        this.nextElementSibling.style.display = (a == 'block') ? 'none': 'block';

    });
}
```

Body:
No jQuery.

I want to loop through unknown amount of table rows with the same class and add a click event that will change the class of hidden table row that is right bellow the one i clicked. All i managed to do is open all hidden rows on click..

Here is a fiddle with my current progres: jsfiddle.net

An my js code, that obviously doesn't work...

var x = document.querySelectorAll('.table');
var y = document.querySelectorAll(".content");

for (var i = 0; i < x.length; i++) {
  x[i].addEventListener('click', function(event) {
    for (var j = 0; j < y.length; j++) {
      if (i === j) {
        y[j].style.display = "block";
      }
    }
  });
}

EDIT:

Also i saw that it is bad to make functions inside loops. Would appreciate some feedback on that as well...

Body:
Try with nextElementSibling function

Demo fiddle

var x = document.querySelectorAll('.table');

for (var i = 0; i < x.length; i++) {
    x[i].addEventListener('click', function(event) {
       this.nextElementSibling.style.display='block';
    });
}

table tr td {
  border: 2px solid #000;
}

table {
  width: 500px;
  height: 40px;
}

.content {
  display: none;
  width: 100px;
}

.table:hover {
  background-color: red;
}

.content.visible {
  display: table-cell;
}

    <table>
      <thead>
        <tr>
          <th>Tabela</th>
        </tr>
      </thead>

      <tbody>
        <tr class="table">
          <td>Visible</td>
        </tr>
        <tr class="content">
          <td>Hidden 1</td>
        </tr>
        <tr class="table">
          <td>Visible</td>
        </tr>
        <tr class="content">
          <td>Hidden 2</td>
        </tr>
        <tr class="table">
          <td>Visible</td>
        </tr>
        <tr class="content">
          <td>Hidden 3</td>
        </tr>
        <tr class="table">
          <td>Visible</td>
        </tr>
        <tr class="content">
          <td>Hidden 4</td>
        </tr>
      </tbody>
    </table>

or If you need like toggle  effect (reclick to hide) use this js code

var x = document.querySelectorAll('.table');

for (var i = 0; i < x.length; i++) {
    x[i].addEventListener('click', function(event) {
    var a = this.nextElementSibling.style.display;
        this.nextElementSibling.style.display = (a == 'block') ? 'none': 'block';

    });
}


问:
Extracting json records from sequence files in spark scala
I have a sequence file containing multiple json records. I want to send every json record to a function . How can I extract one json record at a time?</p>

答:
You can read content of your sequence files to RDD[String] and convert it to Spark Dataframe.</p>

```<code>val seqFileContent = sc
  .sequenceFile[LongWritable, BytesWritable](inputFilename)
  .map(x => new String(x._2.getBytes))
val dataframeFromJson = sqlContext.read.json(seqFileContent)
</code>```

Body:
You can read content of your sequence files to RDD[String] and convert it to Spark Dataframe.

val seqFileContent = sc
  .sequenceFile[LongWritable, BytesWritable](inputFilename)
  .map(x => new String(x._2.getBytes))
val dataframeFromJson = sqlContext.read.json(seqFileContent)


问:
Background image not showing in browser
I have a question. I am pretty new to coding and I am trying to make my own website. I want to add a background image to my website but the image is not showing up. I have tried several things but without luck. I have added code of what I have done in my html file. I hope someone can help me with this and point me in the right direction.

This is what my html file looks like:

<!DOCTYPE html>

     <link rel="stylesheet" type="text/css" href="./Lusofly virtual.css" />
     <title>Lusofly Virtual</title>

Lusofly Virtual

HOME

COMMUNITY

CONTACT

PILOT AREA

```

Thanks in advance

答:
Updated your css.

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="./Lusofly virtual.css" />
  <title>Lusofly Virtual</title>

Lusofly Virtual

HOME

COMMUNITY

CONTACT

PILOT AREA

```

Title: Background image not showing in browser

Body:
I have a question. I am pretty new to coding and I am trying to make my own website. I want to add a background image to my website but the image is not showing up. I have tried several things but without luck. I have added code of what I have done in my html file. I hope someone can help me with this and point me in the right direction.

This is what my html file looks like:

<!DOCTYPE html>

     <link rel="stylesheet" type="text/css" href="./Lusofly virtual.css" />
     <title>Lusofly Virtual</title>

Lusofly Virtual

HOME

COMMUNITY

CONTACT

PILOT AREA

Thanks in advance

Body:
Updated your css.

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="./Lusofly virtual.css" />
  <title>Lusofly Virtual</title>
  <style type="text/css">
    body {
      background-color: gray;
    }

    .header {
      background-image: url('http://placehold.it/800x800.jpg');
      background-repeat: no-repeat;
      background-size: contain;
      height: 200px;
      width: 1200px;
    }
  </style>
</head>

<body>

  <div class="header">

    <div class="container">

      <div class="logo">
        <h1><a href="#">Lusofly Virtual</a></h1>
      </div>

      <div class="nav">
        <ul>
          <li><a href="#">HOME</a></li>
          <li><a href="#">COMMUNITY</a></li>
          <li><a href="#">CONTACT</a></li>
          <li><a href="#">PILOT AREA</a></li>
        </ul>
      </div>
    </div>
  </div>
</body>

</html>


问:
How to access the nested JSON objects
I want to access nested JSON object values by iterating.

I tried console.log(test[0].Invoice[0].Cost.NO[0]); but it's not working.

var test = [{
  "Invoice": {
    "NO": "869",
    "$$hashKey": "object:186"
  },
  "Cost": [{
    "NO": 183,
    "Amnt": 100
  }, {
    "NO": 184,
    "Amnt": 200
  }]
}, {
  "Invoice": {
    "NO": "698",
    "$$hashKey": "object:189"
  },
  "Cost": [{
    "NO": 110,
    "Amnt": 150
  }, {
    "NO": 142,
    "Amnt": 263
  }]
}];

console.log(test[0].Invoice[0].Cost.NO[0]);```

答:
```<code> var test = [{ "Invoice": { "NO": "869", "$$hashKey": "object:186" }, "Cost": [{ "NO": 183, "Amnt": 100 }, { "NO": 184, "Amnt": 200 }] }, { "Invoice": { "NO": "698", "$$hashKey": "object:189" }, "Cost": [{ "NO": 110, "Amnt": 150 }, { "NO": 142, "Amnt": 263 }] }];
        for (var t in test)
        {
            var obj = test[t];
            console.log(obj.Invoice.NO);
            console.log(obj.Invoice.$$hashKey);
            for ( var cst in obj.Cost)
            {
                console.log("Cost Value: " + obj.Cost[cst].NO + " " + obj.Cost[cst].Amnt);
            }
        }
</code>```

Title: How to access the nested JSON objects


问:
Tweepy: get all friends of a sample of twitter accounts: how to handle protected users
I want to look up all the friends (meaning the twitter users one is following) of a sample of friends of one twitter account, to see what other friends they have in common. The problem is that I don't know how to handle protected accounts, and I keep running into this error:

```<code>tweepy.error.TweepError: Not authorized.
</code>```

This is the code I have:

```<code>...
screen_name = ----
file_name = "followers_data/follower_ids-" + screen_name + ".txt"
with open(file_name) as file:
ids = file.readlines()

num_samples = 30
ids = [x.strip() for x in ids]
friends = [[] for i in range(num_samples)]

for i in range(0, num_samples):
    id = random.choice(ids)
    for friend in tweepy.Cursor(api.friends_ids, id).items():
        print(friend)
        friends[i].append(friend)
</code>```

I have a list of all friends from one account screen_name, from which I load the friend ids. I then want to sample a few of those and look up their friends.

I have also tried something like this:

```<code>def limit_handled(cursor, name):
    try:
        yield cursor.next()
    except tweepy.TweepError:
        print("Something went wrong... ", name)
        pass

for i in range(0, num_samples):
    id = random.choice(ids)
    items = tweepy.Cursor(api.friends_ids, id).items()
    for friend in limit_handled(items, id):
        print(friend)
        friends[i].append(friend)
</code>```

But then it seems like only one friend per sample friend is stored before moving on to the next sample. I'm pretty new to Python and Tweepy so if anything looks weird, please let me know.

答:
First of all, a couple of comments on naming. The names file and id are protected, so you should avoid using them to name variables - I have changes these.

Secondly, when you initialise your tweepy API, it's clever enough to deal with rate limits if you use wait_on_rate_limit=True and will inform you when it's delayed due to rate limits if you use wait_on_rate_limit_notify=True.

You also lose some information when you set friends = [[] for i in range(num_samples)], as you then won't be able to associate the friends you find with the account they relate to. You can instead use a dictionary, which will associate each ID used with the friends found, allowing for better processing.

My corrected code is as follows:

```<code>import tweepy
import random

consumer_key = '...'
consumer_secret = '...'
access_token = '...'
access_token_secret = '...'

# OAuth process, using the keys and tokens
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

# Creation of the actual interface, using authentication. Use rate limits.
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

screen_name = '----'
file_name = "followers_data/follower_ids-" + screen_name + ".txt"
with open(file_name) as f:
    ids = [x.strip() for x in f.readlines()]

num_samples = 30
friends = dict()

# Initialise i
i = 0

# We want to check that i is less than our number of samples, but we also need to make
# sure there are IDs left to choose from.
while i <= num_samples and ids:
    current_id = random.choice(ids)

    # remove the ID we're testing from the list, so we don't pick it again.
    ids.remove(current_id)

    try:
        # try to get friends, and add them to our dictionary value if we can
        # use .get() to cope with the first loop.
        for page in tweepy.Cursor(api.friends_ids, current_id).pages():
            friends[current_id] = friends.get(current_id, []) + page
        i += 1
    except tweepy.TweepError:
        # we get a tweep error when we can't view a user - skip them and move onto the next.
        # don't increment i as we want to replace this user with someone else.
        print 'Could not view user {}, skipping...'.format(current_id)
</code>```

The output is a dictionary, friends, with keys of user IDs and items of the friends for each user.

Body:
I want to look up all the friends (meaning the twitter users one is following) of a sample of friends of one twitter account, to see what other friends they have in common. The problem is that I don't know how to handle protected accounts, and I keep running into this error:

tweepy.error.TweepError: Not authorized.

This is the code I have:

...
screen_name = ----
file_name = "followers_data/follower_ids-" + screen_name + ".txt"
with open(file_name) as file:
ids = file.readlines()

num_samples = 30
ids = [x.strip() for x in ids]
friends = [[] for i in range(num_samples)]

for i in range(0, num_samples):
    id = random.choice(ids)
    for friend in tweepy.Cursor(api.friends_ids, id).items():
        print(friend)
        friends[i].append(friend)

I have a list of all friends from one account screen_name, from which I load the friend ids. I then want to sample a few of those and look up their friends.

I have also tried something like this:

def limit_handled(cursor, name):
    try:
        yield cursor.next()
    except tweepy.TweepError:
        print("Something went wrong... ", name)
        pass

for i in range(0, num_samples):
    id = random.choice(ids)
    items = tweepy.Cursor(api.friends_ids, id).items()
    for friend in limit_handled(items, id):
        print(friend)
        friends[i].append(friend)

But then it seems like only one friend per sample friend is stored before moving on to the next sample. I'm pretty new to Python and Tweepy so if anything looks weird, please let me know.

Body:
First of all, a couple of comments on naming. The names file and id are protected, so you should avoid using them to name variables - I have changes these.

Secondly, when you initialise your tweepy API, it's clever enough to deal with rate limits if you use wait_on_rate_limit=True and will inform you when it's delayed due to rate limits if you use wait_on_rate_limit_notify=True.

You also lose some information when you set friends = [[] for i in range(num_samples)], as you then won't be able to associate the friends you find with the account they relate to. You can instead use a dictionary, which will associate each ID used with the friends found, allowing for better processing.

My corrected code is as follows:

import tweepy
import random

consumer_key = '...'
consumer_secret = '...'
access_token = '...'
access_token_secret = '...'

# OAuth process, using the keys and tokens
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

# Creation of the actual interface, using authentication. Use rate limits.
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

screen_name = '----'
file_name = "followers_data/follower_ids-" + screen_name + ".txt"
with open(file_name) as f:
    ids = [x.strip() for x in f.readlines()]

num_samples = 30
friends = dict()

# Initialise i
i = 0

# We want to check that i is less than our number of samples, but we also need to make
# sure there are IDs left to choose from.
while i <= num_samples and ids:
    current_id = random.choice(ids)

    # remove the ID we're testing from the list, so we don't pick it again.
    ids.remove(current_id)

    try:
        # try to get friends, and add them to our dictionary value if we can
        # use .get() to cope with the first loop.
        for page in tweepy.Cursor(api.friends_ids, current_id).pages():
            friends[current_id] = friends.get(current_id, []) + page
        i += 1
    except tweepy.TweepError:
        # we get a tweep error when we can't view a user - skip them and move onto the next.
        # don't increment i as we want to replace this user with someone else.
        print 'Could not view user {}, skipping...'.format(current_id)

The output is a dictionary, friends, with keys of user IDs and items of the friends for each user.


问:
Calculate the time stamp of year
Given that I have $num_years, how can I add it to Time()  to get a time stamp $num_years hence?

答:
Well if you looking for the timestamp for just that time then use mktime

```<code>mktime(0,0,0,0,0,$noOfYears);
</code>```

http://www.php.net/manual/en/function.mktime.php

Title: Calculate the time stamp of year

Body:
Well if you looking for the timestamp for just that time then use mktime

mktime(0,0,0,0,0,$noOfYears);

http://www.php.net/manual/en/function.mktime.php


问:
Directly Access RAM on AUTOSAR Environtment
I want to read value in RAM with given address and length of data. I have read several RTE API's and I think there is no API provide my needs. I hope there is API like Rte_Ram_read(address,length) or something else. I found API for access PerInstanceMemory or InterRunnableVariable, but they didn't work like what I want.

My question, Is there any API like what I want? or I have to create that by myself? or is there any advice for me?

答:
It depends on which SWC puts the data in the RAM. The responsibility to define an interface is taken by this SWC.

I believe that it is according to AUTOSAR if you define a pointer to the desired address and read the value.

For example, if the value is 32-bit:

```<code>unsigned int * pAddr = (unsigned int *)0xYYYYZZZZ;
int value = *pAddr;
</code>```

0xYYYYZZZZ is the address in the RAM that you want to read from. Normally, it should be byte aligned by 4(depends on the processor).

Also you should take care for endianness(either big or little endian), because bytes may be in reversed order.

Body:
It depends on which SWC puts the data in the RAM. The responsibility to define an interface is taken by this SWC.

I believe that it is according to AUTOSAR if you define a pointer to the desired address and read the value.

For example, if the value is 32-bit:

unsigned int * pAddr = (unsigned int *)0xYYYYZZZZ;
int value = *pAddr;

0xYYYYZZZZ is the address in the RAM that you want to read from. Normally, it should be byte aligned by 4(depends on the processor).

Also you should take care for endianness(either big or little endian), because bytes may be in reversed order.


问:
How can I get rid of an "unused variable" warning in Xcode?
I understand exactly why unused variable warnings occur. I don't want to suppress them in general, because they are incredibly useful in most cases. However, consider the following (contrived) code.

```<code>NSError *error = nil;
BOOL saved = [moc save:&error];
NSAssert1(saved, @"Dude!!1! %@!!!", error);
</code>```

Xcode reports that saved is an unused variable, when of course it isn't. I suspect this is because NSAssert1 is a macro. The NS_BLOCK_ASSERTIONS macro is not defined, so Objective C assertions are definitely enabled.

While it doesn't hurt anything, I find it untidy and annoying, and I want to suppress it, but I'm not sure how to do so. Assigning the variable to itself gets rid of the compiler warning, but I'd rather do it the "right" way if such a thing exists.

答:
This is the way you do it in C and therefore also Objective-C.

Even though you do not have warnings enabled, it's always a good idea to mark the return value as explicitly ignored. It also goes to show other developers, that you have not just forgotten about the return value – you have indeed explicitly chosen to ignore it.

```<code>(void)[moc save:&error];
</code>```

EDIT: Compilers ignore casts to void, so it should not affect performance – it's just a nice clean human annotation.

Body:
I understand exactly why unused variable warnings occur. I don't want to suppress them in general, because they are incredibly useful in most cases. However, consider the following (contrived) code.

NSError *error = nil;
BOOL saved = [moc save:&error];
NSAssert1(saved, @"Dude!!1! %@!!!", error);

Xcode reports that saved is an unused variable, when of course it isn't. I suspect this is because NSAssert1 is a macro. The NS_BLOCK_ASSERTIONS macro is not defined, so Objective C assertions are definitely enabled.

While it doesn't hurt anything, I find it untidy and annoying, and I want to suppress it, but I'm not sure how to do so. Assigning the variable to itself gets rid of the compiler warning, but I'd rather do it the "right" way if such a thing exists.

Body:
This is the way you do it in C and therefore also Objective-C.

Even though you do not have warnings enabled, it's always a good idea to mark the return value as explicitly ignored. It also goes to show other developers, that you have not just forgotten about the return value – you have indeed explicitly chosen to ignore it.

(void)[moc save:&error];

EDIT: Compilers ignore casts to void, so it should not affect performance – it's just a nice clean human annotation.

ContentLicense: CC BY-SA 4.0


问:
Transform array by cutting in half but extend elements
I want to transform an existing array to display it. Therefore I cut the array in half but add the content of the cut element to the remained elements.

```<code># source structure
s = [[1, 'blue'],
     [2, 'red'],
     [3, 'yellow'],
     [4, 'green'],
     [5, 'orange'],
     [6, 'black']]

# result structure
format_array(s)
# [[1, 'blue', 4, 'green'],
#  [2, 'red', 5, 'orange'],
#  [3, 'yellow', 6, 'black']]
</code>```

How would you achieve it?

答:
a maths trick -))</p>

```<code>s.group_by {|a| a[0]%((s.length)/2) }.values.map {|e| e.flatten }
# [
#   [1, "blue", 4, "green"],
#   [2, "red", 5, "orange"],
#   [3, "yellow", 6, "black"]
# ]
</code>```

Body:
I want to transform an existing array to display it. Therefore I cut the array in half but add the content of the cut element to the remained elements.

# source structure
s = [[1, 'blue'],
     [2, 'red'],
     [3, 'yellow'],
     [4, 'green'],
     [5, 'orange'],
     [6, 'black']]

# result structure
format_array(s)
# [[1, 'blue', 4, 'green'],
#  [2, 'red', 5, 'orange'],
#  [3, 'yellow', 6, 'black']]

How would you achieve it?

Body:
a maths trick -))

s.group_by {|a| a[0]%((s.length)/2) }.values.map {|e| e.flatten }
# [
#   [1, "blue", 4, "green"],
#   [2, "red", 5, "orange"],
#   [3, "yellow", 6, "black"]
# ]


问:
howto highlight matched text for ex mode output in vim like :syntax command does?
I'm not talking about syntax, highlight for normal mode text.
What I want to do is to highlight the output text of ex mode command, Ex.

```<code>:g/re/p
</code>```

command will print out the lines which match re, but how to highlight the output text on screen.  I noticed that

```<code>:syntax
</code>```

command output text on screen with highlight, that's what I want.

答:
Just set hlsearch

```<code>:set hlsearch
</code>```

or simply

```<code>:set hls
</code>```

from :help hls

```<code>'hlsearch' 'hls'    boolean (default off)
                    global
                    {not in Vi}
                    {not available when compiled without the
                    |+extra_search| feature}
    When there is a previous search pattern, highlight all its matches.
    The type of highlighting used can be set with the 'l' occasion in
</code>```

the
        'highlight' option.  This uses the "Search" highlight group by

        default.  Note that only the matching text is highlighted, any

 offsets
        are not applied.

Body:
I'm not talking about syntax, highlight for normal mode text.
What I want to do is to highlight the output text of ex mode command, Ex.

:g/re/p

command will print out the lines which match re, but how to highlight the output text on screen.  I noticed that

:syntax

command output text on screen with highlight, that's what I want.

Body:
Just set hlsearch

:set hlsearch

or simply

:set hls

from :help hls

'hlsearch' 'hls'    boolean (default off)
                    global
                    {not in Vi}
                    {not available when compiled without the
                    |+extra_search| feature}
    When there is a previous search pattern, highlight all its matches.
    The type of highlighting used can be set with the 'l' occasion in

the
        'highlight' option.  This uses the "Search" highlight group by

        default.  Note that only the matching text is highlighted, any

 offsets
        are not applied.


问:
How to filter array using same key value of(preview_url and countries code) and return higher amount of array and unmatch array data will be same
I have this array i want sorting using same preview_url and same countries code and want result which array have higher amount of value and unmatch array data remain same.
I want result i have add in comment please provide sollution for same i have stuck on this issue from couple of days

Thanks in advance

```<code>Array
(
    [id] => 377556
    [amount] => 1.46000
    [preview_url] => https://itunes.apple.com/app/id543186831?mt=8
    [countries] => Array
        (
            [US] => Array
                (
                    [id] => 840
                    [code] => US
                    [name] => united states
                    [regions] => Array
                        (
                        )
                )
        )
)
Array
(
    [id] => 377557
    [amount] => 2.46000
    [preview_url] => https://itunes.apple.com/app/id543186831?mt=8
    [countries] => Array
        (
            [US] => Array
                (
                    [id] => 840
                    [code] => US
                    [name] => united states
                )
            [UK] => Array
                (
                    [id] => 841
                    [code] => UK
                    [name] => united kingdom
                )
        )
)
</code>```

答:
You can sort it by using usort.

```<code>usort($array, function($a, $b) {
     return $a['amount'] < $b['amount'];
});
</code>```

For details refer this great answer by christian. Kudos

Happy Coding.

Body:
I have this array i want sorting using same preview_url and same countries code and want result which array have higher amount of value and unmatch array data remain same.
I want result i have add in comment please provide sollution for same i have stuck on this issue from couple of days

Thanks in advance

Array
(
    [id] => 377556
    [amount] => 1.46000
    [preview_url] => https://itunes.apple.com/app/id543186831?mt=8
    [countries] => Array
        (
            [US] => Array
                (
                    [id] => 840
                    [code] => US
                    [name] => united states
                    [regions] => Array
                        (
                        )
                )
        )
)
Array
(
    [id] => 377557
    [amount] => 2.46000
    [preview_url] => https://itunes.apple.com/app/id543186831?mt=8
    [countries] => Array
        (
            [US] => Array
                (
                    [id] => 840
                    [code] => US
                    [name] => united states
                )
            [UK] => Array
                (
                    [id] => 841
                    [code] => UK
                    [name] => united kingdom
                )
        )
)

Body:
You can sort it by using usort.

usort($array, function($a, $b) {
     return $a['amount'] < $b['amount'];
});

For details refer this great answer by christian. Kudos

Happy Coding.


问:
Cancel long running Task after 5 seconds when not finished
I have created a task which creates an XML string. The task can last multiple seconds. When the task isn't finished after 5 seconds, I want to cancel the Task 'smootly' and continue with writing the rest of the XML. So I built in cancellation inside my task. But although I see the following message in the Log:

ProcessInformationTask timed out

I also see this line in my log

Adding the process information took 10001 ms

I wonder why this can happen because I want to cancel the Task after 5 seconds (if not finished). So I expect the task to last 5 seconds max. How can I solve this? Probably the cancelation isn't setup properly?

Code where I call my task

```<code>string additionalInformation = null;
var contextInfo = new StringBuilder();

var xmlWriterSettings = new XmlWriterSettings()
{
    OmitXmlDeclaration = true,
    ConformanceLevel = ConformanceLevel.Fragment
};

var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;

using (XmlWriter xmlWriter = XmlWriter.Create(contextInfo, xmlWriterSettings))
{
    try
    {
        xmlWriter.WriteStartElement("AdditionalInformation");

        //Write xml (not long running)

        var watch = System.Diagnostics.Stopwatch.StartNew();
        string processInformation = AddProcessesInformation(xmlWriterSettings);
        watch.Stop();
        var elapsedMs = watch.ElapsedMilliseconds;
        Log.Info("Adding the process information took : " + elapsedMs + " ms");

        if (!string.IsNullOrEmpty(processInformation))
        {
            xmlWriter.WriteRaw(processInformation);
        }

        //Write xml (not long running)

        xmlWriter.WriteEndElement();

        additionalInformation = contextInfo.ToString();
    }

    catch (Exception e)
    {
        Log.Info("An exception occured during writing the additional information: " + e.Message);
        return false;
    }

    return true;
}
</code>```

Task method

```<code>private static string AddProcessesInformation(XmlWriterSettings xmlWriterSettings)
    {
        var tokenSource = new CancellationTokenSource();
        var token = tokenSource.Token;
        var contextInfo = new StringBuilder();

        var processInformationTask = Task<string>.Factory.StartNew(() =>
        {
            if (token.IsCancellationRequested)
            {
                Log.Info("Cancellation request for the ProcessInformationTask");
            }

            Thread.Sleep(10000);

            return "Ran without problems'";

        }, token);

        if (!processInformationTask.Wait(5000, token))
        {
            Log.Info("ProcessInformationTask timed out");
            tokenSource.Cancel();
        }

        return processInformationTask?.Result;
    }
</code>```

答:
I think you should check if cancellation is requested multiple Times, after each step in your method. Here is example using for loop:

```<code>    private static string AddProcessesInformation(XmlWriterSettings xmlWriterSettings)
    {
        var tokenSource = new CancellationTokenSource();
        var token = tokenSource.Token;
        var contextInfo = new StringBuilder();

        var processInformationTask = Task<string>.Factory.StartNew(() =>
        {
            for(int i = 0; i < 10; i++)
            {
                if (token.IsCancellationRequested)
                {
                    Console.WriteLine("Cancellation request for the ProcessInformationTask");
                    return string.Empty;
                }
                Thread.Sleep(1000);
            }

            return "Ran without problems'";

        }, token);

        if (!processInformationTask.Wait(5000, token))
        {
            Console.WriteLine("ProcessInformationTask timed out");
            tokenSource.Cancel();
        }

        return processInformationTask?.Result;
    }
</code>```

If inside task method you call other methods, you can pass cancellation token to them and use method token.ThrowIfCancellationRequested() inside.

```<code>        var processInformationTask = Task<string>.Factory.StartNew(() =>
        {
            try
            {
                Method1(token);
                Thread.Sleep(1000);
                Method2(token);
                Thread.Sleep(1000);
            }
            catch(OperationCanceledException ex)
            {
                return string.Empty;
            }
            return "Ran without problems'";

        }, token);

    private static void Method1(CancellationToken token)
    {
        token.ThrowIfCancellationRequested();
        // do more work
    }
</code>```

Body:
I have created a task which creates an XML string. The task can last multiple seconds. When the task isn't finished after 5 seconds, I want to cancel the Task 'smootly' and continue with writing the rest of the XML. So I built in cancellation inside my task. But although I see the following message in the Log:

ProcessInformationTask timed out

I also see this line in my log

Adding the process information took 10001 ms

I wonder why this can happen because I want to cancel the Task after 5 seconds (if not finished). So I expect the task to last 5 seconds max. How can I solve this? Probably the cancelation isn't setup properly?

Code where I call my task

string additionalInformation = null;
var contextInfo = new StringBuilder();

var xmlWriterSettings = new XmlWriterSettings()
{
    OmitXmlDeclaration = true,
    ConformanceLevel = ConformanceLevel.Fragment
};

var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;

using (XmlWriter xmlWriter = XmlWriter.Create(contextInfo, xmlWriterSettings))
{
    try
    {
        xmlWriter.WriteStartElement("AdditionalInformation");

        //Write xml (not long running)

        var watch = System.Diagnostics.Stopwatch.StartNew();
        string processInformation = AddProcessesInformation(xmlWriterSettings);
        watch.Stop();
        var elapsedMs = watch.ElapsedMilliseconds;
        Log.Info("Adding the process information took : " + elapsedMs + " ms");

        if (!string.IsNullOrEmpty(processInformation))
        {
            xmlWriter.WriteRaw(processInformation);
        }

        //Write xml (not long running)

        xmlWriter.WriteEndElement();

        additionalInformation = contextInfo.ToString();
    }

    catch (Exception e)
    {
        Log.Info("An exception occured during writing the additional information: " + e.Message);
        return false;
    }

    return true;
}

Task method

private static string AddProcessesInformation(XmlWriterSettings xmlWriterSettings)
    {
        var tokenSource = new CancellationTokenSource();
        var token = tokenSource.Token;
        var contextInfo = new StringBuilder();

        var processInformationTask = Task<string>.Factory.StartNew(() =>
        {
            if (token.IsCancellationRequested)
            {
                Log.Info("Cancellation request for the ProcessInformationTask");
            }

            Thread.Sleep(10000);

            return "Ran without problems'";

        }, token);

        if (!processInformationTask.Wait(5000, token))
        {
            Log.Info("ProcessInformationTask timed out");
            tokenSource.Cancel();
        }

        return processInformationTask?.Result;
    }

Body:
I think you should check if cancellation is requested multiple Times, after each step in your method. Here is example using for loop:

    private static string AddProcessesInformation(XmlWriterSettings xmlWriterSettings)
    {
        var tokenSource = new CancellationTokenSource();
        var token = tokenSource.Token;
        var contextInfo = new StringBuilder();

        var processInformationTask = Task<string>.Factory.StartNew(() =>
        {
            for(int i = 0; i < 10; i++)
            {
                if (token.IsCancellationRequested)
                {
                    Console.WriteLine("Cancellation request for the ProcessInformationTask");
                    return string.Empty;
                }
                Thread.Sleep(1000);
            }

            return "Ran without problems'";

        }, token);

        if (!processInformationTask.Wait(5000, token))
        {
            Console.WriteLine("ProcessInformationTask timed out");
            tokenSource.Cancel();
        }

        return processInformationTask?.Result;
    }

If inside task method you call other methods, you can pass cancellation token to them and use method token.ThrowIfCancellationRequested() inside.

        var processInformationTask = Task<string>.Factory.StartNew(() =>
        {
            try
            {
                Method1(token);
                Thread.Sleep(1000);
                Method2(token);
                Thread.Sleep(1000);
            }
            catch(OperationCanceledException ex)
            {
                return string.Empty;
            }
            return "Ran without problems'";

        }, token);

    private static void Method1(CancellationToken token)
    {
        token.ThrowIfCancellationRequested();
        // do more work
    }


问:
Retrieving data from 2 tables in SQLite (android)
I am creating a fitness app and have 2 sqlite database tables (TABLE_CARDIO & TABLE_WEIGHTS) in which workout info can be saved to. I need to create a query to fetch all data from both of these tables. At the moment I have a query which works and fetched all data from TABLE_CARDIO as shown below:

```<code>public Cursor getWorkoutData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor result = db.rawQuery("SELECT * from "+TABLE_CARDIO,null);
    return result;
}
</code>```

However I need to modify this query so that it can fetch the data from TABLE_WEIGHTS too. I know there are other questions on here about fetching data from 2 tables however, I have failed to understand how to apply a solution to my specific scenario. I thought adding '+TABLE_WEIGHTS,null' after '+TABLE_CARDIO,null' would work but it doesn't. Any help appreciated!

答:
with SQL you can embed multiple select statements into the same query.  for instance,

```<code>SELECT  (
    SELECT *
    FROM   TABLE_CARDIO
    ),
    (
    SELECT *
    FROM TABLE_WEIGHTS
    )
)
</code>```

You can also use Unions,

```<code>SELECT * FROM TABLE_CARDIO UNION SELECT * FROM TABLE_WEIGHTS
</code>```

Of course you are getting all of the data here in one return statement.

So your java string should contain both statements inside of the argument

```<code>"SELECT * FROM " + TABLE_CARDIO + " UNION SELECT * FROM " + TABLE_WEIGHTS
</code>```

rather then

```<code>select * from table_1, null, select * from table_2, null.
</code>```

Body:
I am creating a fitness app and have 2 sqlite database tables (TABLE_CARDIO & TABLE_WEIGHTS) in which workout info can be saved to. I need to create a query to fetch all data from both of these tables. At the moment I have a query which works and fetched all data from TABLE_CARDIO as shown below:

public Cursor getWorkoutData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor result = db.rawQuery("SELECT * from "+TABLE_CARDIO,null);
    return result;
}

However I need to modify this query so that it can fetch the data from TABLE_WEIGHTS too. I know there are other questions on here about fetching data from 2 tables however, I have failed to understand how to apply a solution to my specific scenario. I thought adding '+TABLE_WEIGHTS,null' after '+TABLE_CARDIO,null' would work but it doesn't. Any help appreciated!

Body:
with SQL you can embed multiple select statements into the same query.  for instance,

SELECT  (
    SELECT *
    FROM   TABLE_CARDIO
    ),
    (
    SELECT *
    FROM TABLE_WEIGHTS
    )
)

You can also use Unions,

SELECT * FROM TABLE_CARDIO UNION SELECT * FROM TABLE_WEIGHTS

Of course you are getting all of the data here in one return statement.

So your java string should contain both statements inside of the argument

"SELECT * FROM " + TABLE_CARDIO + " UNION SELECT * FROM " + TABLE_WEIGHTS

rather then

select * from table_1, null, select * from table_2, null.


问:
RegEx Expression for Eclipse that searches for all items that have not been dealt with
To help stop SQL Injection attacks, I am going through about 2000 parameter requests in my code to validate them. I validate them by determining what type of value (e.g. integer, double) they should return and then applying a function to them to sanitize the value.

Any requests I have dealt with look like this

```<code>*SecurityIssues.*(request.getParameter
</code>```

where * signifies any number of characters on the same line.

What RegExp expression can I use in the Eclipse search (CTRL+H) which will help me search for all the ones I have not yet dealt with, i.e. all the times that the text request.getParameter appears when it is not preceded by the word SecurityIssues?

Examples for matches

The regular expression should match each of the following e.g.

```<code>int companyNo = StringFunctions.StringToInt(request.getParameter("COMPANY_NO"))
double percentage = StringFunctions.StringToDouble(request.getParameter("MARKETSHARE"))
int c = request.getParameter("DUMMY")
</code>```

But should not match:

```<code>int companyNo = SecurityIssues.StringToIntCompany(request.getParameter("COMPANY_NO"))
</code>```

答:
With inspiration and the links provided by @michaeak (thank you), as well as testing in https://regex101.com/ I appear to have found the answer:

```<code>^((?!SecurityIssues).)*(request\.getParameter)
</code>```

The advantage of this answer is that I can blacklist the word SecurityIssues, as opposed to having to whitelist the formats that I do want.

Note, that it is relatively slow, and also slowed down my computer a lot when performing the search.

Body:
To help stop SQL Injection attacks, I am going through about 2000 parameter requests in my code to validate them. I validate them by determining what type of value (e.g. integer, double) they should return and then applying a function to them to sanitize the value.

Any requests I have dealt with look like this

*SecurityIssues.*(request.getParameter

where * signifies any number of characters on the same line.

What RegExp expression can I use in the Eclipse search (CTRL+H) which will help me search for all the ones I have not yet dealt with, i.e. all the times that the text request.getParameter appears when it is not preceded by the word SecurityIssues?

Examples for matches

The regular expression should match each of the following e.g.

int companyNo = StringFunctions.StringToInt(request.getParameter("COMPANY_NO"))
double percentage = StringFunctions.StringToDouble(request.getParameter("MARKETSHARE"))
int c = request.getParameter("DUMMY")

But should not match:

int companyNo = SecurityIssues.StringToIntCompany(request.getParameter("COMPANY_NO"))

Body:
With inspiration and the links provided by @michaeak (thank you), as well as testing in https://regex101.com/ I appear to have found the answer:

^((?!SecurityIssues).)*(request\.getParameter)

The advantage of this answer is that I can blacklist the word SecurityIssues, as opposed to having to whitelist the formats that I do want.

Note, that it is relatively slow, and also slowed down my computer a lot when performing the search.


问:
How to resolve same package name in two different dependency issue in Jboss fuse
I'm trying to use Apache POI to work with excel sheet. The application should support .xlsx format files.

For this I am installing these two dependency as bundles in Jboss FUSE:

```<code><bundle start-level="15">wrap:mvn:org.apache.poi/poi/3.5-FINAL</bundle>
<bundle start-level="15">wrap:mvn:org.apache.poi/poi-ooxml/3.15</bundle>
</code>```

However I get an error saying that it finds below package in both the above bundles. Hence there is an ambiguity.

```<code>org.apache.poi.ss.usermodel
</code>```

ERROR:

```<code>Unable to resolve bundle revision wrap_mvn_org.apache.poi_poi-ooxml_3.15 [2133.0] because it exports package 'org.apache.poi.ss.usermodel' and is also exposed to it from bundle revision wrap_mvn_org.apache.poi_poi_3.5-FINAL [2094.0]
</code>```

As a matter of fact:

I need both the Apache POI dependency mentioned above.

Different set of classes belongs to above package in two
dependencies. And these classes are used in application. Hence I cannot unimport/unexport the package from any of the dependency.

Is there any workaround in FUSE to resolve the issue arising due to same package name in two dependencies.

答:
Such kind of problem in OSGi has its own name: Split-package issue, and it has no straight-forward solution. While in Java SE such approach is used in some frameworks, in OSGi it is not supported by the core concept of modules, and I doubt it will ever be.

Usually, such problem is solved by repackaging modules in such way that the packages are not splat beyond the modules. You can find such an approach applied in different frameworks, which provide a separate artifact for using in OSGi. You may do it by your own, by means of some maven plugins like maven-bundle-plugin.

Alternatives to consider may be to:

embed such modules into the bundle which uses it (see http://felix.apache.org/documentation/subprojects/apache-felix-maven-bundle-plugin-bnd.html#embedding-dependencies)

or export them via system package (see
http://felix.apache.org/documentation/subprojects/apache-felix-framework/apache-felix-framework-configuration-properties.html)

But be careful: usually such approaches break the concept of modularity and have it's own risks.

Body:
I'm trying to use Apache POI to work with excel sheet. The application should support .xlsx format files.

For this I am installing these two dependency as bundles in Jboss FUSE:

<bundle start-level="15">wrap:mvn:org.apache.poi/poi/3.5-FINAL</bundle>
<bundle start-level="15">wrap:mvn:org.apache.poi/poi-ooxml/3.15</bundle>

However I get an error saying that it finds below package in both the above bundles. Hence there is an ambiguity.

org.apache.poi.ss.usermodel

ERROR:

Unable to resolve bundle revision wrap_mvn_org.apache.poi_poi-ooxml_3.15 [2133.0] because it exports package 'org.apache.poi.ss.usermodel' and is also exposed to it from bundle revision wrap_mvn_org.apache.poi_poi_3.5-FINAL [2094.0]

As a matter of fact:

I need both the Apache POI dependency mentioned above.

Different set of classes belongs to above package in two
dependencies. And these classes are used in application. Hence I cannot unimport/unexport the package from any of the dependency.

Is there any workaround in FUSE to resolve the issue arising due to same package name in two dependencies.


问:
How to exclude bank holidays from working days calculation?
I have been able to show working days excluding weekdays.
But now i need to know how to also exclude bank holiday. Please help?

This is my current code:

```<code>DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2016/01/01'
SET @EndDate = '2017/01/01'

SELECT
   (DATEDIFF(dd, @StartDate, @EndDate) + 1)
  -(DATEDIFF(wk, @StartDate, @EndDate) * 2)
  -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
  -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
   DECLARE @TotalDays INT,@WorkDays INT
   SET @TotalDays = (DATEDIFF(dd, @StartDate, @EndDate) +1)
  print @TotalDays
</code>```

答:
Try this out, i think it should work</p>

```<code>SELECT COUNT(1)
    FROM  bankholidays
    WHERE (@Region = 1 and Column1 BETWEEN @StartDate AND @EndDate)
    or (@Region = 2 and Column2 BETWEEN @StartDate AND @EndDate
    or (@Region not in (1,2) and Column3 BETWEEN @StartDate AND @EndDate
</code>```

Body:
I have been able to show working days excluding weekdays.
But now i need to know how to also exclude bank holiday. Please help?

This is my current code:

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2016/01/01'
SET @EndDate = '2017/01/01'

SELECT
   (DATEDIFF(dd, @StartDate, @EndDate) + 1)
  -(DATEDIFF(wk, @StartDate, @EndDate) * 2)
  -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
  -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
   DECLARE @TotalDays INT,@WorkDays INT
   SET @TotalDays = (DATEDIFF(dd, @StartDate, @EndDate) +1)
  print @TotalDays

Body:
Try this out, i think it should work

SELECT COUNT(1)
    FROM  bankholidays
    WHERE (@Region = 1 and Column1 BETWEEN @StartDate AND @EndDate)
    or (@Region = 2 and Column2 BETWEEN @StartDate AND @EndDate
    or (@Region not in (1,2) and Column3 BETWEEN @StartDate AND @EndDate


问:
Cascaded batch validation
Is it possible to make a batched validation of annotated fields?

For example, we have a class

```<code>class SomeContainer {

@Valid
List<InnerClass> innerClass;
}

class InnerClass {

@CustomValidator
String validated;

@Valid
NestedClass nestedClass;

}

class NestedClass {

@CustomValidator
String validateToo;
}
</code>```

And when we validate SomeContainer. Validator collect all fields with @CustomValidator and make a some batch (aggregated validation) and if something is wrong the whole SomeContainer object is not valid.

答:
You should try it :)

It's how cascaded validation works. See our documentation here: https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-object-graph-validation

The validation of object graphs is recursive, i.e. if a reference marked for cascaded validation points to an object which itself has properties annotated with @Valid, these references will be followed up by the validation engine as well. The validation engine will ensure that no infinite loops occur during cascaded validation, for example if two objects hold references to each other.

Title: Cascaded batch validation

Body:
Is it possible to make a batched validation of annotated fields?

For example, we have a class

class SomeContainer {

@Valid
List<InnerClass> innerClass;
}

class InnerClass {

@CustomValidator
String validated;

@Valid
NestedClass nestedClass;

}

class NestedClass {

@CustomValidator
String validateToo;
}

And when we validate SomeContainer. Validator collect all fields with @CustomValidator and make a some batch (aggregated validation) and if something is wrong the whole SomeContainer object is not valid.


问:
How can we run two stages in parallel in Jenkins2.0 Pipeline project
How can we run two stages in parallel in Jenkins2.0 Pipeline project.
For ex: in the following code i want to run the two stages to run in parallel i.e. "Build_First_Repo" and "Build_Second_Repo" should run in parallel.

```<code>stage "Build_First_Repo"
    node { sh '''echo 'Build first repo'
                 source ~/.bashrc'''
                 export path_to_perl_library="/path/to/perl/lib/perl5/5.8.8"
                 perl -I <include_files> build_first_view.pl --inputfile ${input_params}

        }

 stage "Build_Second_Repo"
    node { sh '''echo 'Build second repo'
                 source ~/.bashrc'''
                 export path_to_perl_library="/path/to/perl/lib/perl5/5.8.8"
                 perl -I <include_files> build_second_view.pl --inputfile ${input_params}

        }
</code>```

I tried to use the "parallel" keyword but it didnt work.

答:
In declarative pipeline you cannot run stages within a parallel step because steps are part of the stage directive. The declarative flow is like stages -> stage -> steps -> the actual step that you perform.

But, you can achieve it in scripted pipeline. A sample is as follows:

```<code>node(){
    parallel first:{
    stage('stage1'){
        echo 'helloworld'
    }
    },
    second:{
    stage('stage2'){
        echo 'helloworld2'
    }
    }
}
</code>```

Body:
How can we run two stages in parallel in Jenkins2.0 Pipeline project.
For ex: in the following code i want to run the two stages to run in parallel i.e. "Build_First_Repo" and "Build_Second_Repo" should run in parallel.

stage "Build_First_Repo"
    node { sh '''echo 'Build first repo'
                 source ~/.bashrc'''
                 export path_to_perl_library="/path/to/perl/lib/perl5/5.8.8"
                 perl -I <include_files> build_first_view.pl --inputfile ${input_params}

        }

 stage "Build_Second_Repo"
    node { sh '''echo 'Build second repo'
                 source ~/.bashrc'''
                 export path_to_perl_library="/path/to/perl/lib/perl5/5.8.8"
                 perl -I <include_files> build_second_view.pl --inputfile ${input_params}

        }

I tried to use the "parallel" keyword but it didnt work.

Body:
In declarative pipeline you cannot run stages within a parallel step because steps are part of the stage directive. The declarative flow is like stages -> stage -> steps -> the actual step that you perform.

But, you can achieve it in scripted pipeline. A sample is as follows:

node(){
    parallel first:{
    stage('stage1'){
        echo 'helloworld'
    }
    },
    second:{
    stage('stage2'){
        echo 'helloworld2'
    }
    }
}


问:
Using bagof/3 only for the side effect
Solving a very simple exercise in Prolog: print all numbers from 1 to 100, but instead of the number, print 'Fuzz' if number is a multiple of 3, 'Buzz' if multiple of 5, and 'FizzBuzz' if both.

I ended up doing the following:

```<code>fizzbuzz :- forall( between(1, 100, X), fizzbuzz(X) ).
fizzbuzz(X) :- ( write_fb(X) ; write_n(X) ), nl.

write_fb(X) :- bagof(_, fb(X), _).
fb(X) :- X rem 3 =:= 0, write('Fizz').
fb(X) :- X rem 5 =:= 0, write('Buzz').

write_n(X) :- write(X).
</code>```

but isn't there any predicate or a control structure that would avoid using bagof/3 only for its side effect? (I am always a bit unsure with using predicates only for the side effects).

答:
I take the idea of @Kintalken and I just do minimal change in your original code to arrive at this solution:

```<code>fizzbuzz :-
    forall( between(1, 100, X),
        (   fizzbuzz(X, Output),
            format("~w~n", [Output])
        )).

fizzbuzz(X, Output) :-
    (   bagof(Y, fb(X, Y), Ys)
    ->  atomic_list_concat(Ys, Output)
    ;   X = Output
    ).

fb(X, 'Fizz') :- X rem 3 =:= 0.
fb(X, 'Buzz') :- X rem 5 =:= 0.
</code>```

The only change from the code in your question is that first I collect solutions then I print in one place only and not as side effect of predicate that is collected with bagof so you no more have to have side effect inside bagof.

Also as you see now printing is in the second argument of forall so that it is clear where side effects are happening and not hiding elsewhere and there is exactly one place for all side effect of this program not scattered between clauses of different predicates.

Another thing is that instead of conjunction I use -> not because it is any different but because it conveys intention to use bagof to collect solution or do something else if there are no solutions. When I read your question and answers and comments to answers this was part of the discussion?

I do not know how to indent exactly the contents of forall. The way I have indented looks maybe ok but maybe not ok at all. between and fizzbuzz and format are now aligned but only fizzbuzz and format should have been aligned, but between aligned by accident so this is not on purpose, maybe it is confusing, but I don't like to have something like this

```<code>forall(
    between(1, 100, X),
    (   fizzbuzz(X, Output),
        format("~w~n", [Output])
    ))
</code>```

because then forall( looks so lonely all alone by itself on a whole line without anything to help it feel less lonely with its sad little opening paren.

Title: Using bagof/3 only for the side effect

Body:
Solving a very simple exercise in Prolog: print all numbers from 1 to 100, but instead of the number, print 'Fuzz' if number is a multiple of 3, 'Buzz' if multiple of 5, and 'FizzBuzz' if both.

I ended up doing the following:

fizzbuzz :- forall( between(1, 100, X), fizzbuzz(X) ).
fizzbuzz(X) :- ( write_fb(X) ; write_n(X) ), nl.

write_fb(X) :- bagof(_, fb(X), _).
fb(X) :- X rem 3 =:= 0, write('Fizz').
fb(X) :- X rem 5 =:= 0, write('Buzz').

write_n(X) :- write(X).

but isn't there any predicate or a control structure that would avoid using bagof/3 only for its side effect? (I am always a bit unsure with using predicates only for the side effects).

Body:
I take the idea of @Kintalken and I just do minimal change in your original code to arrive at this solution:

fizzbuzz :-
    forall( between(1, 100, X),
        (   fizzbuzz(X, Output),
            format("~w~n", [Output])
        )).

fizzbuzz(X, Output) :-
    (   bagof(Y, fb(X, Y), Ys)
    ->  atomic_list_concat(Ys, Output)
    ;   X = Output
    ).

fb(X, 'Fizz') :- X rem 3 =:= 0.
fb(X, 'Buzz') :- X rem 5 =:= 0.

The only change from the code in your question is that first I collect solutions then I print in one place only and not as side effect of predicate that is collected with bagof so you no more have to have side effect inside bagof.

Also as you see now printing is in the second argument of forall so that it is clear where side effects are happening and not hiding elsewhere and there is exactly one place for all side effect of this program not scattered between clauses of different predicates.

Another thing is that instead of conjunction I use -> not because it is any different but because it conveys intention to use bagof to collect solution or do something else if there are no solutions. When I read your question and answers and comments to answers this was part of the discussion?

I do not know how to indent exactly the contents of forall. The way I have indented looks maybe ok but maybe not ok at all. between and fizzbuzz and format are now aligned but only fizzbuzz and format should have been aligned, but between aligned by accident so this is not on purpose, maybe it is confusing, but I don't like to have something like this

forall(
    between(1, 100, X),
    (   fizzbuzz(X, Output),
        format("~w~n", [Output])
    ))

because then forall( looks so lonely all alone by itself on a whole line without anything to help it feel less lonely with its sad little opening paren.


问:
Error in Office Outlook Add-in during Initiallzation
I get an error as this when loading my Outlook add-in in the Desktop client:

```<code>SCRIPT5022: Office.js has not been fully loaded yet. Please try again later or make sure to add your initialization code on the Office.initialize function.
</code>```

My initialization code looks something like this:

```<code>Office.initialize = function (reason) {
    app.initialize();

    // set adal.js b2c authentication
    setAuthContext();

    // handle any window callback redirections
    authContext.handleWindowCallback();

    checkUser();
    setListeners();
};
</code>```

I tried different variations with the initialize function of Office.js but I get the same error over and over again. This doesn't happen with the same outlook add-in in Outlook online.

Am I doing something wrong with the Office app initialization?

答:
I think you need to use   $(document).ready or window.onload  and then set your code.

From the documentation:

If you are using additional JavaScript frameworks that include their own initialization handler or tests, these should be placed within the Office.initialize event. For example, JQuery's $(document).ready()

code:

```<code>Office.initialize = function () {
// Office is ready
$(document).ready(function () {
    // The document is ready insert your code here

});
};
</code>```

Body:
I get an error as this when loading my Outlook add-in in the Desktop client:

SCRIPT5022: Office.js has not been fully loaded yet. Please try again later or make sure to add your initialization code on the Office.initialize function.

My initialization code looks something like this:

Office.initialize = function (reason) {
    app.initialize();

    // set adal.js b2c authentication
    setAuthContext();

    // handle any window callback redirections
    authContext.handleWindowCallback();

    checkUser();
    setListeners();
};

I tried different variations with the initialize function of Office.js but I get the same error over and over again. This doesn't happen with the same outlook add-in in Outlook online.

Am I doing something wrong with the Office app initialization?

Body:
I think you need to use   $(document).ready or window.onload  and then set your code.

From the documentation:

If you are using additional JavaScript frameworks that include their own initialization handler or tests, these should be placed within the Office.initialize event. For example, JQuery's $(document).ready()

code:

Office.initialize = function () {
// Office is ready
$(document).ready(function () {
    // The document is ready insert your code here

});
};


问:
Reclaim string memory quickly (device with limited RAM)
I am writing a C# app for a device with limited ram. (Mono on iPhone/iPad)

When I assign a large string:

```<code>string xml = "10 meg xml string from REST service";
</code>```

then clear it

```<code>xml = null;
</code>```

Is with the GC free up that memory asap? Is there a way to make sure it's cleaned up. GC has a collect feature, but is this executed right away?

The problem is that I am downloading many large xml files in a loop and even though I am setting the string to null, memory use is growing.

答:
First, keeping large strings or large arrays in memory at once should be avoided, especially on memory constrained devices like phones. Use XmlTextReader, for example, to parse xml files. If you get them from the network, save them to disk, etc.

Next, the issue about garbage collection: the current Mono GC does a conservative scan of the thread stacks, which means that some pointers to objects may be still be visible to the GC, even if to the programmer they have been cleared (like setting to null in your example).
To limit the consequences of this behavior, you should try to allocate or otherwise manipulate big arrays and strings in a separate stack frame. For example, instead of coding it this way:

```<code>  while (true) {
    string s = get_big_string_from_network ();
    do_something_with_string(s);
    handle_ui ();
    s = null;
  }
</code>```

do the following:

```<code>  void manipulate_big_string() {
    string s = get_big_string_from_network ();
    do_something_with_string(s);
  }
  ...
  while (true) {
    manipulate_big_string ();
    handle_ui ();
  }
</code>```

Normally, setting a reference to null has the intended effect only when applied to a static or instance field, using it with a method local variable may not be enough to hide the reference from the GC.

Body:
I am writing a C# app for a device with limited ram. (Mono on iPhone/iPad)

When I assign a large string:

string xml = "10 meg xml string from REST service";

then clear it

xml = null;

Is with the GC free up that memory asap? Is there a way to make sure it's cleaned up. GC has a collect feature, but is this executed right away?

The problem is that I am downloading many large xml files in a loop and even though I am setting the string to null, memory use is growing.

Body:
First, keeping large strings or large arrays in memory at once should be avoided, especially on memory constrained devices like phones. Use XmlTextReader, for example, to parse xml files. If you get them from the network, save them to disk, etc.

Next, the issue about garbage collection: the current Mono GC does a conservative scan of the thread stacks, which means that some pointers to objects may be still be visible to the GC, even if to the programmer they have been cleared (like setting to null in your example).
To limit the consequences of this behavior, you should try to allocate or otherwise manipulate big arrays and strings in a separate stack frame. For example, instead of coding it this way:

  while (true) {
    string s = get_big_string_from_network ();
    do_something_with_string(s);
    handle_ui ();
    s = null;
  }

do the following:

  void manipulate_big_string() {
    string s = get_big_string_from_network ();
    do_something_with_string(s);
  }
  ...
  while (true) {
    manipulate_big_string ();
    handle_ui ();
  }

Normally, setting a reference to null has the intended effect only when applied to a static or instance field, using it with a method local variable may not be enough to hide the reference from the GC.


问:
Using Airbnb API with Facebook Login
This is my first time dealing with logging in using Facebook credentials. I want to be able to query listings in Airbnb through my account. My original account in Airbnb is through Facebook login. Here is the sample request on airbnb page:  http://airbnbapi.org/#login-by-facebook.

I am not sure where can I get my client_id and Facebook's access token. Although it does point to https://developers.facebook.com/docs/facebook-login/access-tokens to get the user access token but, if I understand it correctly, it requires me to create an app. I am not sure what flow of authentication is required for me to use Airbnb API.

I have already looked at Airbnb docs to search for client_id but, of no use.

Here is what I have so far:

```<code>import requests
import json

API_URL = "https://api.airbnb.com"
LISTING_ENDPOINT= "https://api.airbnb.com/v2/search_results"

post_query = {
    "client_id": "I HAVE NO IDEA WHERE TO GET IT",
    "locale": "en-US",
    "currency":"USD",
    "assertion_type":"https://graph.facebook.com/me"
    "assertion":"HOW SHOULD I GET THIS ONE?",
    "prevent_account_creation":True
}

# I think this should be able to log me in and I should be able to query listings
_ = requests.post(API_URL, post_query).json()

query = {
    "client_id":"FROM ABOVE",
    "user_lat": "40.00",
    "user_long":"-54.31"
}

listings = requests.get(LISTING_ENDPOINT, json=query).json()
</code>```

答:
I came across the same problem as you. I figure it out finally. The tool i used is the advanced function of requests library, that is Session(),  for saving cookies. The important part for login with a third party account is to find the link we need to post the cookies. The following is my code.</p>

```<code>import requests
x=requests.Session() #savig the cookies when you click the "log in with facebook button"
y=requests.Session() #saving the cookies for parsing the airbnb listing.
account={'email':'your_facebook_account','pass':'your_facebook_ps'}
log_in_with_facebook_click=x.post("https://www.airbnb.jp/oauth_connect?from=facebook_login&service=facebook")

#all the cookies up to now is saved in "x"
my_first_time_cookies=x.cookies.get_dict()
real_login_link=log_in_with_facebook_click.url

real_log_in=y.post(real_login_link,account,cookies=my_first_time_cookies)
#the real login link is saved in "log_in_with_facebook"
#pass the cookies and your facebook account information to the real login link
#you should have logged into airbnb.For testing the log in, we do the following. We check the reservation data.

from bs4 import BeautifulSoup
page=1
test=y.get("https://www.airbnb.jp/my_reservations?page="+str(page))
#Remember that the cookies we use to access airbnb website after loggin in is saved in "y"
test_html=BeautifulSoup(test.text,'lxml')
print(test_html.text)
#you should have looked your tenants reservation information.
</code>```

Title: Using Airbnb API with Facebook Login

Body:
This is my first time dealing with logging in using Facebook credentials. I want to be able to query listings in Airbnb through my account. My original account in Airbnb is through Facebook login. Here is the sample request on airbnb page:  http://airbnbapi.org/#login-by-facebook.

I am not sure where can I get my client_id and Facebook's access token. Although it does point to https://developers.facebook.com/docs/facebook-login/access-tokens to get the user access token but, if I understand it correctly, it requires me to create an app. I am not sure what flow of authentication is required for me to use Airbnb API.

I have already looked at Airbnb docs to search for client_id but, of no use.

Here is what I have so far:

import requests
import json

API_URL = "https://api.airbnb.com"
LISTING_ENDPOINT= "https://api.airbnb.com/v2/search_results"

post_query = {
    "client_id": "I HAVE NO IDEA WHERE TO GET IT",
    "locale": "en-US",
    "currency":"USD",
    "assertion_type":"https://graph.facebook.com/me"
    "assertion":"HOW SHOULD I GET THIS ONE?",
    "prevent_account_creation":True
}

# I think this should be able to log me in and I should be able to query listings
_ = requests.post(API_URL, post_query).json()

query = {
    "client_id":"FROM ABOVE",
    "user_lat": "40.00",
    "user_long":"-54.31"
}

listings = requests.get(LISTING_ENDPOINT, json=query).json()

Body:
I came across the same problem as you. I figure it out finally. The tool i used is the advanced function of requests library, that is Session(),  for saving cookies. The important part for login with a third party account is to find the link we need to post the cookies. The following is my code.

import requests
x=requests.Session() #savig the cookies when you click the "log in with facebook button"
y=requests.Session() #saving the cookies for parsing the airbnb listing.
account={'email':'your_facebook_account','pass':'your_facebook_ps'}
log_in_with_facebook_click=x.post("https://www.airbnb.jp/oauth_connect?from=facebook_login&service=facebook")

#all the cookies up to now is saved in "x"
my_first_time_cookies=x.cookies.get_dict()
real_login_link=log_in_with_facebook_click.url

real_log_in=y.post(real_login_link,account,cookies=my_first_time_cookies)
#the real login link is saved in "log_in_with_facebook"
#pass the cookies and your facebook account information to the real login link
#you should have logged into airbnb.For testing the log in, we do the following. We check the reservation data.

from bs4 import BeautifulSoup
page=1
test=y.get("https://www.airbnb.jp/my_reservations?page="+str(page))
#Remember that the cookies we use to access airbnb website after loggin in is saved in "y"
test_html=BeautifulSoup(test.text,'lxml')
print(test_html.text)
#you should have looked your tenants reservation information.


问:
How to get Flow to properly work with Vue 2 (webpack)?
I'm trying to add Flow to the Vue 2 webpack-template. For the record, I'm on runtime-only (files follow the .vue format / standard).

My first attempt was to use flow through the cli, which I realized it's not going to work because it didn't know how to handle .vue files.

My second attempt was to add a webpack loader (namely  flow-status-webpack-plugin) and run Flow check as part of the build (like eslint works for example). That didn't work out, so I looked into other options.

My third attempt was to use a babel plugin, which was fairly successful at first. I used babel-plugin-typecheck + babel-plugin-syntax-flow. There's no output in Webpack, however a type error would break the app. I'm fine with this approach; it'll work fine with a CI and break the build.

Here's how my .babelrc looked:

```<code>{
  ...
  "plugins": [
    ...
    ["typecheck", {
      "disable": {
        "production": true
      }
    }],
    "syntax-flow",
    "transform-flow-strip-types"
  ],
  ...
}
</code>```

At this point, Flow works as expected for global methods, but doesn't work inside a Vue component:

```<code><template>...</template>

<script>
/* @flow */
const flowIt = (a: number): number => {
  return a * 10
}

flowIt(20)
flowIt('bah') // Uncaught TypeError: Value of argument "a" violates contract. Expected: number Got: string

export default {
  mounted: function () {
    flowIt(20)
    flowIt('bah') // Sees nothing wrong here
  }
}
</script>

<style>...</style>
</code>```

On top of that, the goal is to not change the app code because of Flow. Ideally, I'd just use Vue as normally:

```<code><template>...</template>

<script>
/* @flow */
export default {
  methods: {
    flowIt (a: number): number {
      return a * 10
    }
  },

  mounted: function () {
    this.flowIt(20)
    this.flowIt('bah') // Should throw a type error.
  }
}
</script>

<style>...</style>
</code>```

Not sure if this has that much to do with Vue as it has with my experience with Flow (hint: not that experienced). I'm thinking I need some type files that make Flow 'understand' how a Vue component is structured (same for directives I guess).

To those that have more experience with it, how did you get Flow to properly work with Vue + webpack?

答:
I think this has been solved in the meantime and now you can use Flow with Vue-components without hacks. See this rather brilliant article for config details:
https://alligator.io/vuejs/components-flow/</p>

Body:
I'm trying to add Flow to the Vue 2 webpack-template. For the record, I'm on runtime-only (files follow the .vue format / standard).

My first attempt was to use flow through the cli, which I realized it's not going to work because it didn't know how to handle .vue files.

My second attempt was to add a webpack loader (namely  flow-status-webpack-plugin) and run Flow check as part of the build (like eslint works for example). That didn't work out, so I looked into other options.

My third attempt was to use a babel plugin, which was fairly successful at first. I used babel-plugin-typecheck + babel-plugin-syntax-flow. There's no output in Webpack, however a type error would break the app. I'm fine with this approach; it'll work fine with a CI and break the build.

Here's how my .babelrc looked:

{
  ...
  "plugins": [
    ...
    ["typecheck", {
      "disable": {
        "production": true
      }
    }],
    "syntax-flow",
    "transform-flow-strip-types"
  ],
  ...
}

At this point, Flow works as expected for global methods, but doesn't work inside a Vue component:

<template>...</template>

On top of that, the goal is to not change the app code because of Flow. Ideally, I'd just use Vue as normally:

<template>...</template>

Not sure if this has that much to do with Vue as it has with my experience with Flow (hint: not that experienced). I'm thinking I need some type files that make Flow 'understand' how a Vue component is structured (same for directives I guess).

To those that have more experience with it, how did you get Flow to properly work with Vue + webpack?


问:
What does this error means and how to fix it "Error in saving to database. error is: The method or operation is not implemented"?
Those are my codes on SAVE Button:</p>

```<code>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim dbCon As MySqlConnection
    Dim conStr As String

    conStr = "server=127.0.0.1;uid=root;pwd=;database=ps20150385"
    Try

    Catch ex As Exception

    End Try
    dbCon = New MySqlConnection(conStr)
    dbCon.Open()
    ' Add record to database
    Dim productName, productCat, unitPrice As String

    productName = Trim(TextBox1.Text)
    productCat = Trim(ComboBox1.Text)
    unitPrice = Trim(TextBox3.Text)

    Dim Sql As String = "INSERT INTO products (ProductName,ProductCat,UnitPrice) VALUES('" & TextBox1.Text & "' , '" & ComboBox1.Text & "' , '" & TextBox3.Text & "')"
    If TextBox1.Text = "" Or ComboBox1.Text = "" Or TextBox3.Text = "" Then
        MsgBox("Please! insert record")
    Else
        MsgBox("Record inserted successfully.")

    End If
    Try
        DbCommand = New MySqlCommand(Sql, dbconn)
        dbread = DbCommand.ExecuteReader()
        Me.Close()
    Catch ex As Exception
        MsgBox("Error in saving to Database. error is :" & ex.Message)
        TextBox1.Text = ""
        ComboBox1.Text = ""
        TextBox3.Text = ""
        Exit Sub

    End Try
    dbread.Close()
    TextBox1.Text = ""
    ComboBox1.Text = ""
    TextBox3.Text = ""

End Sub
</code>```

答:
The first thing that pops out is  that you are using .ExecuteReader()on an INSERTcmd. INSERTshould be executed as .ExecuteNonQuery()

Second thing that pops out is that you are just asking for an sql injection attack (purposeful or accidental). Instead of including TextBox.Text In your queries, you should use parameters. Instead of direct strings. A simple special character will break your query if you don't.

Body:
Those are my codes on SAVE Button:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim dbCon As MySqlConnection
    Dim conStr As String

    conStr = "server=127.0.0.1;uid=root;pwd=;database=ps20150385"
    Try

    Catch ex As Exception

    End Try
    dbCon = New MySqlConnection(conStr)
    dbCon.Open()
    ' Add record to database
    Dim productName, productCat, unitPrice As String

    productName = Trim(TextBox1.Text)
    productCat = Trim(ComboBox1.Text)
    unitPrice = Trim(TextBox3.Text)

    Dim Sql As String = "INSERT INTO products (ProductName,ProductCat,UnitPrice) VALUES('" & TextBox1.Text & "' , '" & ComboBox1.Text & "' , '" & TextBox3.Text & "')"
    If TextBox1.Text = "" Or ComboBox1.Text = "" Or TextBox3.Text = "" Then
        MsgBox("Please! insert record")
    Else
        MsgBox("Record inserted successfully.")

    End If
    Try
        DbCommand = New MySqlCommand(Sql, dbconn)
        dbread = DbCommand.ExecuteReader()
        Me.Close()
    Catch ex As Exception
        MsgBox("Error in saving to Database. error is :" & ex.Message)
        TextBox1.Text = ""
        ComboBox1.Text = ""
        TextBox3.Text = ""
        Exit Sub

    End Try
    dbread.Close()
    TextBox1.Text = ""
    ComboBox1.Text = ""
    TextBox3.Text = ""

End Sub


问:
match columns in 2 tab-delimited text files
I have two tab-delimited .txt files

file1 has 20 million lines and the following structure

```<code>col1    col2    col3    col4    col5
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x
6       x       y       E       x
7       x       z       F       x
</code>```

file2 has 3000 lines and the following structure

```<code>col1
A
B
C
D
</code>```

Now I want to extract from file1 the lines where there is a match between col1 from file2 and col4 of file1

So the new file3 should look like this

```<code>col1    col2    col3    col4    col5
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x
</code>```

How can I do this with perl or bash?

答:
Since you also asked about Perl, here's a reusable perl solution.  You first read file 2, generate an array of lookup values, and then read file 1, printing out any line in which column 4 matches a value inside of the array we created above.  Something like this might work:

```<code>#!/usr/bin/perl
use strict;
use warnings;
use autodie;

my $key_file = shift;
open(my $fh, "<", $key_file);
my $header = <$fh>; # read the header line into '$h'
my %keys = map{ chomp; $_ => 1 }<$fh>;
close $fh;

my $query_file = shift;
open(my $q_fh, "<", $query_file);
print scalar <$q_fh>;
while (<$q_fh>) {
    my @fields = split;
    print if $keys{$fields[3]};
}
close $q_fh;
</code>```

You can run this as table_combine.pl <file2> <file1>.

Body:
I have two tab-delimited .txt files

file1 has 20 million lines and the following structure

col1    col2    col3    col4    col5
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x
6       x       y       E       x
7       x       z       F       x

file2 has 3000 lines and the following structure

col1
A
B
C
D

Now I want to extract from file1 the lines where there is a match between col1 from file2 and col4 of file1

So the new file3 should look like this

col1    col2    col3    col4    col5
1       x       x       A       x
2       y       y       A       x
3       z       z       A       x
4       x       x       B       x
5       x       y       B       x

How can I do this with perl or bash?

Body:
Since you also asked about Perl, here's a reusable perl solution.  You first read file 2, generate an array of lookup values, and then read file 1, printing out any line in which column 4 matches a value inside of the array we created above.  Something like this might work:

#!/usr/bin/perl
use strict;
use warnings;
use autodie;

my $key_file = shift;
open(my $fh, "<", $key_file);
my $header = <$fh>; # read the header line into '$h'
my %keys = map{ chomp; $_ => 1 }<$fh>;
close $fh;

my $query_file = shift;
open(my $q_fh, "<", $query_file);
print scalar <$q_fh>;
while (<$q_fh>) {
    my @fields = split;
    print if $keys{$fields[3]};
}
close $q_fh;

You can run this as table_combine.pl <file2> <file1>.


问:
Navigation in Ionic 2 Not working
I have one login page and want to add a forgot password button, and when a user clicks it, he/she will redirect to the forgot password page.

here is my login.html

```<code><button ion-button block color="blue"
        (click)="goToSignup()"
        class="signup-btn"
        style="background:#45b64a;width:45%;margin:20px 2% 0;display:inline-block">
        Signup</button>
<button ion-button block color="blue"
        (click)="goToForgotPassword()"
        class="signup-btn"
        style="background:#45b64a;width:45%;margin:20px 2% 0;display:inline-block">
        Forgot Password</button>
</code>```

Here is my login.js

```<code>..
..
import {
    SignupPage
}
from '../signup/signup';
import {
    ForgotPasswordPage
}
from '../forgotpassword/forgotpassword';
Page({
    templateUrl: 'build/pages/loginpage/loginpage.html'
})
export class LoginPage {

    static get parameters() {
        return [[NavController], [Http]];
    }
    constructor(nav, http, fbProvider) {
        this.login = {};
    }
    goToSignup() {
        this.nav.push(SignupPage);
    }
    goToForgotPassword(){
        this.nav.push(ForgotPasswordPage);
    }

}
</code>```

Here is my signup.js

```<code>..
..
Page({
    templateUrl: 'build/pages/signup/signup.html'
})

export class SignupPage {
    ..
    ..
}
</code>```

Here is my forgotpassword.js

```<code>..
..
Page({
    templateUrl: 'build/pages/forgotpassword/forgotpassword.html'
})

export class ForgotPasswordPage{
    ..
    ..
}
</code>```

Navigation for Signup is working perfectly, the only issue with is with the ForgotPassword Navigation.

In the browser I am getting the error below.

TypeError: self.context.goToForgotPassword is not a function
      at _View_LoginPage0._handle_click_36_0 (LoginPage.template.js:627:28)

What is going wrong with forgotpassword navigation?

答:
Add your second page in app.module..,
in declarations and in entrycomponents..

for further details check this link

http://blog.ionic.io/10-minutes-with-ionic-2-adding-pages-and-navigation/

Title: Navigation in Ionic 2 Not working

Body:
I have one login page and want to add a forgot password button, and when a user clicks it, he/she will redirect to the forgot password page.

here is my login.html

<button ion-button block color="blue"
        (click)="goToSignup()"
        class="signup-btn"
        style="background:#45b64a;width:45%;margin:20px 2% 0;display:inline-block">
        Signup</button>
<button ion-button block color="blue"
        (click)="goToForgotPassword()"
        class="signup-btn"
        style="background:#45b64a;width:45%;margin:20px 2% 0;display:inline-block">
        Forgot Password</button>

Here is my login.js

..
..
import {
    SignupPage
}
from '../signup/signup';
import {
    ForgotPasswordPage
}
from '../forgotpassword/forgotpassword';
Page({
    templateUrl: 'build/pages/loginpage/loginpage.html'
})
export class LoginPage {

    static get parameters() {
        return [[NavController], [Http]];
    }
    constructor(nav, http, fbProvider) {
        this.login = {};
    }
    goToSignup() {
        this.nav.push(SignupPage);
    }
    goToForgotPassword(){
        this.nav.push(ForgotPasswordPage);
    }

}

Here is my signup.js

..
..
Page({
    templateUrl: 'build/pages/signup/signup.html'
})

export class SignupPage {
    ..
    ..
}

Here is my forgotpassword.js

..
..
Page({
    templateUrl: 'build/pages/forgotpassword/forgotpassword.html'
})

export class ForgotPasswordPage{
    ..
    ..
}

Navigation for Signup is working perfectly, the only issue with is with the ForgotPassword Navigation.

In the browser I am getting the error below.

TypeError: self.context.goToForgotPassword is not a function
      at _View_LoginPage0._handle_click_36_0 (LoginPage.template.js:627:28)

What is going wrong with forgotpassword navigation?


问:
Kubernetes Deployments, Pod and Container concepts
I have started recently getting familiar with Kubernetes, however while I do get the concept I have some questions I am unable to answer clearly through Kubernete's Concept and Documentation, and some understandings that I'd wish to confirm.

A Deployment is a group of one or more container images (Docker ..etc) that is deployed within a Pod, and through Kubernetes Deployment Controller such deployments are monitored and created, updated, or deleted.

A Pod is a group of one or more containers, are those containers from the same Deployment, or can they be from multiple deployments?

"A pod models contains one or more application containers which are relatively tightly coupled". Is there any clear criteria on when to deploy containers within the same pod, rather than separate pods?

"Pods are the smallest deployable units of computing that can be created and managed in Kubernetes" - Pods, Kuberenets Documentation. Is that to mean that Kubernetes API is unable to monitor, and manage containers (at least directly)?

Appreciate your input.

答:
your question is actually too broad for StackOverflow but I'll quickly answer before this one is closed.

Maybe it get's clearer when you look at the API documentation. Which you could read like this:

A Deployment describes a specification of the desired behavior for the contained objects.
This is done within the spec field which is of type DeploymentSpec.

A DeploymentSpec defines how the related Pods should look like with a templatethrough the PodTemplateSpec

The PodTemplateSpec then holds the PodSpec for all the require parameters and that defines how containers within this Pod should look like through a Container definition.

This is not a punchy oneline statement, but maybe makes it easier to see how things relate to each other.

Related to the criteria on what's a good size and what's too big for a Pod or a Container. This is very opinion loaded and the best way to figure that out is to read through the opinions on the size of Microservices.

To cover your last point - Kubernetes is able to monitor and manage containers, but the "user" is not able to schedule single containers. They have to be embedded in a Pod definion. You can of course access Container status and details per container (e.g. through kubeget logs <pod> -c <container> (details) or through the metrics API.

I hope this helps a bit and doesn't add to the confusion.