问:
Issue with 'click' function in 'each' loop
Basically, I have multiple UL's with a class "list". Each of them has multiple radio buttons. I would like to do something with span element upon the last radio option of individual UL's being checked. And undo it after another radio button of that same UL is being checked.

The code essentially works but it is triggering for all of the UL's instead of the one in which the click occurred.

I used alert (which is commented out) to check if I'm getting everything with 'each' and it seems to work fine.

$(document).ready(function() {
  $('ul.list').each(function() {
    //alert($(this).text());
    $("ul.list input[type$='radio']").click(function() {
      if ($("li:last-of-type input[type$='radio']").prop("checked")) {
        // do something with span
      } else {
        // do something with span
      }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="list">
  <li><input type="radio">Option 1</input>
  </li>
  <li><input type="radio">Option 2</input>
  </li>
  <li><input type="radio">Bonus</input><span>Bonus text</span></li>
</ul>

<ul class="list">
  <li><input type="radio">Option 1</input>
  </li>
  <li><input type="radio">Option 2</input>
  </li>
  <li><input type="radio">Bonus</input><span>Bonus text</span></li>
</ul></code>```

答:
Actually you don't need the loop in this case just attach the click directly to the selector :

```<code>$(document).ready(function() {
  $("ul.list :radio").click(function() {
    if ( $(this).prop("checked") )
    {
      // do something with span
    } else {
      // do something with span
    }
  });
});
</code>```

NOTE 1 : The input are self-closing tags so thsy should be like :

```<code><input type="radio"/>Option 1
</code>```

Instead of :

```<code><input type="radio">Option 1</input>
</code>```

NOTE 2 : Use this keyword to target the clicked element instead :

```<code>if( $(this).prop("checked") ){
</code>```

Hope this helps.

$(document).ready(function() {
  $("ul.list :radio").change(function() {
    if ( !$(this).is(':last-child') && $(this).is(":checked") )
    {
      $(this).closest("ul").find('span').show();
    }else{
      $(this).closest("ul").find('span').hide();
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul.list li>span{
   display:none;
}</code>```

<input type="radio" name="same_name_1" checked/>Option 1

<input type="radio" name="same_name_1" />Option 2

<input type="radio" name="same_name_1" />Bonus
Bonus text

<input type="radio" name="same_name_2" checked/>Option 1

<input type="radio" name="same_name_2" />Option 2

<input type="radio" name="same_name_2" />Bonus
Bonus text

```

Body:
Basically, I have multiple UL's with a class "list". Each of them has multiple radio buttons. I would like to do something with span element upon the last radio option of individual UL's being checked. And undo it after another radio button of that same UL is being checked.

The code essentially works but it is triggering for all of the UL's instead of the one in which the click occurred.

I used alert (which is commented out) to check if I'm getting everything with 'each' and it seems to work fine.

$(document).ready(function() {
  $('ul.list').each(function() {
    //alert($(this).text());
    $("ul.list input[type$='radio']").click(function() {
      if ($("li:last-of-type input[type$='radio']").prop("checked")) {
        // do something with span
      } else {
        // do something with span
      }
    });
  });
});

<input type="radio">Option 1</input>

<input type="radio">Option 2</input>

<input type="radio">Bonus</input>Bonus text

<input type="radio">Option 1</input>

<input type="radio">Option 2</input>

<input type="radio">Bonus</input>Bonus text

Body:
Actually you don't need the loop in this case just attach the click directly to the selector :

$(document).ready(function() {
  $("ul.list :radio").click(function() {
    if ( $(this).prop("checked") )
    {
      // do something with span
    } else {
      // do something with span
    }
  });
});

NOTE 1 : The input are self-closing tags so thsy should be like :

<input type="radio"/>Option 1

Instead of :

<input type="radio">Option 1</input>

NOTE 2 : Use this keyword to target the clicked element instead :

if( $(this).prop("checked") ){

Hope this helps.

$(document).ready(function() {
  $("ul.list :radio").change(function() {
    if ( !$(this).is(':last-child') && $(this).is(":checked") )
    {
      $(this).closest("ul").find('span').show();
    }else{
      $(this).closest("ul").find('span').hide();
    }
  });
});

ul.list li>span{
   display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="list">
  <li><input type="radio" name="same_name_1" checked/>Option 1</li>
  <li><input type="radio" name="same_name_1" />Option 2</li>
  <li><input type="radio" name="same_name_1" />Bonus<br><span>Bonus text</span></li>
</ul>

<ul class="list">
  <li><input type="radio" name="same_name_2" checked/>Option 1</li>
  <li><input type="radio" name="same_name_2" />Option 2</li>
  <li><input type="radio" name="same_name_2" />Bonus<br><span>Bonus text</span></li>
</ul>


来源: stackexchange

问:
heatmap using geom_tile in ggplot2() - looking for the equivalent of older code
I've got a data frame with three variables: location, weather, and wc.

I'd like to make a heatmap using  geom_tile in ggplot2(), so that weather is on the y axis, location on the x axis, and wc being the fill. I found some code on https://learnr.wordpress.com/2010/01/26/ggplot2-quick-heatmap-plotting/, producing exactly the kind of plot I'm looking for.

The problem's that while I can make the basic plot (p), I can't get the code for the finishing touches to work (there's a visual of the end product on the webpage). As far as I can tell some of the code is for older versions of ggplot2(), but I can't figure out what the updated equivalent is.

Any help would be much appreciated.

Starting point (df):

```<code>df1 <- data.frame(location=c("az","az","az","bi","bi","ca","ca","ca"),weather=c(1,2,3,2,3,1,2,3),wc=c(2,1,1,2,1,2,2,1))
</code>```

Current code:

```<code>p <- ggplot(df1, aes(location,weather)) + geom_tile(aes(fill = wc),colour = "white") +
 scale_fill_gradient(low = "white", high = "steelblue")

p + theme_grey(base_size = base_size) + labs(x = "", y = "") +
    scale_x_discrete(expand = c(0, 0)) + scale_y_discrete(expand = c(0, 0)) +
    opts(legend.position = "none", axis.ticks = theme_blank(), axis.text.x = theme_text(size = base_size * 0.8, angle = 330, hjust = 0, colour = "grey50"))
</code>```

答:
Here is an updated version:

```<code>base_size <- 9
ggplot(df1, aes(location,weather)) + geom_tile(aes(fill = wc),colour = "white") +
    scale_fill_gradient(low = "white", high = "steelblue") +
    theme_grey(base_size = base_size) + labs(x = "", y = "") +
    scale_x_discrete(expand = c(0, 0)) + scale_y_discrete(expand = c(0, 0)) +
    theme(legend.position = "none",
          axis.ticks = element_blank(),
          axis.text.x = element_text(size = base_size * 0.8,
                                      angle = 330,
                                      hjust = 0,
                                      colour = "grey50"))
</code>```

all arguments under opts should be inside theme

theme_text() is replaced with element_text()

theme_blank() is replaced with element_blank()

ContentLicense: CC BY-SA 3.0

Body:
I've got a data frame with three variables: location, weather, and wc.

I'd like to make a heatmap using  geom_tile in ggplot2(), so that weather is on the y axis, location on the x axis, and wc being the fill. I found some code on https://learnr.wordpress.com/2010/01/26/ggplot2-quick-heatmap-plotting/, producing exactly the kind of plot I'm looking for.

The problem's that while I can make the basic plot (p), I can't get the code for the finishing touches to work (there's a visual of the end product on the webpage). As far as I can tell some of the code is for older versions of ggplot2(), but I can't figure out what the updated equivalent is.

Any help would be much appreciated.

Starting point (df):

df1 <- data.frame(location=c("az","az","az","bi","bi","ca","ca","ca"),weather=c(1,2,3,2,3,1,2,3),wc=c(2,1,1,2,1,2,2,1))

Current code:

p <- ggplot(df1, aes(location,weather)) + geom_tile(aes(fill = wc),colour = "white") +
 scale_fill_gradient(low = "white", high = "steelblue")

p + theme_grey(base_size = base_size) + labs(x = "", y = "") +
    scale_x_discrete(expand = c(0, 0)) + scale_y_discrete(expand = c(0, 0)) +
    opts(legend.position = "none", axis.ticks = theme_blank(), axis.text.x = theme_text(size = base_size * 0.8, angle = 330, hjust = 0, colour = "grey50"))

Body:
Here is an updated version:

base_size <- 9
ggplot(df1, aes(location,weather)) + geom_tile(aes(fill = wc),colour = "white") +
    scale_fill_gradient(low = "white", high = "steelblue") +
    theme_grey(base_size = base_size) + labs(x = "", y = "") +
    scale_x_discrete(expand = c(0, 0)) + scale_y_discrete(expand = c(0, 0)) +
    theme(legend.position = "none",
          axis.ticks = element_blank(),
          axis.text.x = element_text(size = base_size * 0.8,
                                      angle = 330,
                                      hjust = 0,
                                      colour = "grey50"))

all arguments under opts should be inside theme

theme_text() is replaced with element_text()

theme_blank() is replaced with element_blank()


问:
JAVA sockets client to client communication
I was planning to create a chat messaging application wherein two or more clients can communicate but I am a little confused.

Does java can have a client to client communication using sockets?

Does the socket communication always needs a server?

Is it possible that one client will stand a server of the communication?

Do you have any tutorials for a client to client communication?

If the communication needs a server, how a can a client A see Client B's messages?

答: If you need simple approach you can try https://httprelay.io service. What you need is just http client and no external libraries.</p>


问:
Plotting exact Solution (error)
This code is to get a plot of an exact function, where the function is the array of y defined in fn1. the error is "have shapes {} and {}".format(x.shape, y.shape))

ValueError: x and y must have same first dimension, but have shapes (401,) and (2, 401)

```<code>def fn1( interval, N):
    x = numpy.linspace(interval[0], interval[1], N+1)
    y = numpy.array([numpy.exp(-1000*x),(1000/999)*(numpy.exp(-x)-numpy.exp(-1000*x))])
    return x, y

interval=numpy.array([0,0.1])
N=400

x,y=fn1(interval,N)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.semilogy(x, y[:,0], 'b+')
</code>```

答:
the error was that it should have been</p>

```<code>plt.semilogy(x, y[0,:], 'b+')
</code>```

Title: Plotting exact Solution (error)

Body:
This code is to get a plot of an exact function, where the function is the array of y defined in fn1. the error is "have shapes {} and {}".format(x.shape, y.shape))

ValueError: x and y must have same first dimension, but have shapes (401,) and (2, 401)

def fn1( interval, N):
    x = numpy.linspace(interval[0], interval[1], N+1)
    y = numpy.array([numpy.exp(-1000*x),(1000/999)*(numpy.exp(-x)-numpy.exp(-1000*x))])
    return x, y

interval=numpy.array([0,0.1])
N=400

x,y=fn1(interval,N)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.semilogy(x, y[:,0], 'b+')

Body:
the error was that it should have been

plt.semilogy(x, y[0,:], 'b+')


问:
Selection Sort Algorithm using small array
Ive been working on selection sort algorithms, just wanted to know the step by step method on working out using the selection sort algorithm.

Just wanted to know if the below is correct

```<code>Array: 6, 20, 12, 8
</code>```

1st phase: n=0  6, 20, 12, 8 (no swap)

2nd phase: n=1  6, 8, 12, 20

3rd phase: n=2  6, 8, 12, 20 (no swap)

答:
Yes You are right</p>

```<code>  arr[] = 6, 20, 12, 8

// Find the minimum element in arr[0...3]
// and place it at beginning
// 6 is minimum and at its place so no swap
 6, 20, 12, 8

// Find the minimum element in arr[1...3]
// and place it at beginning of arr[1...3]
// 8 is minimum and so swap it with index at 1
 6, 8, 12, 20

// Find the minimum element in arr[2...3]
// and place it at beginning of arr[2...3]
//Every thing is at place no swap
 6, 8, 12, 20
</code>```

Body:
Ive been working on selection sort algorithms, just wanted to know the step by step method on working out using the selection sort algorithm.

Just wanted to know if the below is correct

Array: 6, 20, 12, 8

1st phase: n=0  6, 20, 12, 8 (no swap)

2nd phase: n=1  6, 8, 12, 20

3rd phase: n=2  6, 8, 12, 20 (no swap)

Body:
Yes You are right

  arr[] = 6, 20, 12, 8

// Find the minimum element in arr[0...3]
// and place it at beginning
// 6 is minimum and at its place so no swap
 6, 20, 12, 8

// Find the minimum element in arr[1...3]
// and place it at beginning of arr[1...3]
// 8 is minimum and so swap it with index at 1
 6, 8, 12, 20

// Find the minimum element in arr[2...3]
// and place it at beginning of arr[2...3]
//Every thing is at place no swap
 6, 8, 12, 20


问:
How to make a div span 100% of the page even when scrolling to the right
This has probably been answered before somewhere, but I cant find a good solution. I want to create a header, which behaves like a div which is  position:absolute in the sense that it will stay at the top of the page when one scrolls down. Although, I would also like the user to be able to scroll right and left and have the header maintain its 100% width of the view port. Right now, with position absolute there becomes a white space to the right of the header as seen in the image. How can I create a header which maintains 100% width when scrolling right to left, but also stays at the top of the page when scrolling down using only css?

答:
Navbar: make it position:fixed

And width of your content as 300%
As shown in fiddle.

EDIT

By adding JQuery, I was able to get the desired output.

You are able to scroll the content, left and right keeping the navbar at it's place.

When you scroll vertical, navbar disappears. Just like a regular webpage.

$(window).scroll({
    previousTop: 0
  },
  function() {
    var currentTop = $(window).scrollTop();
    if (currentTop <= this.previousTop) {
      $(".header").show();
    } else {
      $(".header").hide();
    }
    this.previousTop = currentTop;
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  height: 700px;
}

h1 {
  margin: 0;
  position: relative;
  top: 20%;
}

.header {
  position: fixed;
  margin: 0;
  height: 30px;
  width: 100%;
  background-color: red;
}

.content {
  background-color: blue;
  height: 100%;
  width: 400%;
}</code>```

Scroll Right

Scroll Right

Scroll Right

```

Body:
Navbar: make it position:fixed

And width of your content as 300%
As shown in fiddle.

EDIT

By adding JQuery, I was able to get the desired output.

You are able to scroll the content, left and right keeping the navbar at it's place.

When you scroll vertical, navbar disappears. Just like a regular webpage.

$(window).scroll({
    previousTop: 0
  },
  function() {
    var currentTop = $(window).scrollTop();
    if (currentTop <= this.previousTop) {
      $(".header").show();
    } else {
      $(".header").hide();
    }
    this.previousTop = currentTop;
  });

body {
  margin: 0;
  height: 700px;
}

h1 {
  margin: 0;
  position: relative;
  top: 20%;
}

.header {
  position: fixed;
  margin: 0;
  height: 30px;
  width: 100%;
  background-color: red;
}

.content {
  background-color: blue;
  height: 100%;
  width: 400%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class='header'></div>
  <div class='content'>
    <h1 style="color:white">Scroll Right</h1>
    <h1 style="color:red; background-color:yellow; left:100%;">Scroll Right</h1>
    <h1 style="color:gree; left:200%;">Scroll Right</h1>

  </div>
</body>


问:
Create a web page to control a C# windows form application
I have developed a C# windows application with Visual Studio 2013. It runs on a server and communicates with some devices around the world through a Apache server(txt files which contains commands). Now I would need to create a web page(accessible via the internet) which allows my customers to log in and change some parameters which are in my windows application.What would be the best way to do it?

Thank you in advance for your help!

答:
Create a web page to save customer settings in database

Expose a webservice or Web API that can be called from the desktop application in a different thread to access the customer data from the web


问:
Download returning empty file
I'm building a node.js+express application in which the user will input some data, the generates a PDF with pdfkit and the file is sent to the user. I'm being able to generate the file successfully, the problem is that when I download the file generated, it's empty. I can't even open the PDF, the reader (Preview, native reader in macOS) says that the file is empty. I'm using the following code:

```<code>var express = require('express');
var router = express.Router();
var guid = require('guid');
var PDFDocument = require('pdfkit');
var fs = require('fs');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/criar', function(req, res, next) {
    var filename = guid.raw()+'.pdf';
    var doc = new PDFDocument();
    doc.pipe(fs.createWriteStream(filename));

    doc.font('fonts/UbuntuMono-R.ttf')
        .fontSize(25)
        .text('Some text with an embedded font!', 100, 100);

    doc.end();

    res.download(filename, 'rifas.pdf', function(err){
        if(!err){
            fs.unlink(filename);
        }
    })
});

module.exports = router;
</code>```

Do you have any idea on why my downloaded files are empty, while in the server they're being generated correctly?

Thanks!

答:
Do you really need the physical file? If not then you can stream directly to the client:</p>

```<code>var express = require('express');
var router = express.Router();
var PDFDocument = require('pdfkit');
var fs = require('fs');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/criar', function(req, res, next) {
    var doc = new PDFDocument();
    doc.pipe(res);

    doc.font('fonts/UbuntuMono-R.ttf')
        .fontSize(25)
        .text('Some text with an embedded font!', 100, 100);

    doc.end();

});

module.exports = router;
</code>```

Title: Download returning empty file

Body:
I'm building a node.js+express application in which the user will input some data, the generates a PDF with pdfkit and the file is sent to the user. I'm being able to generate the file successfully, the problem is that when I download the file generated, it's empty. I can't even open the PDF, the reader (Preview, native reader in macOS) says that the file is empty. I'm using the following code:

var express = require('express');
var router = express.Router();
var guid = require('guid');
var PDFDocument = require('pdfkit');
var fs = require('fs');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/criar', function(req, res, next) {
    var filename = guid.raw()+'.pdf';
    var doc = new PDFDocument();
    doc.pipe(fs.createWriteStream(filename));

    doc.font('fonts/UbuntuMono-R.ttf')
        .fontSize(25)
        .text('Some text with an embedded font!', 100, 100);

    doc.end();

    res.download(filename, 'rifas.pdf', function(err){
        if(!err){
            fs.unlink(filename);
        }
    })
});

module.exports = router;

Do you have any idea on why my downloaded files are empty, while in the server they're being generated correctly?

Thanks!

Body:
Do you really need the physical file? If not then you can stream directly to the client:

var express = require('express');
var router = express.Router();
var PDFDocument = require('pdfkit');
var fs = require('fs');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/criar', function(req, res, next) {
    var doc = new PDFDocument();
    doc.pipe(res);

    doc.font('fonts/UbuntuMono-R.ttf')
        .fontSize(25)
        .text('Some text with an embedded font!', 100, 100);

    doc.end();

});

module.exports = router;


问:
Bash - inside a "for" loop if a condition is met once or more - take action
I have this script :

```<code>for sha1 in $(git log origin/$current_branch..HEAD --format=format:%H);do
comment=$(git cat-file commit $sha1 | sed '1,/^$/d')
    if [[ $comment == *oops!* ]]; then touch oops ; else : ; fi ; done
    if [ -e oops ]; then
      rm -f oops
      return 0 #0=oops! string exists in comment
    else
      return 1 #1=oops! string doesn't exists in comment
    fi
}
</code>```

Which is working great for me,

In this script, I am checking if the string "oops!" is inside any of the sha1 commit messages and if that is the case I return 0 from this function.
What is bothering me is the fact that I create a temporary file called oops (using touch) and then delete it.

Is there a way to check inside for loop if a condition is met once or more, and if so -  do something (In my case return 0) without having to create a file.

The reason I need this is that I want my script not to be affected by any r/w permissions.

答:
Not sure I understood your problem but why don't you just return when your condition is met?

```<code>for sha1 in $(git log origin/$current_branch..HEAD --format=format:%H);do
    comment=$(git cat-file commit $sha1 | sed '1,/^$/d')
    if [[ $comment == *oops!* ]]; then
      return 0 #0=oops! string exists in comment
    fi
done
return 1 #1=oops! string doesn't exists in comment
</code>```

This would return 0 if the condition is met else 1...

Body:
I have this script :

for sha1 in $(git log origin/$current_branch..HEAD --format=format:%H);do
comment=$(git cat-file commit $sha1 | sed '1,/^$/d')
    if [[ $comment == *oops!* ]]; then touch oops ; else : ; fi ; done
    if [ -e oops ]; then
      rm -f oops
      return 0 #0=oops! string exists in comment
    else
      return 1 #1=oops! string doesn't exists in comment
    fi
}

Which is working great for me,

In this script, I am checking if the string "oops!" is inside any of the sha1 commit messages and if that is the case I return 0 from this function.
What is bothering me is the fact that I create a temporary file called oops (using touch) and then delete it.

Is there a way to check inside for loop if a condition is met once or more, and if so -  do something (In my case return 0) without having to create a file.

The reason I need this is that I want my script not to be affected by any r/w permissions.

Body:
Not sure I understood your problem but why don't you just return when your condition is met?

for sha1 in $(git log origin/$current_branch..HEAD --format=format:%H);do
    comment=$(git cat-file commit $sha1 | sed '1,/^$/d')
    if [[ $comment == *oops!* ]]; then
      return 0 #0=oops! string exists in comment
    fi
done
return 1 #1=oops! string doesn't exists in comment

This would return 0 if the condition is met else 1...


问:
hive, get the data location using an one-liner
I wonder if there is a way to get the data location from hive using a one-liner.  Something like </p>

```<code>select d.location from ( describe formatted table_name partition ( .. ) ) as d;
</code>```

<p>My current solution is to get the full output and then parse it. </p>

答:
Unlike traditional RDBMS, Hive metadata is stored in a separate database. In most cases it is in MySQL or Postgres. The metastore database details can be found in hive-site.conf. If you have access to the metastore database, you can run SELECT on table TBLS to get the details about the tables and COLUMNS_V2 to get the details about columns etc..

If you do not have access to the metastore, the only option is to describe each table to get the details. If you have a lot of databases and tables, you could write a shell script to get the list of tables using "show tables" and loop around the tables.

Body:
I wonder if there is a way to get the data location from hive using a one-liner.  Something like

select d.location from ( describe formatted table_name partition ( .. ) ) as d;

My current solution is to get the full output and then parse it.


问:
Java 8 filter a stream to replace SQL IN (...) clause
Is there any way to achieve the same result with a collection like with SQL IN clause ? For example, there a list of objects and I have to choose those with ids in (2, 17, 31, ...) what is equal to SQL</p>

```<code>SELECT *
FROM table_name
WHERE column_name IN (value1, value2, ...);
</code>```

答:
I figured out how to do that:

```<code>private static void selectByRange(List<Integer> range) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 23, 101);
        Stream<Integer> filterStream = numbers.stream().filter((Integer number) -> range.contains(number));
        List<Integer> collected = filterStream.collect(Collectors.toList());
        System.out.println(collected.toString());

    }
</code>```

You pass in a list of Integers and get the filtered list:

```<code>selectByRange(Arrays.asList(5, 3, 4, 20, 100)); #=> [3, 4, 5, 20]
</code>```

Body:
Is there any way to achieve the same result with a collection like with SQL IN clause ? For example, there a list of objects and I have to choose those with ids in (2, 17, 31, ...) what is equal to SQL

SELECT *
FROM table_name
WHERE column_name IN (value1, value2, ...);

Body:
I figured out how to do that:

private static void selectByRange(List<Integer> range) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 23, 101);
        Stream<Integer> filterStream = numbers.stream().filter((Integer number) -> range.contains(number));
        List<Integer> collected = filterStream.collect(Collectors.toList());
        System.out.println(collected.toString());

    }

You pass in a list of Integers and get the filtered list:

selectByRange(Arrays.asList(5, 3, 4, 20, 100)); #=> [3, 4, 5, 20]


问:
Kotlin: how to get searchView submit
I have a SearchView:

<SearchView
    android:id="@+id/searchBar"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:visibility="visible"/>
```

<p>I want to add a custom action when the submit button is pressed.</p>

<p>This is what I have so far:</p>

<pre class="lang-kotlin prettyprint-override"><code>searchBar.setOnSearchClickListener {
  //do some stuff
}
</code>```

All the information I found is old and not in kotlin.

How can I get trigger an action when the search icon on the keyboard is tapped?

答:
Try doing this:

```<code>override fun onCreateOptionsMenu(menu: Menu): Boolean {
    menuInflater.inflate(R.menu.main, menu)

    val searchItem = menu.findItem(R.id.search_city)
    searchView = searchItem.actionView as SearchView
    searchView.setQueryHint("Search View Hint")

    searchView.setOnQueryTextListener(object : OnQueryTextListener {

        override fun onQueryTextChange(newText: String): Boolean {
            return false
        }

        override fun onQueryTextSubmit(query: String): Boolean {
            // task HERE
            return false
        }

    })

    return true
}
</code>```

Response link: Listen to keyboard event

ContentLicense: CC BY-SA 4.0

Title: Kotlin: how to get searchView submit

Body:
I have a SearchView:

<SearchView
    android:id="@+id/searchBar"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:visibility="visible"/>

I want to add a custom action when the submit button is pressed.

This is what I have so far:

searchBar.setOnSearchClickListener {
  //do some stuff
}

All the information I found is old and not in kotlin.

How can I get trigger an action when the search icon on the keyboard is tapped?

Body:
Try doing this:

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    menuInflater.inflate(R.menu.main, menu)

    val searchItem = menu.findItem(R.id.search_city)
    searchView = searchItem.actionView as SearchView
    searchView.setQueryHint("Search View Hint")

    searchView.setOnQueryTextListener(object : OnQueryTextListener {

        override fun onQueryTextChange(newText: String): Boolean {
            return false
        }

        override fun onQueryTextSubmit(query: String): Boolean {
            // task HERE
            return false
        }

    })

    return true
}

Response link: Listen to keyboard event


问:
How to use apps script or add-ons in Google Forms
I am trying to create some Apps Script (or add-ons) in a Google Form but the documentation does not match the application.  For example, this says to enable add-ons in the menu but that options does not exist. Other documentation mentions the script editor, but that seems to be missing also.  Is there some other way to enable this?

Edit: In the "three dots" menu in a Form I see preview, settings, undo, star, make a copy, move to folder, move to trash, get pre-filled link, print, add collaborators, help center, report a problem, and preferences.

答:
It's very likely that you are using a G Suite account from an organization that has not enabled the use of add-ons. Ask your G Suite administrator about this.

Reference

Enable add-ons in Docs editors


问:
FileSystemWatcher inside Docker does not notice changes to local directory
My program inside a docker container uses FileSystemWatcher to monitor a local folder. I mounted the directory with:

docker run -v /c/Users/Support/Desktop/inbox:/Users/Support/Desktop/inbox -v /c/Users/Support/Desktop/outbox:/Users/Support/Desktop/outbox -it --name workbeanRun workbean

I used Docker Exec to look into the container while it was running. It can see the inbox and outbox directories along with any files that are in it. However, when I throw a new file into the inbox, the FileSystemWatcher event does not fire. There's nothing wrong with the code because if I don't use a docker container, it runs fine.

Is there anything else I need to do in mounting the directores? Or is FileSystemWatcher even possible inside a container?

Okay, as requested, here's the program:

```<code>using System;
using System.IO;

namespace workbean
{
    class Program
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        static string sourceDir = "/Users/Support/Desktop/inbox";
        static string destDir = "/Users/Support/Desktop/outbox";

        static void Main(string[] args)
        {
            Console.WriteLine("Testing...");

            Program p = new Program();

            while (true) { }
        }

        public Program()
        {
            watcher.Path = sourceDir;
            watcher.Filter = "*.*";
            watcher.Created += new FileSystemEventHandler(OnCreated);
            watcher.EnableRaisingEvents = true;

        }

        static void OnCreated(object source, FileSystemEventArgs e)
        {

            string[] files = Directory.GetFiles(sourceDir);
            foreach (var item in files)
            {
                string destDir2 = destDir + "/" + Path.GetFileName(item);
                File.Move(item, destDir2);
            }

        }

    }
}
</code>```

答:
It appears that this is what is happening:

The inbox folder on my local drive is tied to the inbox folder in the container. If you add files to one, they show up in the other.

However, the FileSystemWatcher is only monitoring the inbox in the container. If I add a file to the inbox in the container, then FileSystemWatcher fires an event.

But when adding a file to the local inbox, nothing happens, because FileSystemWatcher is not monitoring that one, even though the two folders are tied to each other.

Body:
My program inside a docker container uses FileSystemWatcher to monitor a local folder. I mounted the directory with:

docker run -v /c/Users/Support/Desktop/inbox:/Users/Support/Desktop/inbox -v /c/Users/Support/Desktop/outbox:/Users/Support/Desktop/outbox -it --name workbeanRun workbean

I used Docker Exec to look into the container while it was running. It can see the inbox and outbox directories along with any files that are in it. However, when I throw a new file into the inbox, the FileSystemWatcher event does not fire. There's nothing wrong with the code because if I don't use a docker container, it runs fine.

Is there anything else I need to do in mounting the directores? Or is FileSystemWatcher even possible inside a container?

Okay, as requested, here's the program:

using System;
using System.IO;

namespace workbean
{
    class Program
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        static string sourceDir = "/Users/Support/Desktop/inbox";
        static string destDir = "/Users/Support/Desktop/outbox";

        static void Main(string[] args)
        {
            Console.WriteLine("Testing...");

            Program p = new Program();

            while (true) { }
        }

        public Program()
        {
            watcher.Path = sourceDir;
            watcher.Filter = "*.*";
            watcher.Created += new FileSystemEventHandler(OnCreated);
            watcher.EnableRaisingEvents = true;

        }

        static void OnCreated(object source, FileSystemEventArgs e)
        {

            string[] files = Directory.GetFiles(sourceDir);
            foreach (var item in files)
            {
                string destDir2 = destDir + "/" + Path.GetFileName(item);
                File.Move(item, destDir2);
            }

        }

    }
}


问:
How to pass parameter into SQL file from UNIX script?
I'm looking to pass in a parameter into a SQL file from my UNIX script. Unfortunately having problems with it.

Please see UNIX script below:

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

# Functions
_usage() {
SCRIPT_NAME=XXX
    -eq 1 -o "$1" = "" -o "$1" = help -o "$1" = Help -o "$1" = HELP ]; then
    echo "Usage: $SCRIPT_NAME [ cCode ]"
    echo " - For example : $SCRIPT_NAME GH\n"
    exit 1
fi
}

_initialise() {
cCode=$1
echo $cCode
}

# Set Variables
_usage $@
_initialise $1

# Main Processing
sql $DBNAME < test.sql $cCode > $PVNUM_LOGFILE
RETCODE=$?
# Check for errors within log file
if [[ $RETCODE != 0 ]] || grep 'E_' $PVNUM_LOGFILE
    then
    echo "Error - 50 - running test.sql. Please see $PVNUM_LOGFILE"
    exit 50
fi
</code>```

Please see SQL script (test.sql):

```<code>SELECT DISTINCT v1.*
FROM data_latest v1
JOIN temp_table t
ON v1.number = t.id
WHERE v1.code = '&1'
</code>```

The error I am receiving when running my UNIX script is:

```<code>INGRES TERMINAL MONITOR Copyright 2008 Ingres Corporation
E_US0022 Either the flag format or one of the flags is incorrect,
    or the parameters are not in proper order.
</code>```

Anyone have any idea what I'm doing wrong?

Thanks!

答:
NOTE: While I don't work with the sql command, I do routinely pass UNIX parameters into SQL template/script files when using the isql command line tool, so fwiw ...

The first thing you'll want to do is replace the &1 string with the value in the cCode variable; one typical method is to use sed to do a global search and replace of &1 with ${cCode} , eg:

```<code>$ cCode=XYZ
$ sed "s/\&1/${cCode}/g" test.sql

SELECT DISTINCT v1.*
FROM data_latest v1
JOIN temp_table t
ON v1.number = t.id
WHERE v1.code = 'XYZ'    <=== &1 replaced with XYZ
</code>```

NOTE: You'll need to wrap the sed code in double quotes so that the value of the cCode variable can be referenced.

Now, to get this passed into sql there are a couple options ... capture the sed output to a new file and submit that file to sql or ... [and I'm guessing this is doable with sql], pipe the sed output into sql, eg:

```<code>sed "s/\&1/${cCode}/g" test.sql | sql $DBNAME > $PVNUM_LOGFILE
</code>```

Body:
I'm looking to pass in a parameter into a SQL file from my UNIX script. Unfortunately having problems with it.

Please see UNIX script below:

#!/bin/ksh
############

# Functions
_usage() {
SCRIPT_NAME=XXX
    -eq 1 -o "$1" = "" -o "$1" = help -o "$1" = Help -o "$1" = HELP ]; then
    echo "Usage: $SCRIPT_NAME [ cCode ]"
    echo " - For example : $SCRIPT_NAME GH\n"
    exit 1
fi
}

_initialise() {
cCode=$1
echo $cCode
}

# Set Variables
_usage $@
_initialise $1

# Main Processing
sql $DBNAME < test.sql $cCode > $PVNUM_LOGFILE
RETCODE=$?
# Check for errors within log file
if [[ $RETCODE != 0 ]] || grep 'E_' $PVNUM_LOGFILE
    then
    echo "Error - 50 - running test.sql. Please see $PVNUM_LOGFILE"
    exit 50
fi

Please see SQL script (test.sql):

SELECT DISTINCT v1.*
FROM data_latest v1
JOIN temp_table t
ON v1.number = t.id
WHERE v1.code = '&1'

The error I am receiving when running my UNIX script is:

INGRES TERMINAL MONITOR Copyright 2008 Ingres Corporation
E_US0022 Either the flag format or one of the flags is incorrect,
    or the parameters are not in proper order.

Anyone have any idea what I'm doing wrong?

Thanks!

Body:
NOTE: While I don't work with the sql command, I do routinely pass UNIX parameters into SQL template/script files when using the isql command line tool, so fwiw ...

The first thing you'll want to do is replace the &1 string with the value in the cCode variable; one typical method is to use sed to do a global search and replace of &1 with ${cCode} , eg:

$ cCode=XYZ
$ sed "s/\&1/${cCode}/g" test.sql

SELECT DISTINCT v1.*
FROM data_latest v1
JOIN temp_table t
ON v1.number = t.id
WHERE v1.code = 'XYZ'    <=== &1 replaced with XYZ

NOTE: You'll need to wrap the sed code in double quotes so that the value of the cCode variable can be referenced.

Now, to get this passed into sql there are a couple options ... capture the sed output to a new file and submit that file to sql or ... [and I'm guessing this is doable with sql], pipe the sed output into sql, eg:

sed "s/\&1/${cCode}/g" test.sql | sql $DBNAME > $PVNUM_LOGFILE


问:
Openshift online v3 - Timeout when reading response headers from daemon process
I created an python api on openshift online with python image. If you request all the data, it takes more than 30 seconds to respond. The server gives a 504  gateway timeout http response. How do you configure the length a response can take? > I created an annotation on the route, this seems to set proxy timeout.

```<code>haproxy.router.openshift.io/timeout: 600s
</code>```

Problem remains, I now got logging. It looks like the message comes from mod_wsgi.

I want to try alter the configuration of the httpd (mod_wsgi-express process) from request-timeout 60 to request-timeout 600. Where doe you configure this. I am using base image https://github.com/sclorg/s2i-python-container/tree/master/2.7

Logging:

```<code>Timeout when reading response headers from daemon process  'localhost:8080':/tmp/mod_wsgi-localhost:8080:1000430000/htdocs
</code>```

Does someone know how to fix this error on openshift online

答:
Next to alter timeout of haproxy of the route of my app

```<code>haproxy.router.openshift.io/timeout: 600s
</code>```

I altered the request-timeout and socket-timeout in app.sh of my python application. So the mod_wsgi-express server is configured with a higher timeout

```<code>ARGS="$ARGS --request-timeout 600"
ARGS="$ARGS --socket-timeout 600"
</code>```

My application now wait 10 minutes before cancelling a request

Body:
I created an python api on openshift online with python image. If you request all the data, it takes more than 30 seconds to respond. The server gives a 504  gateway timeout http response. How do you configure the length a response can take? > I created an annotation on the route, this seems to set proxy timeout.

haproxy.router.openshift.io/timeout: 600s

Problem remains, I now got logging. It looks like the message comes from mod_wsgi.

I want to try alter the configuration of the httpd (mod_wsgi-express process) from request-timeout 60 to request-timeout 600. Where doe you configure this. I am using base image https://github.com/sclorg/s2i-python-container/tree/master/2.7

Logging:

Timeout when reading response headers from daemon process  'localhost:8080':/tmp/mod_wsgi-localhost:8080:1000430000/htdocs

Does someone know how to fix this error on openshift online

Body:
Next to alter timeout of haproxy of the route of my app

haproxy.router.openshift.io/timeout: 600s

I altered the request-timeout and socket-timeout in app.sh of my python application. So the mod_wsgi-express server is configured with a higher timeout

ARGS="$ARGS --request-timeout 600"
ARGS="$ARGS --socket-timeout 600"

My application now wait 10 minutes before cancelling a request


问:
extract name from specific occurence of a pattern in a large file
I have a FASTA file which is basically a text file for depicting biological sequence data (https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=BlastHelp) having more than 10,000 FASTA sequences (starting with >). The beginning of the file looks like:

```<code>>Gene A
GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAATTCCAGAAGTTGGACAGACATATATAGACAGCACATATATTA
TCTTTATTTTTTTATGTATGATAACATTAAATATAACGTTCAACAATT
>Gene B
GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAATTCCAGAAGTTGGACAGACATATATAGACAGCACATATATTA
TCTTTATTTTTTTATGTATGATAACATTAAATATAACGTTCAACAATTACACCGTTAGCAGTGTGAGCAAAAACGATTAA
AAAGTAAATATTATAAAAGCCCTC
>Gene C
AACAACAAATTGCCATCTACCCGTTTGAATCCTGTAATAATAACTTGCCCAGATTTGCTGCAGCATACTCCTAGAGTTGG
GCTGGGTGGCCCACACAAGCGATAATAACATTTAACAATTGTTTGATATATGTACTTTTTTTTAAGTTTTTTTCTCCTCG
TACTTGCCTTCCAAAAACTCGTTAGCTTTGTACACATACGCCTTTAATTAAAATACTGATAGATGCGTACCACTTACGTC
ATTAGAAAAAGTCACCAAAAGGAAAAATATGGACGACACAAGAACGAGGAGATCTAAGCCACTCGTAGACCACTAAGCAC
AAAATACCCGAAAAATATAACTGATATGATTGCCAACTACCCTGCGACTATGTAAACCCAACCTTCCCCCCTCCTTTACC
CTCTTATTCAAATCGACGCGTGTGTAGAAGATACACTTATTATATTTTTTTTCTGAGATACAATTATAAACACAAAAACG
ACTTTTAACTATATATTAAATAAAAACAAAAGGAAAAACATAATAATTT
>Gene D
AACAACAAATTGCCATCTACCCGTTTGAATCCTGTAATAATAACTTGCCCAGATTTGCTGCAGCATACTCCTAGAGTTGG
GCTGGGTGGCCCACACAAGCGATAATAACATTTAACAATTGTTTGATATATGTACTTTTTTTTAAGTTTTTTTCTCCTCG
TACTTGCCTTCCAAAAACTCGTTAGCTTTGTACACATACGCCTTTAATTAAAATACTGATAGATGCGTACCACTTACGTC
ATTAGAAAAAGTCACCAAAAGGAAAAATATGGACGACACAAGAACGAGGAGATCTAAGCCACTCGTAGACCACTAAGCAC
AAAATACCCGAAAAATATAACTGATATGATTGCCAACTACCCTGCGACTATGTAAACCCAACCTTCCCCCCTCCTTTACC
CTCTTATTCAAATCGACGCGTGTGTAGAAGATACACTTATTATATTTTTTTTCTGAGATACAATTATAAACACAAAAACG
ACTTTTAACTATATATTAAATAAAAACAAAAGGAAAAACATAATAATTT
</code>```

and so on for approximately 10,000 genes.
I want to:

find which of the genes contain a specific pattern (CTTTGTA)

how many times is this pattern present in that gene?

export the list of gene names containing the pattern with the frequency of the pattern.

Any solution in Bash or Python (or R) is appreciated.

P.S. What I have tried thus far but didn't work: extracting genes with their sequences into separate files and then grep for the pattern in separate files. I could, however, not generate these separate files. I used

```<code>grep '^>' file.txt > new_file.txt
</code>```

but the output I get is a single file containing all the gene names only.

答:
Here a solution with R using stringi package. Since there is no single text file or similar to be accessed as reproducible example I have used used cat()and readlines() to read a temporary representing a copy of the lines you provided. Please also check the timing benchmark, might be of interest for large files.

```<code>library(stringi)

cat(">Gene A
GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAATTCCAGAAGTTGGACAGACATATATAGACAGCACATATATTA
    TCTTTATTTTTTTATGTATGATAACATTAAATATAACGTTCAACAATT
    >Gene B
    GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAATTCCAGAAGTTGGACAGACATATATAGACAGCACATATATTA
    TCTTTATTTTTTTATGTATGATAACATTAAATATAACGTTCAACAATTACACCGTTAGCAGTGTGAGCAAAAACGATTAA
    AAAGTAAATATTATAAAAGCCCTC
    >Gene C
    AACAACAAATTGCCATCTACCCGTTTGAATCCTGTAATAATAACTTGCCCAGATTTGCTGCAGCATACTCCTAGAGTTGG
    GCTGGGTGGCCCACACAAGCGATAATAACATTTAACAATTGTTTGATATATGTACTTTTTTTTAAGTTTTTTTCTCCTCG
    TACTTGCCTTCCAAAAACTCGTTAGCTTTGTACACATACGCCTTTAATTAAAATACTGATAGATGCGTACCACTTACGTC
    ATTAGAAAAAGTCACCAAAAGGAAAAATATGGACGACACAAGAACGAGGAGATCTAAGCCACTCGTAGACCACTAAGCAC
    AAAATACCCGAAAAATATAACTGATATGATTGCCAACTACCCTGCGACTATGTAAACCCAACCTTCCCCCCTCCTTTACC
    CTCTTATTCAAATCGACGCGTGTGTAGAAGATACACTTATTATATTTTTTTTCTGAGATACAATTATAAACACAAAAACG
    ACTTTTAACTATATATTAAATAAAAACAAAAGGAAAAACATAATAATTT
    >Gene D
    AACAACAAATTGCCATCTACCCGTTTGAATCCTGTAATAATAACTTGCCCAGATTTGCTGCAGCATACTCCTAGAGTTGG
    GCTGGGTGGCCCACACAAGCGATAATAACATTTAACAATTGTTTGATATATGTACTTTTTTTTAAGTTTTTTTCTCCTCG
    TACTTGCCTTCCAAAAACTCGTTAGCTTTGTACACATACGCCTTTAATTAAAATACTGATAGATGCGTACCACTTACGTC
    ATTAGAAAAAGTCACCAAAAGGAAAAATATGGACGACACAAGAACGAGGAGATCTAAGCCACTCGTAGACCACTAAGCAC
    AAAATACCCGAAAAATATAACTGATATGATTGCCAACTACCCTGCGACTATGTAAACCCAACCTTCCCCCCTCCTTTACC
    CTCTTATTCAAATCGACGCGTGTGTAGAAGATACACTTATTATATTTTTTTTCTGAGATACAATTATAAACACAAAAACG
    ACTTTTAACTATATATTAAATAAAAACAAAAGGAAAAACATAATAATTT
", file = "tempfile.txt")

genes <- readLines("tempfile.txt", n=-1)
unlink("tempfile.txt")

genes <- unlist(stri_split_fixed(paste(genes, collapse = " "), ">"))
genes <- genes[ genes != ""]

genenames <- unlist(stri_extract_all_regex(genes, "Gene \\w+"))
genes <- stri_replace_all_fixed(genes, genenames, "")
names(genes) <- genenames

genes <- gsub("\\s+", "", genes, perl = T)

gene_pattern_freq <- function(str, patterns) {

  res <- sapply(patterns, function(p) {

    stringi::stri_count_fixed(str, p)

  }, USE.NAMES = T)

  rownames(res) <- names(str)

  return(res)
}

searchpatterns <- c("AA", "GT", "GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAA")
result <- gene_pattern_freq(genes, searchpatterns)
result
#        AA GT GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAA
# Gene A 14  6                                      1
# Gene B 21 10                                      1
# Gene C 52 18                                      0
# Gene D 52 18                                      0

library(microbenchmark)
microbenchmark(gene_pattern_freq(genes, searchpatterns))
# Unit: microseconds
# expr                                      min     lq    mean   median   uq     max   neval
# gene_pattern_freq(genes, searchpatterns) 68.687 77.371 123.438 78.161 79.345 4479.19   100

#export
write.csv(result, file = "../mypath/gene_pattern_freq_result.csv" )
</code>```

Body:
I have a FASTA file which is basically a text file for depicting biological sequence data (https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=BlastHelp) having more than 10,000 FASTA sequences (starting with >). The beginning of the file looks like:

>Gene A
GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAATTCCAGAAGTTGGACAGACATATATAGACAGCACATATATTA
TCTTTATTTTTTTATGTATGATAACATTAAATATAACGTTCAACAATT
>Gene B
GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAATTCCAGAAGTTGGACAGACATATATAGACAGCACATATATTA
TCTTTATTTTTTTATGTATGATAACATTAAATATAACGTTCAACAATTACACCGTTAGCAGTGTGAGCAAAAACGATTAA
AAAGTAAATATTATAAAAGCCCTC
>Gene C
AACAACAAATTGCCATCTACCCGTTTGAATCCTGTAATAATAACTTGCCCAGATTTGCTGCAGCATACTCCTAGAGTTGG
GCTGGGTGGCCCACACAAGCGATAATAACATTTAACAATTGTTTGATATATGTACTTTTTTTTAAGTTTTTTTCTCCTCG
TACTTGCCTTCCAAAAACTCGTTAGCTTTGTACACATACGCCTTTAATTAAAATACTGATAGATGCGTACCACTTACGTC
ATTAGAAAAAGTCACCAAAAGGAAAAATATGGACGACACAAGAACGAGGAGATCTAAGCCACTCGTAGACCACTAAGCAC
AAAATACCCGAAAAATATAACTGATATGATTGCCAACTACCCTGCGACTATGTAAACCCAACCTTCCCCCCTCCTTTACC
CTCTTATTCAAATCGACGCGTGTGTAGAAGATACACTTATTATATTTTTTTTCTGAGATACAATTATAAACACAAAAACG
ACTTTTAACTATATATTAAATAAAAACAAAAGGAAAAACATAATAATTT
>Gene D
AACAACAAATTGCCATCTACCCGTTTGAATCCTGTAATAATAACTTGCCCAGATTTGCTGCAGCATACTCCTAGAGTTGG
GCTGGGTGGCCCACACAAGCGATAATAACATTTAACAATTGTTTGATATATGTACTTTTTTTTAAGTTTTTTTCTCCTCG
TACTTGCCTTCCAAAAACTCGTTAGCTTTGTACACATACGCCTTTAATTAAAATACTGATAGATGCGTACCACTTACGTC
ATTAGAAAAAGTCACCAAAAGGAAAAATATGGACGACACAAGAACGAGGAGATCTAAGCCACTCGTAGACCACTAAGCAC
AAAATACCCGAAAAATATAACTGATATGATTGCCAACTACCCTGCGACTATGTAAACCCAACCTTCCCCCCTCCTTTACC
CTCTTATTCAAATCGACGCGTGTGTAGAAGATACACTTATTATATTTTTTTTCTGAGATACAATTATAAACACAAAAACG
ACTTTTAACTATATATTAAATAAAAACAAAAGGAAAAACATAATAATTT

and so on for approximately 10,000 genes.
I want to:

find which of the genes contain a specific pattern (CTTTGTA)

how many times is this pattern present in that gene?

export the list of gene names containing the pattern with the frequency of the pattern.

Any solution in Bash or Python (or R) is appreciated.

P.S. What I have tried thus far but didn't work: extracting genes with their sequences into separate files and then grep for the pattern in separate files. I could, however, not generate these separate files. I used

grep '^>' file.txt > new_file.txt

but the output I get is a single file containing all the gene names only.

Body:
Here a solution with R using stringi package. Since there is no single text file or similar to be accessed as reproducible example I have used used cat()and readlines() to read a temporary representing a copy of the lines you provided. Please also check the timing benchmark, might be of interest for large files.

library(stringi)

cat(">Gene A
GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAATTCCAGAAGTTGGACAGACATATATAGACAGCACATATATTA
    TCTTTATTTTTTTATGTATGATAACATTAAATATAACGTTCAACAATT
    >Gene B
    GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAATTCCAGAAGTTGGACAGACATATATAGACAGCACATATATTA
    TCTTTATTTTTTTATGTATGATAACATTAAATATAACGTTCAACAATTACACCGTTAGCAGTGTGAGCAAAAACGATTAA
    AAAGTAAATATTATAAAAGCCCTC
    >Gene C
    AACAACAAATTGCCATCTACCCGTTTGAATCCTGTAATAATAACTTGCCCAGATTTGCTGCAGCATACTCCTAGAGTTGG
    GCTGGGTGGCCCACACAAGCGATAATAACATTTAACAATTGTTTGATATATGTACTTTTTTTTAAGTTTTTTTCTCCTCG
    TACTTGCCTTCCAAAAACTCGTTAGCTTTGTACACATACGCCTTTAATTAAAATACTGATAGATGCGTACCACTTACGTC
    ATTAGAAAAAGTCACCAAAAGGAAAAATATGGACGACACAAGAACGAGGAGATCTAAGCCACTCGTAGACCACTAAGCAC
    AAAATACCCGAAAAATATAACTGATATGATTGCCAACTACCCTGCGACTATGTAAACCCAACCTTCCCCCCTCCTTTACC
    CTCTTATTCAAATCGACGCGTGTGTAGAAGATACACTTATTATATTTTTTTTCTGAGATACAATTATAAACACAAAAACG
    ACTTTTAACTATATATTAAATAAAAACAAAAGGAAAAACATAATAATTT
    >Gene D
    AACAACAAATTGCCATCTACCCGTTTGAATCCTGTAATAATAACTTGCCCAGATTTGCTGCAGCATACTCCTAGAGTTGG
    GCTGGGTGGCCCACACAAGCGATAATAACATTTAACAATTGTTTGATATATGTACTTTTTTTTAAGTTTTTTTCTCCTCG
    TACTTGCCTTCCAAAAACTCGTTAGCTTTGTACACATACGCCTTTAATTAAAATACTGATAGATGCGTACCACTTACGTC
    ATTAGAAAAAGTCACCAAAAGGAAAAATATGGACGACACAAGAACGAGGAGATCTAAGCCACTCGTAGACCACTAAGCAC
    AAAATACCCGAAAAATATAACTGATATGATTGCCAACTACCCTGCGACTATGTAAACCCAACCTTCCCCCCTCCTTTACC
    CTCTTATTCAAATCGACGCGTGTGTAGAAGATACACTTATTATATTTTTTTTCTGAGATACAATTATAAACACAAAAACG
    ACTTTTAACTATATATTAAATAAAAACAAAAGGAAAAACATAATAATTT
", file = "tempfile.txt")

genes <- readLines("tempfile.txt", n=-1)
unlink("tempfile.txt")

genes <- unlist(stri_split_fixed(paste(genes, collapse = " "), ">"))
genes <- genes[ genes != ""]

genenames <- unlist(stri_extract_all_regex(genes, "Gene \\w+"))
genes <- stri_replace_all_fixed(genes, genenames, "")
names(genes) <- genenames

genes <- gsub("\\s+", "", genes, perl = T)

gene_pattern_freq <- function(str, patterns) {

  res <- sapply(patterns, function(p) {

    stringi::stri_count_fixed(str, p)

  }, USE.NAMES = T)

  rownames(res) <- names(str)

  return(res)
}

searchpatterns <- c("AA", "GT", "GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAA")
result <- gene_pattern_freq(genes, searchpatterns)
result
#        AA GT GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAA
# Gene A 14  6                                      1
# Gene B 21 10                                      1
# Gene C 52 18                                      0
# Gene D 52 18                                      0

library(microbenchmark)
microbenchmark(gene_pattern_freq(genes, searchpatterns))
# Unit: microseconds
# expr                                      min     lq    mean   median   uq     max   neval
# gene_pattern_freq(genes, searchpatterns) 68.687 77.371 123.438 78.161 79.345 4479.19   100

#export
write.csv(result, file = "../mypath/gene_pattern_freq_result.csv" )


问:
TPL Complete vs Completion
I need to import customer related data from legacy DB and perform several transformations during the process. This means a single entry needs to perform additional "events" (synchronize products, create invoices, etc.).

My initial solution was a simple parallel approach.
It works okay, but sometimes it has issues. If the currently processed customers need to wait for the same type of events, their processing queues might got stuck and eventually time out, causing every underlying events to fail too (they depend on the one which failed). It doesn't happen all the time, yet it's annoying.

So I got another idea, work in batches. I mean not only limiting the number of customers being processed at the same time, but also the number of the events which are broadcasted to the queues. While searching around for ideas, I found this answer, which points to the TPL DataFlow.

I made a skeleton to get familiar with it. I set up a simple pipeline, but I'm a bit confused about the usage of Complete() and awaiting Completion().

The steps are the following

Make a list of numbers (the ids of the customers to be imported) - this is outside the import logic, it just there to be able to trigger the rest of the logic

Create a BatchBlock (to be able to limit the number of customers to be processed at the same time)

Create a single MyClass1 item based on the id (TransformBlock<int, MyClass1>)

Perform some logic and generate a collection of MyClass2 (TransformManyBlock<MyClass1, MyClass2>) - as example, sleep for 1 second

Perform some logic on every item of the collection (ActionBlock<MyClass2>) - as example, sleep for 1 second

Here's the full code:

```<code>public static class Program
{
    private static void Main(string[] args)
    {
        var batchBlock = new BatchBlock<int>(2);
        for (var i = 1; i < 10; i++)
        {
            batchBlock.Post(i);
        }

        batchBlock.Complete();
        while (batchBlock.TryReceive(null, out var ids))
        {
            var transformBlock = new TransformBlock<int, MyClass1>(delegate (int id)
            {
                Console.WriteLine($"TransformBlock(id: {id})");
                return new MyClass1(id, "Star Wars");
            });
            var transformManyBlock = new TransformManyBlock<MyClass1, MyClass2>(delegate (MyClass1 myClass1)
            {
                Console.WriteLine($"TransformManyBlock(myClass1: {myClass1.Id}|{myClass1.Value})");
                Thread.Sleep(1000);
                return GetMyClass22Values(myClass1);
            });

            var actionBlock = new ActionBlock<MyClass2>(delegate (MyClass2 myClass2)
            {
                Console.WriteLine($"ActionBlock(myClass2: {myClass2.Id}|{myClass2.Value})");
                Thread.Sleep(1000);
            });
            transformBlock.LinkTo(transformManyBlock);
            transformManyBlock.LinkTo(actionBlock);
            foreach (var id in ids)
            {
                transformBlock.Post(id);
            }

            // this is the point when I'm not 100% sure

            //transformBlock.Complete();
            //transformManyBlock.Complete();
            //transformManyBlock.Completion.Wait();
            actionBlock.Complete();
            actionBlock.Completion.Wait();
        }

        Console.WriteLine();
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }

    private static IEnumerable<MyClass2> GetMyClass22Values(MyClass1 myClass1)
    {
        return new List<MyClass2>
               {
                   new MyClass2(1, myClass1.Id+ " did this"),
                   new MyClass2(2, myClass1.Id+ " did that"),
                   new MyClass2(3, myClass1.Id+ " did this again")
               };
    }
}

public class MyClass1
{
    public MyClass1(int id, string value)
    {
        Id = id;
        Value = value;
    }

    public int Id { get; set; }

    public string Value { get; set; }
}

public class MyClass2
{
    public MyClass1(int id, string value)
    {
        Id = id;
        Value = value;
    }

    public int Id { get; set; }

    public string Value { get; set; }
}
</code>```

So the point I struggle with is the end, where I'd need to call Complete() or wait for Completion. I can't seem to find the right combination. I'd like to see an output as follows:

```<code>TransformBlock(id: 1)
TransformBlock(id: 2)
TransformManyBlock(myClass1: 1|Star Wars)
TransformManyBlock(myClass1: 2|Star Wars)
ActionBlock(myClass2: 1|1 did this)
ActionBlock(myClass2: 2|1 did that)
ActionBlock(myClass2: 3|1 did this again)
ActionBlock(myClass2: 1|2 did this)
ActionBlock(myClass2: 2|2 did that)
ActionBlock(myClass2: 3|2 did this again)
TransformBlock(id: 3)
TransformBlock(id: 4)
TransformManyBlock(myClass1: 3|Star Wars)
TransformManyBlock(myClass1: 4|Star Wars)
ActionBlock(myClass2: 1|3 did this)
ActionBlock(myClass2: 2|3 did that)
ActionBlock(myClass2: 3|3 did this again)
ActionBlock(myClass2: 1|4 did this)
ActionBlock(myClass2: 2|4 did that)
ActionBlock(myClass2: 3|4 did this again)

[the rest of the items]

Press any key to exit...
</code>```

Anyone can point me to the right direction?

答:
You're almost there, you need to call Complete on the first block in the pipeline then await Completion on the last block. Then in your links you need to propagate completion like this:

```<code>private async static void Main(string[] args) {
    var transformBlock = new TransformBlock<int, MyClass1>(delegate (int id)
    {
        Console.WriteLine($"TransformBlock(id: {id})");
        return new MyClass1(id, "Star Wars");
    });
    var transformManyBlock = new TransformManyBlock<MyClass1, MyClass2>(delegate (MyClass1 myClass1)
    {
        Console.WriteLine($"TransformManyBlock(myClass1: {myClass1.Id}|{myClass1.Value})");
        Thread.Sleep(1000);
        return GetMyClass22Values(myClass1);
    });

    var actionBlock = new ActionBlock<MyClass2>(delegate (MyClass2 myClass2)
    {
        Console.WriteLine($"ActionBlock(myClass2: {myClass2.Id}|{myClass2.Value})");
        Thread.Sleep(1000);
    });

    //propagate completion
    transformBlock.LinkTo(transformManyBlock, new DataflowLinkOptions() { PropagateCompletion = true });
    transformManyBlock.LinkTo(actionBlock, new DataflowLinkOptions() { PropagateCompletion = true});
    foreach(var id in ids) {
        transformBlock.Post(id);
    }

    //Complete the first block
    transformBlock.Complete();

    //wait for completion to flow to the last block
    await actionBlock.Completion;
}
</code>```

You can also incorporate the batch block into your pipeline and remove the need for the TryRecieve call but that seems like another part of your flow.

Edit

Example of propagating completion to multiple blocks:

```<code>public async static void Main(string[] args) {

    var sourceBlock = new BufferBlock<int>();

    var processBlock1 = new ActionBlock<int>(i => Console.WriteLine($"Block1 {i}"));

    var processBlock2 = new ActionBlock<int>(i => Console.WriteLine($"Block2 {i}"));

    sourceBlock.LinkTo(processBlock1);
    sourceBlock.LinkTo(processBlock2);

    var sourceBlockCompletion = sourceBlock.Completion.ContinueWith(tsk => {
        if(!tsk.IsFaulted) {
            processBlock1.Complete();
            processBlock2.Complete();
        } else {
            ((IDataflowBlock)processBlock1).Fault(tsk.Exception);
            ((IDataflowBlock)processBlock2).Fault(tsk.Exception);
        }
    });

    //Send some data...

    sourceBlock.Complete();
    await Task.WhenAll(sourceBlockCompletion, processBlock1.Completion, processBlock2.Completion);
}
</code>```

Title: TPL Complete vs Completion

Body:
I need to import customer related data from legacy DB and perform several transformations during the process. This means a single entry needs to perform additional "events" (synchronize products, create invoices, etc.).

My initial solution was a simple parallel approach.
It works okay, but sometimes it has issues. If the currently processed customers need to wait for the same type of events, their processing queues might got stuck and eventually time out, causing every underlying events to fail too (they depend on the one which failed). It doesn't happen all the time, yet it's annoying.

So I got another idea, work in batches. I mean not only limiting the number of customers being processed at the same time, but also the number of the events which are broadcasted to the queues. While searching around for ideas, I found this answer, which points to the TPL DataFlow.

I made a skeleton to get familiar with it. I set up a simple pipeline, but I'm a bit confused about the usage of Complete() and awaiting Completion().

The steps are the following

Make a list of numbers (the ids of the customers to be imported) - this is outside the import logic, it just there to be able to trigger the rest of the logic

Create a BatchBlock (to be able to limit the number of customers to be processed at the same time)

Create a single MyClass1 item based on the id (TransformBlock<int, MyClass1>)

Perform some logic and generate a collection of MyClass2 (TransformManyBlock<MyClass1, MyClass2>) - as example, sleep for 1 second

Perform some logic on every item of the collection (ActionBlock<MyClass2>) - as example, sleep for 1 second

Here's the full code:

public static class Program
{
    private static void Main(string[] args)
    {
        var batchBlock = new BatchBlock<int>(2);
        for (var i = 1; i < 10; i++)
        {
            batchBlock.Post(i);
        }

        batchBlock.Complete();
        while (batchBlock.TryReceive(null, out var ids))
        {
            var transformBlock = new TransformBlock<int, MyClass1>(delegate (int id)
            {
                Console.WriteLine($"TransformBlock(id: {id})");
                return new MyClass1(id, "Star Wars");
            });
            var transformManyBlock = new TransformManyBlock<MyClass1, MyClass2>(delegate (MyClass1 myClass1)
            {
                Console.WriteLine($"TransformManyBlock(myClass1: {myClass1.Id}|{myClass1.Value})");
                Thread.Sleep(1000);
                return GetMyClass22Values(myClass1);
            });

            var actionBlock = new ActionBlock<MyClass2>(delegate (MyClass2 myClass2)
            {
                Console.WriteLine($"ActionBlock(myClass2: {myClass2.Id}|{myClass2.Value})");
                Thread.Sleep(1000);
            });
            transformBlock.LinkTo(transformManyBlock);
            transformManyBlock.LinkTo(actionBlock);
            foreach (var id in ids)
            {
                transformBlock.Post(id);
            }

            // this is the point when I'm not 100% sure

            //transformBlock.Complete();
            //transformManyBlock.Complete();
            //transformManyBlock.Completion.Wait();
            actionBlock.Complete();
            actionBlock.Completion.Wait();
        }

        Console.WriteLine();
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }

    private static IEnumerable<MyClass2> GetMyClass22Values(MyClass1 myClass1)
    {
        return new List<MyClass2>
               {
                   new MyClass2(1, myClass1.Id+ " did this"),
                   new MyClass2(2, myClass1.Id+ " did that"),
                   new MyClass2(3, myClass1.Id+ " did this again")
               };
    }
}

public class MyClass1
{
    public MyClass1(int id, string value)
    {
        Id = id;
        Value = value;
    }

    public int Id { get; set; }

    public string Value { get; set; }
}

public class MyClass2
{
    public MyClass1(int id, string value)
    {
        Id = id;
        Value = value;
    }

    public int Id { get; set; }

    public string Value { get; set; }
}

So the point I struggle with is the end, where I'd need to call Complete() or wait for Completion. I can't seem to find the right combination. I'd like to see an output as follows:

TransformBlock(id: 1)
TransformBlock(id: 2)
TransformManyBlock(myClass1: 1|Star Wars)
TransformManyBlock(myClass1: 2|Star Wars)
ActionBlock(myClass2: 1|1 did this)
ActionBlock(myClass2: 2|1 did that)
ActionBlock(myClass2: 3|1 did this again)
ActionBlock(myClass2: 1|2 did this)
ActionBlock(myClass2: 2|2 did that)
ActionBlock(myClass2: 3|2 did this again)
TransformBlock(id: 3)
TransformBlock(id: 4)
TransformManyBlock(myClass1: 3|Star Wars)
TransformManyBlock(myClass1: 4|Star Wars)
ActionBlock(myClass2: 1|3 did this)
ActionBlock(myClass2: 2|3 did that)
ActionBlock(myClass2: 3|3 did this again)
ActionBlock(myClass2: 1|4 did this)
ActionBlock(myClass2: 2|4 did that)
ActionBlock(myClass2: 3|4 did this again)

[the rest of the items]

Press any key to exit...

Anyone can point me to the right direction?

Body:
You're almost there, you need to call Complete on the first block in the pipeline then await Completion on the last block. Then in your links you need to propagate completion like this:

private async static void Main(string[] args) {
    var transformBlock = new TransformBlock<int, MyClass1>(delegate (int id)
    {
        Console.WriteLine($"TransformBlock(id: {id})");
        return new MyClass1(id, "Star Wars");
    });
    var transformManyBlock = new TransformManyBlock<MyClass1, MyClass2>(delegate (MyClass1 myClass1)
    {
        Console.WriteLine($"TransformManyBlock(myClass1: {myClass1.Id}|{myClass1.Value})");
        Thread.Sleep(1000);
        return GetMyClass22Values(myClass1);
    });

    var actionBlock = new ActionBlock<MyClass2>(delegate (MyClass2 myClass2)
    {
        Console.WriteLine($"ActionBlock(myClass2: {myClass2.Id}|{myClass2.Value})");
        Thread.Sleep(1000);
    });

    //propagate completion
    transformBlock.LinkTo(transformManyBlock, new DataflowLinkOptions() { PropagateCompletion = true });
    transformManyBlock.LinkTo(actionBlock, new DataflowLinkOptions() { PropagateCompletion = true});
    foreach(var id in ids) {
        transformBlock.Post(id);
    }

    //Complete the first block
    transformBlock.Complete();

    //wait for completion to flow to the last block
    await actionBlock.Completion;
}

You can also incorporate the batch block into your pipeline and remove the need for the TryRecieve call but that seems like another part of your flow.

Edit

Example of propagating completion to multiple blocks:

public async static void Main(string[] args) {

    var sourceBlock = new BufferBlock<int>();

    var processBlock1 = new ActionBlock<int>(i => Console.WriteLine($"Block1 {i}"));

    var processBlock2 = new ActionBlock<int>(i => Console.WriteLine($"Block2 {i}"));

    sourceBlock.LinkTo(processBlock1);
    sourceBlock.LinkTo(processBlock2);

    var sourceBlockCompletion = sourceBlock.Completion.ContinueWith(tsk => {
        if(!tsk.IsFaulted) {
            processBlock1.Complete();
            processBlock2.Complete();
        } else {
            ((IDataflowBlock)processBlock1).Fault(tsk.Exception);
            ((IDataflowBlock)processBlock2).Fault(tsk.Exception);
        }
    });

    //Send some data...

    sourceBlock.Complete();
    await Task.WhenAll(sourceBlockCompletion, processBlock1.Completion, processBlock2.Completion);
}


问:
Following pointers in a multithreaded environment
If I have some code that looks something like:

```<code>typedef struct {
    bool some_flag;

    pthread_cond_t  c;
    pthread_mutex_t m;
} foo_t;

// I assume the mutex has already been locked, and will be unlocked
// some time after this function returns. For clarity. Definitely not
// out of laziness ;)
void check_flag(foo_t* f) {
    while(f->flag)
        pthread_cond_wait(&f->c, &f->m);
}
</code>```

Is there anything in the C standard preventing an optimizer from rewriting check_flag as:

```<code>void check_flag(foo_t* f) {
    bool cache = f->flag;
    while(cache)
        pthread_cond_wait(&f->c, &f->m);
}
</code>```

In other words, does the generated code have to follow the f pointer every time through the loop, or is the compiler free to pull the dereference out?

If it is free to pull it out, is there any way to prevent this? Do I need to sprinkle a volatile keyword somewhere? It can't be check_flag's parameter because I plan on having other variables in this struct that I don't mind the compiler optimizing like this.

Might I have to resort to:

```<code>void check_flag(foo_t* f) {
    volatile bool* cache = &f->some_flag;
    while(*cache)
        pthread_cond_wait(&f->c, &f->m);
}
</code>```

答:
Volatile is for this purpose.  Relying on the compiler to know about pthread coding practices seems a little nuts to me, although; compilers are pretty smart these days.  In fact, the compiler probably sees that you are looping to test a variable and won't cache it in a register for that reason, not because it sees you using pthreads.  Just use volatile if you really care.

Kind of funny little note.  We have a VOLATILE #define that is either "volatile" (when we think the bug can't possibly be our code...) or blank.  When we think we have a crash due to the optimizer killing us, we #define it "volatile" which puts volatile in front of almost everything.  We then test to see if the problem goes away.  So far... the bugs have been the developer and not the compiler!  who'd have thought!?  We have developed a high performance "non locking" and "non blocking" threading library.  We have a test platform that hammers it to the point of thousands of races per second.  So fare, we have never detected a problem needing volatile!  So far gcc has never cached a shared variable in a register.  yah...we are surprised too.  We are still waiting for our chance to use volatile!

ContentLicense: CC BY-SA 2.5

Body:
If I have some code that looks something like:

typedef struct {
    bool some_flag;

    pthread_cond_t  c;
    pthread_mutex_t m;
} foo_t;

// I assume the mutex has already been locked, and will be unlocked
// some time after this function returns. For clarity. Definitely not
// out of laziness ;)
void check_flag(foo_t* f) {
    while(f->flag)
        pthread_cond_wait(&f->c, &f->m);
}

Is there anything in the C standard preventing an optimizer from rewriting check_flag as:

void check_flag(foo_t* f) {
    bool cache = f->flag;
    while(cache)
        pthread_cond_wait(&f->c, &f->m);
}

In other words, does the generated code have to follow the f pointer every time through the loop, or is the compiler free to pull the dereference out?

If it is free to pull it out, is there any way to prevent this? Do I need to sprinkle a volatile keyword somewhere? It can't be check_flag's parameter because I plan on having other variables in this struct that I don't mind the compiler optimizing like this.

Might I have to resort to:

void check_flag(foo_t* f) {
    volatile bool* cache = &f->some_flag;
    while(*cache)
        pthread_cond_wait(&f->c, &f->m);
}


问:
xdebug profiler laravel 5.5 windows empty grindfile
I am trying to profile Laravel 5.5 app on Windows 8.1 machine with xdebug 2.5.5 php version 7.0.0. php is running as cgi

Debugging works excellent i can debug but the profiler files are filled with this Laravel error (this is only with Laravel app, in simple php file profiling works fine):

```<code>version: 1 creator: xdebug 2.5.5 (PHP 7.0.15-dev)
cmd: D:\www\laravel55\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\HandleExceptions.php
part: 1
positions: line

events: Time

fl=(1)
fn=(2770) php::error_get_last
122 0

fl=(1)
fn=(74)
122 0

fl=(88)
fn=(2771) Illuminate\Foundation\Bootstrap\HandleExceptions->handleShutdown
120 73
cfl=(1)
cfn=(2770)
calls=1 0 0
122 0
cfl=(1)
cfn=(74)
calls=1 0 0
122 0
</code>```

I have tried with xdebug 2.5.5 php version 7.1.9. same thing.

This are xdebug settings:

```<code>[Xdebug]
zend_extension="D:\AppServ\xdebug\php_xdebug-2.5.5-7.1-vc14-nts.dll"
xdebug.remote_enable=1
;xdebug.remote_port="<the port for Xdebug to listen to>" (the default port is 9000)
xdebug.profiler_enable=0
xdebug.profiler_enable_trigger=1
xdebug.profiler_enable_trigger_value=1
xdebug.remote_autostart=1
xdebug.profiler_output_dir="D:\AppServ\xdebug\tmp"
xdebug.idekey="PHPSTORM"
</code>```

答:
The grid file is probably empty because it is overwritten several times in the same request.

You can add the timestamp + script location into the filename to prevent this:

```<code>xdebug.profiler_output_name = "cachegrind.out.%t-%s"
</code>```

Body:
I am trying to profile Laravel 5.5 app on Windows 8.1 machine with xdebug 2.5.5 php version 7.0.0. php is running as cgi

Debugging works excellent i can debug but the profiler files are filled with this Laravel error (this is only with Laravel app, in simple php file profiling works fine):

version: 1 creator: xdebug 2.5.5 (PHP 7.0.15-dev)
cmd: D:\www\laravel55\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\HandleExceptions.php
part: 1
positions: line

events: Time

fl=(1)
fn=(2770) php::error_get_last
122 0

fl=(1)
fn=(74)
122 0

fl=(88)
fn=(2771) Illuminate\Foundation\Bootstrap\HandleExceptions->handleShutdown
120 73
cfl=(1)
cfn=(2770)
calls=1 0 0
122 0
cfl=(1)
cfn=(74)
calls=1 0 0
122 0

I have tried with xdebug 2.5.5 php version 7.1.9. same thing.

This are xdebug settings:

[Xdebug]
zend_extension="D:\AppServ\xdebug\php_xdebug-2.5.5-7.1-vc14-nts.dll"
xdebug.remote_enable=1
;xdebug.remote_port="<the port for Xdebug to listen to>" (the default port is 9000)
xdebug.profiler_enable=0
xdebug.profiler_enable_trigger=1
xdebug.profiler_enable_trigger_value=1
xdebug.remote_autostart=1
xdebug.profiler_output_dir="D:\AppServ\xdebug\tmp"
xdebug.idekey="PHPSTORM"

Body:
The grid file is probably empty because it is overwritten several times in the same request.

You can add the timestamp + script location into the filename to prevent this:

xdebug.profiler_output_name = "cachegrind.out.%t-%s"


问:
How to set added item as active object?
I'm using the following to add text to my fabricjs canvas and I was wondering how I could have it be automatically selected when the onclick is triggered?

```<code>// Add text
function Addtext() {
   canvas.add(new fabric.IText('Tap and Type', {
      left: 50,
      top: 100,
   }));
}
</code>```

```<code><button onclick="Addtext()">+ Text</button>
</code>```

答:
You should work with : object added and set the object active like this ; </p>

```<code>canvas.on({
        'object:added': function(e) {
              e.set('active',true);
            }
        }
</code>```

<p>Or, you juste need to put your object in a variable, and then set it to active. </p>

Title: How to set added item as active object?

Body:
I'm using the following to add text to my fabricjs canvas and I was wondering how I could have it be automatically selected when the onclick is triggered?

// Add text
function Addtext() {
   canvas.add(new fabric.IText('Tap and Type', {
      left: 50,
      top: 100,
   }));
}

<button onclick="Addtext()">+ Text</button>

Body:
You should work with : object added and set the object active like this ;

canvas.on({
        'object:added': function(e) {
              e.set('active',true);
            }
        }

Or, you juste need to put your object in a variable, and then set it to active.


问:
Need help understanding a specific alloc/release idiom in iOS/Objective-C programming
I'm an experienced C/C++ programmer starting to learn Objective-C development. I'm currently looking through the UICatalog sample and came across another instance of an idiom I've seen several places and never understood.

Code:

```<code>ButtonsViewController *buttonsViewController = [[ButtonsViewController alloc] initWithNibName:@"ButtonsViewController" bundle:nil];
[self.menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                       NSLocalizedString(@"ButtonsTitle", @""), kTitleKey,
                                       NSLocalizedString(@"ButtonsExplain", @""), kExplainKey,
                                       buttonsViewController, kViewControllerKey, nil]];
[buttonsViewController release];
</code>```

AFAIK, this allocates and initializes a ButtonsViewController, creates an NSDictionary for the ButtonsViewController and adds the dictionary to an NSMutableArray called menuList (which is a member variable of the MainViewController where the above code lives) and then releases the buttonsViewController that it just created. Later, the MainViewController uses the dictionary entry to switch views to the buttonsViewController when necessary.

My question is: why is the buttonsViewController still valid after this code? It was allocated and released with no 'retains' between. Does adding something to an NSDictionary or NSMutableArray have an implicit 'retain'? If so, was I supposed to be able to figure that out somehow, or is it just one of those things you have to read and remember?

答:
It is standard procedure in the Cocoa frameworks for collections to retain the objects they contain. So yes, the mutable array is retaining the view controller. </p>

<p>This is always the case, unless the documentation says otherwise. </p>

Body:
I'm an experienced C/C++ programmer starting to learn Objective-C development. I'm currently looking through the UICatalog sample and came across another instance of an idiom I've seen several places and never understood.

Code:

ButtonsViewController *buttonsViewController = [[ButtonsViewController alloc] initWithNibName:@"ButtonsViewController" bundle:nil];
[self.menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                       NSLocalizedString(@"ButtonsTitle", @""), kTitleKey,
                                       NSLocalizedString(@"ButtonsExplain", @""), kExplainKey,
                                       buttonsViewController, kViewControllerKey, nil]];
[buttonsViewController release];

AFAIK, this allocates and initializes a ButtonsViewController, creates an NSDictionary for the ButtonsViewController and adds the dictionary to an NSMutableArray called menuList (which is a member variable of the MainViewController where the above code lives) and then releases the buttonsViewController that it just created. Later, the MainViewController uses the dictionary entry to switch views to the buttonsViewController when necessary.

My question is: why is the buttonsViewController still valid after this code? It was allocated and released with no 'retains' between. Does adding something to an NSDictionary or NSMutableArray have an implicit 'retain'? If so, was I supposed to be able to figure that out somehow, or is it just one of those things you have to read and remember?

Body:
It is standard procedure in the Cocoa frameworks for collections to retain the objects they contain. So yes, the mutable array is retaining the view controller.

This is always the case, unless the documentation says otherwise.


问:
Basic flow results in NullPayload
I'm new to Mule and I'm trying to get the very first example from the book "Mule in Action" working.

I'm using Mule 3.9 and Anypoint Studio 6.4.1.  In chapter 1 they describe a very basic product_registration flow that I have created as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:jms="http://www.mulesoft.org/schema/mule/jms" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core
http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http
http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/jms
http://www.mulesoft.org/schema/mule/jms/current/mule-jms.xsd">
    <http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8880" basePath="products" doc:name="HTTP Listener Configuration"/>
    <jms:activemq-connector name="Active_MQ" username="admin" password="admin" brokerURL="tcp://localhost:61616" validateConnections="true" doc:name="Active MQ"/>
    <flow name="product_registrationFlow">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP"/>
        <logger level="INFO" doc:name="Logger Before"/>
        <byte-array-to-string-transformer doc:name="Byte Array to String"/>
        <logger level="INFO" doc:name="Logger After"/>
        <jms:outbound-endpoint doc:name="JMS" queue="products"/>
    </flow>
</mule>
</code>```

and an accompanying functional test:

```<code>@Test
public void testCanRegisterProducts() throws Exception {

    LocalMuleClient client = muleContext.getClient();

    String productAsJson = "{ \"name\":\"Widget\", \"price\": 9.99, \"weight\": 1.0, \"sku\": \"abcd-56789\" }";

    MuleMessage source = new DefaultMuleMessage(productAsJson, muleContext);
    client.dispatch("http://localhost:8880/products", source);

    MuleMessage result = client.request("jms://products", RECEIVE_TIMEOUT);

    assertNotNull(result);
    assertFalse(result.getPayload() instanceof NullPayload);
    assertEquals(productAsJson, result.getPayloadAsString());
}
</code>```

When I run the test it fails at the last assert because the actual payload is:

```<code>{NullPayload}
</code>```

And if I look directly in ActiveMQ I see that payload. If I manually post to Mule (using a tool like Poster in Chrome, setting only the header Content-Type: application/json) the payload is valid JSON and I can get the test to pass (because it is getting the pending message from the queue posted by Poster and the message it creates is at the end of the queue with payload {NullPayload}.

Can someone shed some light on why the flow fails when invoked from the JUnit test, but seems to work when invoked by using a tool like Poster?

Update: With the help of Pierre B. I got it working.  The initialization of the MuleMessage in the FunctionalTestCase was updated as follows:

```<code>    MuleMessage source = new DefaultMuleMessage(productAsJson, muleContext);
    source.setProperty("Content-Type", "application/json", PropertyScope.INBOUND);
    source.setProperty("Content-Length", Integer.valueOf(productAsJson.length()), PropertyScope.INBOUND);
</code>```

答:
You said it works when you POST a message using an external tool instead of MuleClient:

using a tool like Poster in Chrome, setting only the header Content-Type: application/json

Try adding the same header to your MuleMessage such as:

```<code>MuleMessage source = new DefaultMuleMessage(productAsJson, muleContext);

# define the headers
Map<String, Object> headers = new HashMap<String, Object>(1);
headers.put("Content-Type", "application/json");
headers.put("Content-Length", sourceLength);

# add the headers as function parameter
client.dispatch("http://localhost:8880/products", source, headers);
</code>```

EDIT: as @sceaj pointed out, both Content-Type and Content-Length headers are required.

Title: Basic flow results in NullPayload

Body:
I'm new to Mule and I'm trying to get the very first example from the book "Mule in Action" working.

I'm using Mule 3.9 and Anypoint Studio 6.4.1.  In chapter 1 they describe a very basic product_registration flow that I have created as follows:

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:jms="http://www.mulesoft.org/schema/mule/jms" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core
http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http
http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/jms
http://www.mulesoft.org/schema/mule/jms/current/mule-jms.xsd">
    <http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8880" basePath="products" doc:name="HTTP Listener Configuration"/>
    <jms:activemq-connector name="Active_MQ" username="admin" password="admin" brokerURL="tcp://localhost:61616" validateConnections="true" doc:name="Active MQ"/>
    <flow name="product_registrationFlow">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP"/>
        <logger level="INFO" doc:name="Logger Before"/>
        <byte-array-to-string-transformer doc:name="Byte Array to String"/>
        <logger level="INFO" doc:name="Logger After"/>
        <jms:outbound-endpoint doc:name="JMS" queue="products"/>
    </flow>
</mule>

and an accompanying functional test:

@Test
public void testCanRegisterProducts() throws Exception {

    LocalMuleClient client = muleContext.getClient();

    String productAsJson = "{ \"name\":\"Widget\", \"price\": 9.99, \"weight\": 1.0, \"sku\": \"abcd-56789\" }";

    MuleMessage source = new DefaultMuleMessage(productAsJson, muleContext);
    client.dispatch("http://localhost:8880/products", source);

    MuleMessage result = client.request("jms://products", RECEIVE_TIMEOUT);

    assertNotNull(result);
    assertFalse(result.getPayload() instanceof NullPayload);
    assertEquals(productAsJson, result.getPayloadAsString());
}

When I run the test it fails at the last assert because the actual payload is:

{NullPayload}

And if I look directly in ActiveMQ I see that payload. If I manually post to Mule (using a tool like Poster in Chrome, setting only the header Content-Type: application/json) the payload is valid JSON and I can get the test to pass (because it is getting the pending message from the queue posted by Poster and the message it creates is at the end of the queue with payload {NullPayload}.

Can someone shed some light on why the flow fails when invoked from the JUnit test, but seems to work when invoked by using a tool like Poster?

Update: With the help of Pierre B. I got it working.  The initialization of the MuleMessage in the FunctionalTestCase was updated as follows:

    MuleMessage source = new DefaultMuleMessage(productAsJson, muleContext);
    source.setProperty("Content-Type", "application/json", PropertyScope.INBOUND);
    source.setProperty("Content-Length", Integer.valueOf(productAsJson.length()), PropertyScope.INBOUND);

Body:
You said it works when you POST a message using an external tool instead of MuleClient:

using a tool like Poster in Chrome, setting only the header Content-Type: application/json

Try adding the same header to your MuleMessage such as:

MuleMessage source = new DefaultMuleMessage(productAsJson, muleContext);

# define the headers
Map<String, Object> headers = new HashMap<String, Object>(1);
headers.put("Content-Type", "application/json");
headers.put("Content-Length", sourceLength);

# add the headers as function parameter
client.dispatch("http://localhost:8880/products", source, headers);

EDIT: as @sceaj pointed out, both Content-Type and Content-Length headers are required.


问:
Page Header, Page counter and Page Footer layout not working
I have a main report and a subreport i.e main.jrxml and sub.jrxml with the following problems:

On second page the current page number is not incremented

On second page and onwards the Title and Page Header are not fully removed

On last page the Disclaimer and page number is missing

.jasper file is not always re-generated for subreport in Jasper Studio, how can I make sure this is per default always re-generated

I run the reports with the Sample DB. How can I fix this?

CLARIFICATION:

For the page numbering on the TextField I use:

msg("Page {0} of {1}", $V{V_CURRENT_PAGE_NUMBER}, $V{PAGE_NUMBER})

V_CURRENT_PAGE_NUMBER is defined as follows:

```<code>Expression 1
Initial Value Exppression $V{PAGE_NUMBER}
Increment type Page
Reset type Report
</code>```

In the end I used Composite Elements for both current and total page info.

UPDATE:

Point 2: Moved Page Header content into Title.

Point 3: I solved by repeating Disclaimer and page number also in Last Page Footer. I have it now in both Page Footer and Last Page Footer.

答:
Use the Page X of Y element from the Composite Elements of the Palette view.

Only the Page Header repeats on subsequent pages. You can show it only on first page with a Print When Expression like: $V{PAGE_NUMBER} == 1

Duplicate the Footer elements in the Last Page Footer.

From the top menu select Project > Build Automatically

Body:
I have a main report and a subreport i.e main.jrxml and sub.jrxml with the following problems:

On second page the current page number is not incremented

On second page and onwards the Title and Page Header are not fully removed

On last page the Disclaimer and page number is missing

.jasper file is not always re-generated for subreport in Jasper Studio, how can I make sure this is per default always re-generated

I run the reports with the Sample DB. How can I fix this?

CLARIFICATION:

For the page numbering on the TextField I use:

msg("Page {0} of {1}", $V{V_CURRENT_PAGE_NUMBER}, $V{PAGE_NUMBER})

V_CURRENT_PAGE_NUMBER is defined as follows:

Expression 1
Initial Value Exppression $V{PAGE_NUMBER}
Increment type Page
Reset type Report

In the end I used Composite Elements for both current and total page info.

UPDATE:

Point 2: Moved Page Header content into Title.

Point 3: I solved by repeating Disclaimer and page number also in Last Page Footer. I have it now in both Page Footer and Last Page Footer.


问:
webpack-dev-server not working Cannot find module '../lib/polyfills'
I moved my project to another computer, ran npm install. Project works fine except webpack-dev-server, it throws error

```<code>module.js:544
throw err;
^

Error: Cannot find module '../lib/polyfills'
    at Function.Module._resolveFilename (module.js:542:15)
    at Function.Module._load (module.js:472:25)
    at Module.require (module.js:585:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/project/node_modules/.bin/webpack-dev-server:6:1)
    at Module._compile (module.js:641:30)
    at Object.Module._extensions..js (module.js:652:10)
    at Module.load (module.js:560:32)
    at tryModuleLoad (module.js:503:12)
    at Function.Module._load (module.js:495:3)
</code>```

What is it missing ?

答:
I had this exact issue and fixed it doing the following.

Running webpack-dev-server gave the error you pasted.

I thought it may have been a configuration issue, so I tried node_modules/.bin/webpack-dev-server to fix the configuration via the CLI.

Doing this, I was given the same error.

The file inside of .bin existed but something was clearly wrong.  I suspect it's because I seeded this project by copying from another one and perhaps references normally set as part of npm install weren't set on the copy, so they were still pointing to the source of my copy.

Regardless, run npm install --save-dev webpack-dev-server again and try.  Fixed my issue both in running webpack-dev-server and the CLI even though they were already installed.  Perhaps just installed improperly.

Body:
I moved my project to another computer, ran npm install. Project works fine except webpack-dev-server, it throws error

module.js:544
throw err;
^

Error: Cannot find module '../lib/polyfills'
    at Function.Module._resolveFilename (module.js:542:15)
    at Function.Module._load (module.js:472:25)
    at Module.require (module.js:585:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/project/node_modules/.bin/webpack-dev-server:6:1)
    at Module._compile (module.js:641:30)
    at Object.Module._extensions..js (module.js:652:10)
    at Module.load (module.js:560:32)
    at tryModuleLoad (module.js:503:12)
    at Function.Module._load (module.js:495:3)

What is it missing ?


问:
Is storing configurations in vuex store a good practice?
Is storing configurations in vuex store a good practice?</p>

```<code>export default {
  state: {
    app: {
      name: 'A project using vuex'
    }
  }
}
</code>```

答:
Personally, I only put things into the Vuex (or Redux) store that will have some impact to the user. Data from the backend, settings/configurations that alter the interface, etc. You should be able to bootstrap your store data on page load so that if the user refreshes, they're exactly where they were before.

Some configuration options might make sense in the store (particularly if the user can change them somehow). For most things (like app name, app version, etc.), I usually keep them in an environment variable (via the .env file), and read them in as-needed in my application code. Rather than injecting them into the store, I would opt to generate constants for them so there is no risk of them changing if they are not supposed to. This has a lot of benefits:

It's very easy to have different configurations for different environments

It's easy to keep your production configuration out of git in the case that it contains sensitive data (e.g. API credentials)

This data is stored in a clear, concise, and consistent location. It's easy to see how the data changes over time via source control

It's impossible to accidentally modify a variable in state that you didn't intend to

Body:
Is storing configurations in vuex store a good practice?

export default {
  state: {
    app: {
      name: 'A project using vuex'
    }
  }
}


问:
Default Angular-CLI Project Fails in Safari - culprit strict mode?
I have installed the most-recent version of the angular-cli and created a brand new project (ng new my-app). This creates the always-stylish "Welcome to App" with the Angular logo and links to Tour of Heroes, the CLI Documentation, and the Angular blog. I can ng serve this and access it locally on my Windows machine using Chrome and Firefox.

Where this gets strange is when I try to access the same locally hosted app through Browserstack. When I hit it from a Mac running Safari 11, all works as expected.

However, when I try to access via a Mac device (iPad for example) running Safari 10+, the app will not load and I get the error message: "SyntaxError: Unexpected keyword 'const'. Const declarations are not supported in strict mode". The error message is tied to a location in my vendor.bundle.js (in an eval).

From my reading, it appears that older versions of Safari don't play nice with consts when strict mode is enabled. But, I am hoping there is a work-around.

How are others handling this? I am not an angular-cli expert, so if there is an obvious solution, my apologies for not seeing it.

Any assistance would be greatly appreciated.

答:
I have the same issue. It seems an issue in webpack-dev-server (used under the hood by @angular/cli) which uses ES6 features and is not being transpiled.

This is only a problem in older versions of Safari, but updating Safari is not a solution when you want to test on older Safari versions.

A temporary workaround is to use an older version for webpack-dev-server by installing it and copying it manually to the local @angular/cli directory:

```<code>yarn add webpack-dev-server@2.7.1 --dev
cp -R ./node_modules/webpack-dev-server ./node_modules/@angular/cli/node_modules/
./node_modules/.bin/ng serve
</code>```

Body:
I have the same issue. It seems an issue in webpack-dev-server (used under the hood by @angular/cli) which uses ES6 features and is not being transpiled.

This is only a problem in older versions of Safari, but updating Safari is not a solution when you want to test on older Safari versions.

A temporary workaround is to use an older version for webpack-dev-server by installing it and copying it manually to the local @angular/cli directory:

yarn add webpack-dev-server@2.7.1 --dev
cp -R ./node_modules/webpack-dev-server ./node_modules/@angular/cli/node_modules/
./node_modules/.bin/ng serve


问:
Anyway to obtain cell Precedents and Dependents in Excel Javascript API?
Unlike the desktop Excel APIs, which contain a "Precedents" and a "Dependents" on the Range object, the short answer is no for the Excel Javascript APIs, which brings me here.

Is there a way or third-party piece of code to circumvent this huge lack from Microsoft ? If I can't navigate the formula tree, there is just not much useful I can add in terms of add-ins for Excel Online.

Javascript API for Excel

Office Online

UPDATE: to add some context, I've been writing auditing add-ins in C# in the past, to evaluate formula complexity, perform advanced reconciliation of formulas, reconstruct formulas differently, etc... I'm trying to convert a small piece of it, as a javascript prototype add-in, to see whether Excel online can handle it.

答:
I looked at this earlier in the year.
The only way at the moment would be to parse out the references from the formula, which is non-trivial (but achievable) given the wide variety of possible reference types.

For a starter look here http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html

And even then you would still have limitations for functions returning references like OFFSET, INDIRECT etc since the JS API does not currently have any Evaluate methods.
 And to be comprehensive you would also need to handle things like Implicit Intersection etc.

The latest version of the JS API does contain methods for handling Named Formulas, which is a good step forward so a parser would also be able to find references in those.