问:
Using numpy.fromregex on a text file with colon separated digits
I have a dataset that looks like this:

```<code># sparse.txt
1 1:1 2:1 3:1
0 1:1 4:1
1 12:1 13:1 14:1
</code>```

I want to create a matrix without colons which looks like this:

```<code># sparse2.txt
1 1 1 2 1 3 1
0 1 1 4 1
1 2 1 3 1 4 1
</code>```

I used online python regex to find the regex pattern to read the rows of the file.
https://pythex.org/

I used the pattern:

```<code>pat = [0-1]\s+([0-9]:1\s*)+
</code>```

Which satisfies the regex in online regexer, but, when I used it in np.fromregex
it does not work.

```<code>import numpy as np
pat = r'[0-1]\s+([0-9]:1\s*)+'

data = np.fromregex('sparse.txt', pat, dtype='str')
print("data = {}".format(data))
</code>```

How can we fix the error?

答:
With @Wiktor's pattern

```<code>In [58]: pat1 = r'([0-1])\s+([0-9]):(1)\s+([0-9]):(1)(?:\s+([0-9]):(1))?'
In [59]: np.fromregex('stack47266965.txt', pat1, dtype='str')
Out[59]:
array([['1', '1', '1', '2', '1', '3', '1'],
       ['0', '1', '1', '4', '1', '', ''],
       ['1', '2', '1', '3', '1', '4', '1']],
      dtype='<U1')
</code>```

This is a 2d array of dtype string (unicode here); note the padding for the short 2nd line.  That's produced by the ?: portion of the pattern.

fromregex does a re.findall and casts that list of tuples into an array:

```<code>In [60]: re.findall(pat1, open('stack47266965.txt').read())
Out[60]:
[('1', '1', '1', '2', '1', '3', '1'),
 ('0', '1', '1', '4', '1', '', ''),
 ('1', '2', '1', '3', '1', '4', '1')]
</code>```

Note that the fromregex documentation stresses that it returns a structured array.  That list of tuples can be the correct input to a np.array(seq, dtype=dt), where dt is a compound dtype.  Each tuple should have the same length, one that matches the dtype.

This case shows that it works with a simple dtype like str.  But what does this do for you.  You can't convert those strings to numbers, without somehow filtering out the blanks.  And without the blanks the array can not longer be 2d.  That short middle line prevents that.

The text file readers in numpy are designed to read the file line by line, parsing each into a row of a 2d array, or a record of a 1d structured array.  Irregular line length is a problem, requiring some sort of fill.

@XetRAFHan's pattern extracts all the numbers you want, but looses the row structure:

```<code>In [93]: pat2 = r'^\d|[^0-9\:\n][\d]?'
In [94]: re.findall(pat2, open('stack47266965.txt').read())
Out[94]: ['1', ' 1', ' 2', ' 3', ' 1', ' 4', ' 2', ' 3', ' 4']
</code>```

The kind of split that you did before retains the file structure

Create dense matrix from sparse matrix efficently (numpy/scipy but NO sklearn)

```<code>In [95]: lines = open('stack47266965.txt').readlines()
In [96]: lines
Out[96]: ['1 1:1 2:1 3:1\n', '0 1:1 4:1\n', '1 2:1 3:1 4:1\n']
In [97]: alist = []
In [98]: for line in lines:
    ...:     row = line.split()
    ...:     label = int(row[0])
    ...:     values = [int(a.split(':')[0]) for a in row[1:]]
    ...:     alist.append((label, values))
    ...:
In [99]: alist
Out[99]: [(1, [1, 2, 3]), (0, [1, 4]), (1, [2, 3, 4])]
</code>```

Body:
I have a dataset that looks like this:

# sparse.txt
1 1:1 2:1 3:1
0 1:1 4:1
1 12:1 13:1 14:1

I want to create a matrix without colons which looks like this:

# sparse2.txt
1 1 1 2 1 3 1
0 1 1 4 1
1 2 1 3 1 4 1

I used online python regex to find the regex pattern to read the rows of the file.
https://pythex.org/

I used the pattern:

pat = [0-1]\s+([0-9]:1\s*)+

Which satisfies the regex in online regexer, but, when I used it in np.fromregex
it does not work.

import numpy as np
pat = r'[0-1]\s+([0-9]:1\s*)+'

data = np.fromregex('sparse.txt', pat, dtype='str')
print("data = {}".format(data))

How can we fix the error?

Body:
With @Wiktor's pattern

In [58]: pat1 = r'([0-1])\s+([0-9]):(1)\s+([0-9]):(1)(?:\s+([0-9]):(1))?'
In [59]: np.fromregex('stack47266965.txt', pat1, dtype='str')
Out[59]:
array([['1', '1', '1', '2', '1', '3', '1'],
       ['0', '1', '1', '4', '1', '', ''],
       ['1', '2', '1', '3', '1', '4', '1']],
      dtype='<U1')

This is a 2d array of dtype string (unicode here); note the padding for the short 2nd line.  That's produced by the ?: portion of the pattern.

fromregex does a re.findall and casts that list of tuples into an array:

In [60]: re.findall(pat1, open('stack47266965.txt').read())
Out[60]:
[('1', '1', '1', '2', '1', '3', '1'),
 ('0', '1', '1', '4', '1', '', ''),
 ('1', '2', '1', '3', '1', '4', '1')]

Note that the fromregex documentation stresses that it returns a structured array.  That list of tuples can be the correct input to a np.array(seq, dtype=dt), where dt is a compound dtype.  Each tuple should have the same length, one that matches the dtype.

This case shows that it works with a simple dtype like str.  But what does this do for you.  You can't convert those strings to numbers, without somehow filtering out the blanks.  And without the blanks the array can not longer be 2d.  That short middle line prevents that.

The text file readers in numpy are designed to read the file line by line, parsing each into a row of a 2d array, or a record of a 1d structured array.  Irregular line length is a problem, requiring some sort of fill.

@XetRAFHan's pattern extracts all the numbers you want, but looses the row structure:

In [93]: pat2 = r'^\d|[^0-9\:\n][\d]?'
In [94]: re.findall(pat2, open('stack47266965.txt').read())
Out[94]: ['1', ' 1', ' 2', ' 3', ' 1', ' 4', ' 2', ' 3', ' 4']

The kind of split that you did before retains the file structure

Create dense matrix from sparse matrix efficently (numpy/scipy but NO sklearn)

In [95]: lines = open('stack47266965.txt').readlines()
In [96]: lines
Out[96]: ['1 1:1 2:1 3:1\n', '0 1:1 4:1\n', '1 2:1 3:1 4:1\n']
In [97]: alist = []
In [98]: for line in lines:
    ...:     row = line.split()
    ...:     label = int(row[0])
    ...:     values = [int(a.split(':')[0]) for a in row[1:]]
    ...:     alist.append((label, values))
    ...:
In [99]: alist
Out[99]: [(1, [1, 2, 3]), (0, [1, 4]), (1, [2, 3, 4])]


来源: stackexchange

问:
Precisely scale image
I am trying to precisely and predictably scale an image in C# to a different resolution, both up and down. When I open the resulting images with external tools such as Gimp, the results are not satisfying with my current settings.

```<code>public Image Square(Image image, int res) {
    Bitmap sq = new Bitmap(res, res, image.PixelFormat);
    Graphics canvas = Graphics.FromImage(sq);
    canvas.CompositingQuality = CompositingQuality.HighQuality;
    canvas.SmoothingMode = SmoothingMode.None;
    canvas.InterpolationMode = InterpolationMode.Bicubic;
    canvas.DrawImage(sq, 0, 0, res, res);
    return sq;
}
</code>```

The results are okay when scaling down (but far from perfect), but there are side-effects when scaling up:

This picture has a resolution of 2x2 pixels. The alpha channel is set to opaque for all pixels.

After scaling it to 4x4 pixels, this is the result:

Apparently, the C# graphics library introduced transparency while scaling the picture. This method should still work if the given image has transparent pictures, so removing the alpha channel is not an option.

Similarly, when scaling pictures down, there are problems at the edges of the resulting images as well, usually either very dark or transparent.

Is there any way to circumvent this behavior?

Edit: I already tried NearestNeighbor for downscaling only, but it results in this:

Edit 2: With WrapMode.TileFlipXY, the transparent edge is gone, but red only makes up 25% of the image instead of 50% as it should be:

答:
A way to avoid edge artifacts is to wrap the image:

```<code>using (ImageAttributes wrapMode = new ImageAttributes())
{
    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
    g.DrawImage(input, rect, 0, 0, input.Width, input.Height, GraphicsUnit.Pixel, wrapMode);
}
</code>```

Direct copy/paste from:

Ghost-borders ('ringing') when resizing in GDI+

ContentLicense: CC BY-SA 3.0

Title: Precisely scale image

Body:
I am trying to precisely and predictably scale an image in C# to a different resolution, both up and down. When I open the resulting images with external tools such as Gimp, the results are not satisfying with my current settings.

public Image Square(Image image, int res) {
    Bitmap sq = new Bitmap(res, res, image.PixelFormat);
    Graphics canvas = Graphics.FromImage(sq);
    canvas.CompositingQuality = CompositingQuality.HighQuality;
    canvas.SmoothingMode = SmoothingMode.None;
    canvas.InterpolationMode = InterpolationMode.Bicubic;
    canvas.DrawImage(sq, 0, 0, res, res);
    return sq;
}

The results are okay when scaling down (but far from perfect), but there are side-effects when scaling up:

This picture has a resolution of 2x2 pixels. The alpha channel is set to opaque for all pixels.

After scaling it to 4x4 pixels, this is the result:

Apparently, the C# graphics library introduced transparency while scaling the picture. This method should still work if the given image has transparent pictures, so removing the alpha channel is not an option.

Similarly, when scaling pictures down, there are problems at the edges of the resulting images as well, usually either very dark or transparent.

Is there any way to circumvent this behavior?

Edit: I already tried NearestNeighbor for downscaling only, but it results in this:

Edit 2: With WrapMode.TileFlipXY, the transparent edge is gone, but red only makes up 25% of the image instead of 50% as it should be:

Body:
A way to avoid edge artifacts is to wrap the image:

using (ImageAttributes wrapMode = new ImageAttributes())
{
    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
    g.DrawImage(input, rect, 0, 0, input.Width, input.Height, GraphicsUnit.Pixel, wrapMode);
}

Direct copy/paste from:

Ghost-borders ('ringing') when resizing in GDI+


问:
ARKit : How to apply material with multiple colors for SCNCylinder in SCNView?
I have to make a SCNCylinder to look like a dynamic pie chart, I am able to make it look like static pie chart by adding texture or applying color to SCNCylinder with below code. However, my pie chart values changes randomly and want to add material with color values occupying percentage portion of the cylinder. </p>

```<code>    var planet : SCNGeometry
    planet = SCNCylinder(radius: 0.2, height: 0.05)
    let material = SCNMaterial()
    material.diffuse.contents = UIImage(named: "texture.jpg")
    //OR to apply single color
    material.diffuse.contents = UIColor.red
    planet.materials = [material]
    let planetNode = SCNNode(geometry: planet)
</code>```

答:
You can’t recolor arbitrary parts of SCNCylinder with discrete materials. SceneKit defines only one way to decompose a cylinder into separate portions with separate materials (from the docs):

A cylinder contains three SCNGeometryElement objects: one each for its base and top, and one that wraps around its sides. SceneKit can render each element using a different material. For details, see the materials property in SCNGeometry.

That means you can set your planet.materials to an array of three materials, but SceneKit can only use them to color the top, bottom, and sides separately.

So what recourse do you have if you want to create a pie-chart style appearance? OTOH, I can think of two or three directions to investigate:

Do it with images

You mention you’ve already tried something like this — create a static image that looks like a pie chart and assign it to the (top material?) of the cylinder.

There’s nothing preventing you from extending this technique to non-static pie charts. You’ll just need to create your images dynamically (with CoreGraphics, UIGraphicsImageRenderer, etc).

To get your pie chart looking right in 3D you’ll need to create 3 images — a regular pie chart for the top of the cylinder, a reversed version of the same pie chart for the bottom, and a rectangular image with top-to-bottom blocks of color in the same relative proportions as the pie slices that wraps around the sides. It’ll probably take some experimentation to figure out how to format those three images so they line up right.

Do it with custom geometry

If you want a “fully 3D” pie chart (like the ones you see in Pages, Numbers, and Keynote), where each slice is a separate 3D object that can be pulled away from the pie made taller/shorter than other slices, etc, then SCNCylinder is not for you. It only knows how to draw complete cylinders.

There aren’t any built-in SceneKit classes for creating wedge shapes, but if you can work out the math to construct a mesh yourself, you can use SCNGeometrySource and SCNGeometryElement to construct that mesh in SceneKit.

Do it with SCNShape

Custom geometry might be overkill for this task, though. The kind of shape you’re looking for is one of the simpler kinds of 3D geometry — a 2D shape (a sector of a circle) extruded in a third dimension to create a 3D solid (a wedge of a pie, slice of a cake, or whatever other delicious metaphor you prefer).

In SceneKit, there’s an app for that. (Er, a class.) SCNShape takes a 2D UIBezierPath and extrudes it to create a 3D object. You can even apply nice little rounded edges to it. And UIBezierPath lets you create paths using circle arcs.

So, to build a pie chart:

Create several UIBezierPath objects, one for each slice of pie, using the init(arcCenter:radius:startAngle:endAngle:clockwise:) initializer. Use the same center point for all of them (zero is probably fine).

From each Bézier path, create an SCNShape with your preferred extrusion depth. If you want each slice of your pie to have a different flavor color, assign a different material to each shape.

Assemble the slices into a pie by creating an SCNNode to hold each, and placing those nodes at the same position. (The 2D origin of the arc is respected in the 3D coordinate system, so if you set the same node position for different arcs created with the same center they’ll have the same center in 3D.) If you want to be able to move the whole pie together after that, create another SCNNode and make all of the slices its children.

Dangit, now I’m hungry...

Body:
I have to make a SCNCylinder to look like a dynamic pie chart, I am able to make it look like static pie chart by adding texture or applying color to SCNCylinder with below code. However, my pie chart values changes randomly and want to add material with color values occupying percentage portion of the cylinder.

    var planet : SCNGeometry
    planet = SCNCylinder(radius: 0.2, height: 0.05)
    let material = SCNMaterial()
    material.diffuse.contents = UIImage(named: "texture.jpg")
    //OR to apply single color
    material.diffuse.contents = UIColor.red
    planet.materials = [material]
    let planetNode = SCNNode(geometry: planet)


问:
C# and negative array indices
I'm having a problem with getting this code (from Rosetta Code) to work as part of a greater Windows Form Project:

It's a plain old insertion sort. Where it's going wrong is the bit involving the second for loop (The numbers generate just fine), in the sorting part of it. To me within a couple of iterations of the loop then j will be into negative figures and whilst other languages such as Javascript and Pascal don't seem to mind this...C# isn't happy.

```<code>        private void button3_Click(object sender, EventArgs e)
        {

            int i, j, k;
            int[] a = new int[12];
            Random randomObject = new Random();
            ClearOutputs(); // this is an event which just clears the
               text
            from the text boxes.
            //Generate some random numbers
            for (i = 0; i < a.Length; i++)
            {
                a[i] = randomObject.Next(1, 1000);
                textBox1.AppendText(a[i].ToString() + "\n");
            }

            for (i = 1; i <= a.Length; i++)
            {
                k = a[i];
   //*******************
                for (j = i; j > 0 & k < a[j - 1]; j--)
                {
                    a[j] = a[j - 1];
                    a[j] = k;
                }
            }
    // ***************
            //Display them...it never executes this part.
            for (i = 0; i < a.Length; i++)
            {
                textBox2.AppendText(a[i].ToString() + "\n");
            }
        }
</code>```

The longer term fix would be for me to understand the coding of the algorithm...and then fix it for myself, but if anyone could point me in the right direction...I've tried setting the 'for' loop at a higher initial value and yet still got the same "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" Any help would be greatly appreciated.

答:
Following the provided Rosetta Code algorithm, you should change the second "for" block to:</p>

```<code>for (i = 1; i < a.Length; i++)
{
    k = a[i];
    for (j = i - 1; j >= 0 && a[j] > k; j--)
    {
        a[j + 1] = a[j];
    }
    a[j + 1] = k;
}
</code>```

Title: C# and negative array indices

Body:
I'm having a problem with getting this code (from Rosetta Code) to work as part of a greater Windows Form Project:

It's a plain old insertion sort. Where it's going wrong is the bit involving the second for loop (The numbers generate just fine), in the sorting part of it. To me within a couple of iterations of the loop then j will be into negative figures and whilst other languages such as Javascript and Pascal don't seem to mind this...C# isn't happy.

        private void button3_Click(object sender, EventArgs e)
        {

            int i, j, k;
            int[] a = new int[12];
            Random randomObject = new Random();
            ClearOutputs(); // this is an event which just clears the
               text
            from the text boxes.
            //Generate some random numbers
            for (i = 0; i < a.Length; i++)
            {
                a[i] = randomObject.Next(1, 1000);
                textBox1.AppendText(a[i].ToString() + "\n");
            }

            for (i = 1; i <= a.Length; i++)
            {
                k = a[i];
   //*******************
                for (j = i; j > 0 & k < a[j - 1]; j--)
                {
                    a[j] = a[j - 1];
                    a[j] = k;
                }
            }
    // ***************
            //Display them...it never executes this part.
            for (i = 0; i < a.Length; i++)
            {
                textBox2.AppendText(a[i].ToString() + "\n");
            }
        }

The longer term fix would be for me to understand the coding of the algorithm...and then fix it for myself, but if anyone could point me in the right direction...I've tried setting the 'for' loop at a higher initial value and yet still got the same "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" Any help would be greatly appreciated.

Body:
Following the provided Rosetta Code algorithm, you should change the second "for" block to:

for (i = 1; i < a.Length; i++)
{
    k = a[i];
    for (j = i - 1; j >= 0 && a[j] > k; j--)
    {
        a[j + 1] = a[j];
    }
    a[j + 1] = k;
}


问:
How to do Azure Video Watermarking / Overlay
Can anyone please guide me, step by step how to watermark/Overlay a video in Azure as I am new to Azure. If Possible please guide me with a tutorial or Video tutorial for the same. I have uploaded a .mp4 video in Azure and streamed it and able to view it in azure media player. Please guide me for watermarking or overlaying a video in azure.

Also I need to understand, azure is providing watermarking / overlay as a service so is there a way to do water marking directly with an Azure interface without visual studio C# coding.

Thanks in advance..

答:
Do you need to overlay an image onto a video? Or do you want to overlay a video over another video? For the former case, the image will have to overlaid on the input video during the encoding process. There is a basic example documented here. In that example, the output contains a single MP4 at 640x360 resolution, which is sufficient for delivery via progressive download. Since you need to stream your video, you should update the Codecs section in that example with additional video bitrates - such as the one showed here.

You also mention needing to do this without writing code. If you have a PC, then you can install and run AMS Explorer (https://aka.ms/amse). Browse to the input video you want to process, hit "Ctl+R" and you will see tabs to specify the encoding settings, and others for advanced features including overlays.


问:
What are the consequences of renaming a branch in TFS 2012?
I've read in many places that renaming a branch is rather problematic in TFS 2010 : you may lose the history of the branch you just renamed ( as seen in this article or in this SO question )

I cannot find any mention of those problems in TFS 2012. Are there any consequences I should be aware of before renaming a branch in TFS 2012 ?

答:
You can do it, but depends what situation you're in. For my situation, I have the following structure:

```<code>Development
   ProjectX
      ProjectY
Main
Release
</code>```

ProjectX is getting released sooner than ProjectY and it was merged to Development-->Main a week ago. Now, the name ProjectX isn't relevant anymore and also, there's a new project starting with a name ProjectZ so, I'm going to rename ProjectY to ProjectZ and rename ProjectX to ProjectY.

Both X, Y and Z are to be merged fully once they move to the standard release cycle so I don't have to worry about merging piece by piece.

Body:
You can do it, but depends what situation you're in. For my situation, I have the following structure:

Development
   ProjectX
      ProjectY
Main
Release

ProjectX is getting released sooner than ProjectY and it was merged to Development-->Main a week ago. Now, the name ProjectX isn't relevant anymore and also, there's a new project starting with a name ProjectZ so, I'm going to rename ProjectY to ProjectZ and rename ProjectX to ProjectY.

Both X, Y and Z are to be merged fully once they move to the standard release cycle so I don't have to worry about merging piece by piece.


问:
Convert Whole Digit to Date Format
I am trying to convert the Day column to a standard date format. 1 for Nov 1 (current month), 2 for Nov 2, and so on. Would be nice if the formula will display the current month. The format for the Day column is in general.

答:
Alternately, use =A2+43039 and format cells as Custom: d-mmm

Also possible to use =A2+"10/31/2017" to make it clearer what you're doing in the formula.

However, if you want it to update with whatever the current month and year is, Ralph's answer is probably best.

Title: Convert Whole Digit to Date Format


问:
How to upload my files to another server using multer in nodejs?
```<code>var storage =   multer.diskStorage({
              destination: function (req, file, callback) {

                callback(null, '/var/www/html');

              },
              filename: function (req, file, callback) {
              //console.log(file);return;
                if (file.mimetype == 'audio/mp3' || file.mimetype == 'audio/wav') {
                    var w = file.originalname;
                    var f = x.substr(0, x.lastIndexOf('.'));
                    callback(null, Date.now()+'-'+w);
                 }else{

                    var result = new sResultSh.commandResult("Failed","404");
                    onComplete(result);
                }
              },

            });
var upload = multer({ storage: storage}).any();
               upload(req, res, function (err) {
                if(err){
                    var resultErr =[];
                    resultErr.push(err);
                    var result = new sResultSh.commandResult("Failed","404",resultErr);
                    onComplete(result);

                }
                else{
                  var result = new sResultSh.commandResult("Success","200",);
                    onComplete(result);
                }
               })
</code>```

Above is my code and i need to upload my file to 195.158.1.45/var/www/html..
How to do this in nodejs?
my file upload is successful in my local system but i need to upload my file to another server ?
help?

答:
Uploading Files to remote server using multer is not possible directly, But we can play around with  multer-sftp, scp, ssh techniques in node js

Check this answers using multer-sftp and scp2

Body:
var storage =   multer.diskStorage({
              destination: function (req, file, callback) {

                callback(null, '/var/www/html');

              },
              filename: function (req, file, callback) {
              //console.log(file);return;
                if (file.mimetype == 'audio/mp3' || file.mimetype == 'audio/wav') {
                    var w = file.originalname;
                    var f = x.substr(0, x.lastIndexOf('.'));
                    callback(null, Date.now()+'-'+w);
                 }else{

                    var result = new sResultSh.commandResult("Failed","404");
                    onComplete(result);
                }
              },

            });
var upload = multer({ storage: storage}).any();
               upload(req, res, function (err) {
                if(err){
                    var resultErr =[];
                    resultErr.push(err);
                    var result = new sResultSh.commandResult("Failed","404",resultErr);
                    onComplete(result);

                }
                else{
                  var result = new sResultSh.commandResult("Success","200",);
                    onComplete(result);
                }
               })

Above is my code and i need to upload my file to 195.158.1.45/var/www/html..
How to do this in nodejs?
my file upload is successful in my local system but i need to upload my file to another server ?
help?


问:
Java-Swing: A problem using layout managers!
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

```<code>scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();
</code>```

答: Following @Michael Borgwardt's suggestion to let the list grow, you can use setVisibleRowCount() to produce a convenient initial panel size. If necessary, you can also examine the Dimension returned by getPreferredScrollableViewportSize(), which "computes the size of viewport needed to display visibleRowCount rows."

ContentLicense: CC BY-SA 2.5

Body:
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();


问:
How to use an iOS device as an iBeacon in iOS?
I am new to beacon integration. using code to get the UUID of the iPhone beacon(transmitter).
initially, I wrote below code to get UUID of iPhone to act as a beacon

```<code>let uuidString = UIDevice.current.identifierForVendor?.uuidString
print("UUID == \(uuidString)")
</code>```

UUID: F2830580-4E97-4098-B01A-99D49BB69EF1

```<code>var locationManager: CLLocationManager?
var myBeaconRegion: CLBeaconRegion?
var peripheral: CBPeripheral?
var manager: CBCentralManager?
var peripheralManager: CBPeripheralManager?

override func viewDidLoad(){

    super.viewDidLoad()
    locationManager = CLLocationManager()
    locationManager?.delegate = self
    locationManager?.distanceFilter = kCLDistanceFilterNone
    locationManager?.desiredAccuracy = kCLLocationAccuracyBest
    locationManager?.requestAlwaysAuthorization()
    locationManager?.requestWhenInUseAuthorization()
    peripheralManager = CBPeripheralManager(delegate: self as
    CBPeripheralManagerDelegate, queue: nil, options: nil)

    let uuid = UUID(uuidString: "F2830580-4E97-4098-B01A-99D49BB69EF1")

    myBeaconRegion = CLBeaconRegion(proximityUUID: uuid!,identifier: "iBeacon")

    myBeaconRegion?.notifyOnEntry = true
    myBeaconRegion?.notifyOnExit = true
    myBeaconRegion?.notifyEntryStateOnDisplay = true
    manager = CBCentralManager(delegate: self as? CBCentralManagerDelegate, queue: nil)
    locationManager?.startMonitoring(for: myBeaconRegion!)
    locationManager?.startRangingBeacons(in: myBeaconRegion!)
    locationManager?.pausesLocationUpdatesAutomatically = false
    locationManager?.startUpdatingLocation()

}
</code>```

Using delegate method to get the detected beacon

```<code>func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion)
{

  //  let value = region.major  as? NSNumber
   beaconLabel.text = "Beacon not found!"
    let foundBeacon = beacons.first as? CLBeacon
    print("foundBeacon == \(foundBeacon)")
 guard let  discoveredBeacon = beacons.first?.proximity else {
 print("beacon not found")
 return
 }

    let proxyValue = foundBeacon?.accuracy
    beaconDistanceLabel.text = String(describing: proxyValue!)
 let background:UIColor = {

 switch discoveredBeacon {
 case .immediate:
    beaconLabel.text = "Immediate!"
    return  UIColor.green
 case .near:
    beaconLabel.text = "Near!"
    return  UIColor.orange
 case .far:
    beaconLabel.text = "Far!"
    return  UIColor.red
 case .unknown:
    beaconLabel.text = "Unknown!"
    return  UIColor.magenta
 }
 }()
 view.backgroundColor = background

}
</code>```

delegate methods are calling but CLBeacon not detecting iPhone device.

Even i tried with
https://developer.apple.com/documentation/corelocation/turning_an_ios_device_into_an_ibeacon but no results.

Any help will be appreciated..

答:
u can create estimate beacons in any iOS device to make your device as transmitter..

Make use of beacon simulator app and create beacons manually.
Now run your app and monitor the beacon range..hardcode the same beacon I'd in code for testing..

Body:
I am new to beacon integration. using code to get the UUID of the iPhone beacon(transmitter).
initially, I wrote below code to get UUID of iPhone to act as a beacon

let uuidString = UIDevice.current.identifierForVendor?.uuidString
print("UUID == \(uuidString)")

UUID: F2830580-4E97-4098-B01A-99D49BB69EF1

var locationManager: CLLocationManager?
var myBeaconRegion: CLBeaconRegion?
var peripheral: CBPeripheral?
var manager: CBCentralManager?
var peripheralManager: CBPeripheralManager?

override func viewDidLoad(){

    super.viewDidLoad()
    locationManager = CLLocationManager()
    locationManager?.delegate = self
    locationManager?.distanceFilter = kCLDistanceFilterNone
    locationManager?.desiredAccuracy = kCLLocationAccuracyBest
    locationManager?.requestAlwaysAuthorization()
    locationManager?.requestWhenInUseAuthorization()
    peripheralManager = CBPeripheralManager(delegate: self as
    CBPeripheralManagerDelegate, queue: nil, options: nil)

    let uuid = UUID(uuidString: "F2830580-4E97-4098-B01A-99D49BB69EF1")

    myBeaconRegion = CLBeaconRegion(proximityUUID: uuid!,identifier: "iBeacon")

    myBeaconRegion?.notifyOnEntry = true
    myBeaconRegion?.notifyOnExit = true
    myBeaconRegion?.notifyEntryStateOnDisplay = true
    manager = CBCentralManager(delegate: self as? CBCentralManagerDelegate, queue: nil)
    locationManager?.startMonitoring(for: myBeaconRegion!)
    locationManager?.startRangingBeacons(in: myBeaconRegion!)
    locationManager?.pausesLocationUpdatesAutomatically = false
    locationManager?.startUpdatingLocation()

}

Using delegate method to get the detected beacon

func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion)
{

  //  let value = region.major  as? NSNumber
   beaconLabel.text = "Beacon not found!"
    let foundBeacon = beacons.first as? CLBeacon
    print("foundBeacon == \(foundBeacon)")
 guard let  discoveredBeacon = beacons.first?.proximity else {
 print("beacon not found")
 return
 }

    let proxyValue = foundBeacon?.accuracy
    beaconDistanceLabel.text = String(describing: proxyValue!)
 let background:UIColor = {

 switch discoveredBeacon {
 case .immediate:
    beaconLabel.text = "Immediate!"
    return  UIColor.green
 case .near:
    beaconLabel.text = "Near!"
    return  UIColor.orange
 case .far:
    beaconLabel.text = "Far!"
    return  UIColor.red
 case .unknown:
    beaconLabel.text = "Unknown!"
    return  UIColor.magenta
 }
 }()
 view.backgroundColor = background

}

delegate methods are calling but CLBeacon not detecting iPhone device.

Even i tried with
https://developer.apple.com/documentation/corelocation/turning_an_ios_device_into_an_ibeacon but no results.

Any help will be appreciated..


问:
Deleting all content down from the second horizontal line in a document
I'm trying to create a script to delete all text/content downwards from a page. Below you can see the current document.

Currently, I have the script set-up so that it deletes everything down and including from a text of, "STARTHERE". However, I want it to delete down from the second horizontal line in the image, however, not including the line.

Any ideas on how to delete down from the second horizontal line?

What does deleteText startOffset and endOffsetInclusive actually mean? Is it like a line number or?

Previous Script:

```<code>function removeText() {
    var body = DocumentApp.getActiveDocument().getBody();
    var rangeElement = body.editAsText();
    var start = "STARTHERE";
    var end = "ENDHERE";
    var rangeElement1 = DocumentApp.getActiveDocument().getBody().findText(start);
    var rangeElement2 = DocumentApp.getActiveDocument().getBody().findText(end);
    if (rangeElement1.isPartial()) {
       var startOffset = rangeElement1.getStartOffset();
       var endOffset = rangeElement2.getEndOffsetInclusive();
       rangeElement1.getElement().asText().deleteText(startOffset,endOffset);
    }
}
</code>```

答:
You'll need to change your approach completely, because findText only finds text, and a horizontal line is not text; it is a special type of document element, HorizontalRule.

(Since you asked: startOffset and endOffsetInclusive are character counts within an element; e.g., if the text "red" is found in a paragraph that consists of "A big red dog", then startOffset is 6 and endOffset is 9. None of this helps here)

Here is my approach: loop over the Paragraph elements, looking for those that contain a HorizontalRule element (with findElement method). Once we found two such paragraphs, delete all subsequent ones.

There is a catch in that Apps Script can't delete the last paragraph of a document; for this reason I append empty paragraph ahead of time, and do not delete it.

```<code>function removeAfterSecondLine() {
  var body = DocumentApp.getActiveDocument().getBody();
  body.appendParagraph('');
  var para = body.getParagraphs();
  var ruleCount = 0;
  for (var i = 0; i < para.length - 1; i++) {
    if (ruleCount >= 2) {
      body.removeChild(para[i]);
    }
    else if (para[i].findElement(DocumentApp.ElementType.HORIZONTAL_RULE)) {
      ruleCount++;
    }
  }
}
</code>```

Body:
I'm trying to create a script to delete all text/content downwards from a page. Below you can see the current document.

Currently, I have the script set-up so that it deletes everything down and including from a text of, "STARTHERE". However, I want it to delete down from the second horizontal line in the image, however, not including the line.

Any ideas on how to delete down from the second horizontal line?

What does deleteText startOffset and endOffsetInclusive actually mean? Is it like a line number or?

Previous Script:

function removeText() {
    var body = DocumentApp.getActiveDocument().getBody();
    var rangeElement = body.editAsText();
    var start = "STARTHERE";
    var end = "ENDHERE";
    var rangeElement1 = DocumentApp.getActiveDocument().getBody().findText(start);
    var rangeElement2 = DocumentApp.getActiveDocument().getBody().findText(end);
    if (rangeElement1.isPartial()) {
       var startOffset = rangeElement1.getStartOffset();
       var endOffset = rangeElement2.getEndOffsetInclusive();
       rangeElement1.getElement().asText().deleteText(startOffset,endOffset);
    }
}

Body:
You'll need to change your approach completely, because findText only finds text, and a horizontal line is not text; it is a special type of document element, HorizontalRule.

(Since you asked: startOffset and endOffsetInclusive are character counts within an element; e.g., if the text "red" is found in a paragraph that consists of "A big red dog", then startOffset is 6 and endOffset is 9. None of this helps here)

Here is my approach: loop over the Paragraph elements, looking for those that contain a HorizontalRule element (with findElement method). Once we found two such paragraphs, delete all subsequent ones.

There is a catch in that Apps Script can't delete the last paragraph of a document; for this reason I append empty paragraph ahead of time, and do not delete it.

function removeAfterSecondLine() {
  var body = DocumentApp.getActiveDocument().getBody();
  body.appendParagraph('');
  var para = body.getParagraphs();
  var ruleCount = 0;
  for (var i = 0; i < para.length - 1; i++) {
    if (ruleCount >= 2) {
      body.removeChild(para[i]);
    }
    else if (para[i].findElement(DocumentApp.ElementType.HORIZONTAL_RULE)) {
      ruleCount++;
    }
  }
}


问:
Powershell script to dynamically replace text in console as it is displayed
Is it possible to use powershell scripting to scan all console output in a powershell window, before it is outputted, and replace certain words with other words so that the altered output is displayed in the console?

My use case is that if I replace null with an ANSI colored null, the special chars are escaped on display. I want to unescape them on display to show in color.

For example;
\pset null '[91m[0m'

displays null in the console as
\x1B[91m\x1B[0m

So I would wish replace all instances of this with a delicious ANSI colored null everywhere in the console window.

Thanks in advance

答:
I don't know about scanning output, but you can always "-replace" anything that might generate output:

e.g.

{write-host "Hey, this is stuff"} -replace "stuff","things"

[System.Reflection.Assembly]::LoadFile("C:\windows\assembly\GAC_64\System.Data\2.0.0.0__b77a5c561934e089\System.Data.dll") -replace "4.0.0.0","3.1415"


问:
Apache tomcat maven plugin compiling on non-existing version of Java
I am trying to integrate my maven project with Tomcat server 8.5. Without integration, everything works fine. I replaced maven-compiler-plugin with tomcat7-maven-plugin in pom.xml and did other configurations. After that mvn install, mvn clean install and mvn tomcat7:deploy everything is failing with below exception.

```<code>TestServiceCSV.java:[345,48] strings in switch are not supported in -source 1.5
  (use -source 7 or higher to enable strings in switch)

    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213)
</code>```

So clearly the compilation is being performed using java 1.5, whereas my jdk version is 1.8.0_144. Additional details below:

```<code>>mvn -version
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T02:58:13-05:00)
Maven home: C:\Maven\apache-maven-3.5.2\bin\..
Java version: 1.8.0_144, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_144\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

>java -version
java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)
</code>```

I have set the Installed JRE in Eclipse as the JDK. Also the build path for my project reflects same.

```<code>>echo $MAVEN_HOME
C:\Maven\apache-maven-3.5.2

>echo $JAVA_HOME
C:\Program Files\Java\jdk1.8.0_144
</code>```

Tomcat version 8.5.23

POM.xml entry

```<code><plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://localhost:8080/manager/html</url>
<server>TomcatServer</server>
<username>admin</username>
<password>xxxx</password>
</configuration>
</plugin>
</code>```

Why could the compilation is being performed on 1.5 instead of the actual version?

答: Default source level of the compiler plugin is 1.5. The compiler:compile goal is bound to the compile phase of the default lifecycle. You always have to set the source and target levels if you want to use advanced language features from release 6 on.

Body:
I am trying to integrate my maven project with Tomcat server 8.5. Without integration, everything works fine. I replaced maven-compiler-plugin with tomcat7-maven-plugin in pom.xml and did other configurations. After that mvn install, mvn clean install and mvn tomcat7:deploy everything is failing with below exception.

TestServiceCSV.java:[345,48] strings in switch are not supported in -source 1.5
  (use -source 7 or higher to enable strings in switch)

    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213)

So clearly the compilation is being performed using java 1.5, whereas my jdk version is 1.8.0_144. Additional details below:

>mvn -version
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T02:58:13-05:00)
Maven home: C:\Maven\apache-maven-3.5.2\bin\..
Java version: 1.8.0_144, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_144\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

>java -version
java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)

I have set the Installed JRE in Eclipse as the JDK. Also the build path for my project reflects same.

>echo $MAVEN_HOME
C:\Maven\apache-maven-3.5.2

>echo $JAVA_HOME
C:\Program Files\Java\jdk1.8.0_144

Tomcat version 8.5.23

POM.xml entry

<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://localhost:8080/manager/html</url>
<server>TomcatServer</server>
<username>admin</username>
<password>xxxx</password>
</configuration>
</plugin>

Why could the compilation is being performed on 1.5 instead of the actual version?


问:
Can we define a "function declaration" also as a "function statement"?
This question born considering the function declarations VS function expressions.

We clearly know that a function declaration have this form

```<code>function foo() {
    var a = 3;
    console.log( a );
}
</code>```

while a function expression can have this form (appearing like what is known like Immediately invoked function expression)

```<code>(function foo() {
    var a = 3;
    console.log( a );
})()
</code>```

Looking at the immediately invoked function expression I can just notice the first function (the one used in the function declaration) wrapped in parethesis.

Now, the point is: I know that the grouping operator (most commonly known as "the parethesis" () ) can only contain an expression. If this is true I can't say that the function declaration is also a function statement (because it would be like saying that I have wrapped in parenthesis a statement...).

So, can you give some help, I'm a little confused.
A function declaration is also a function statement? If yes, the function wrapped in parenthesis is a statement or what?

I must clarify that I'm not asking about the difference beetwen a function declaration and a function expression. If I mention them and their differences is just to describe my question that is: a "function declaration" is also a "function statement"?

答:
While the syntax of a function expression is the same as a function declaration, they're not the same thing.

The scope of the name used in function declarations is different from named function expressions. When you write:

```<code>function foo() {
    var a = 3;
    console.log( a );
}
</code>```

the scope of foo is the enclosing function (or the global environment if this is at top level).

When you write:

```<code>(function foo() {
    var a = 3;
    console.log( a );
})
</code>```

the scope of foo is just the body of the function.

The parser determines whether it's a function expression or declaration based on the context. Since a statement can't be inside parentheses, putting parentheses around it forces it to be an expression.

Body:
This question born considering the function declarations VS function expressions.

We clearly know that a function declaration have this form

function foo() {
    var a = 3;
    console.log( a );
}

while a function expression can have this form (appearing like what is known like Immediately invoked function expression)

(function foo() {
    var a = 3;
    console.log( a );
})()

Looking at the immediately invoked function expression I can just notice the first function (the one used in the function declaration) wrapped in parethesis.

Now, the point is: I know that the grouping operator (most commonly known as "the parethesis" () ) can only contain an expression. If this is true I can't say that the function declaration is also a function statement (because it would be like saying that I have wrapped in parenthesis a statement...).

So, can you give some help, I'm a little confused.
A function declaration is also a function statement? If yes, the function wrapped in parenthesis is a statement or what?

I must clarify that I'm not asking about the difference beetwen a function declaration and a function expression. If I mention them and their differences is just to describe my question that is: a "function declaration" is also a "function statement"?

Body:
While the syntax of a function expression is the same as a function declaration, they're not the same thing.

The scope of the name used in function declarations is different from named function expressions. When you write:

function foo() {
    var a = 3;
    console.log( a );
}

the scope of foo is the enclosing function (or the global environment if this is at top level).

When you write:

(function foo() {
    var a = 3;
    console.log( a );
})

the scope of foo is just the body of the function.

The parser determines whether it's a function expression or declaration based on the context. Since a statement can't be inside parentheses, putting parentheses around it forces it to be an expression.


问:
How to make a Menu that goes from the header to the footer?
So, I am learning how to code HTML5, CSS3, and all that good stuff. But I have an issue the book doesn't solve. As you may be able to see, The Nav area doesn't go from the header to the footer. I was hoping someone could help me understand how to get it to go from the header to the footer. Maybe it's just a simple padding. But I don't wanna mess up the layout. Hope I am not asking a stupid question.

/*HEADER*/

header {
  border: 3px solid black;
}

/*BODY*/

nav {
  float: left;
  clear: both;
  width: 20%;
  border: 3px solid black;
}

section {
  float: left;
  width: 75%;
  padding-left: 1em;
  border: 3px solid black;
}
article {
  float: left;
  width: 75%;
  padding-left: 1em;
  border: 3px solid black;
}

/*FOOTER*/

footer {
  text-align: center;
  clear: both;
  border: 3px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html lang="en-US">
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet"
          type="text/css"
          href="semanticTags.css"/>
    <title>
      Semantic Tags
    </title>
    <body>
      <header>
        <h1>This is my header</h1>
      </header>

      <nav>
        <h2>Navigation</h2>
        <ul>
          <li>Google</li>
          <li>Bing</li>
          <li>Yahoo</li>
          <li>AOL</li>
          <li>Facebook</li>
        </ul>
      </nav>

      <section id="1">
        <h2>
          Section 1
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <section id="2">
        <h2>
          Section 2
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <article>
        <h2>
          Article
        </h2>
        <p>
          Article Body
        </p>
      </article>

      <footer>
        <h2>footer</h2>
        <address>
          DreamRiskers<br>

            email@gmail.com

        </address>
      </footer>

    </body>
  </head>
</html></code>```

答:
use position:fixed; css property set nav top to bottom. Below code will help you to get expected output.

/*HEADER*/

header {
  border: 3px solid black;
 margin-left:21%;
}

/*BODY*/

nav {
  float: left;
  clear: both;
  width: 20%;
  border: 3px solid black;
 position:fixed;
 top:0;
 bottom:0;
 height:100%;
}

section {
  float: left;
  width: 75%;
  margin-left: 21%;
  border: 3px solid black;
}
article {
  float: left;
  width: 75%;
  margin-left: 21%;
  border: 3px solid black;
}

/*FOOTER*/

footer {
  text-align: center;
  clear: both;
  border: 3px solid black;
 margin-left:21%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>      <header>
        <h1>This is my header</h1>
      </header>

      <nav>
        <h2>Navigation</h2>
        <ul>
          <li>Google</li>
          <li>Bing</li>
          <li>Yahoo</li>
          <li>AOL</li>
          <li>Facebook</li>
        </ul>
      </nav>

      <section id="1">
        <h2>
          Section 1
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <section id="2">
        <h2>
          Section 2
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <article>
        <h2>
          Article
        </h2>
        <p>
          Article Body
        </p>
      </article>

      <footer>
        <h2>footer</h2>
        <address>
          DreamRiskers<br>

            email@gmail.com

        </address>
      </footer>

    </code>```

Body:
So, I am learning how to code HTML5, CSS3, and all that good stuff. But I have an issue the book doesn't solve. As you may be able to see, The Nav area doesn't go from the header to the footer. I was hoping someone could help me understand how to get it to go from the header to the footer. Maybe it's just a simple padding. But I don't wanna mess up the layout. Hope I am not asking a stupid question.

/*HEADER*/

header {
  border: 3px solid black;
}

/*BODY*/

nav {
  float: left;
  clear: both;
  width: 20%;
  border: 3px solid black;
}

section {
  float: left;
  width: 75%;
  padding-left: 1em;
  border: 3px solid black;
}
article {
  float: left;
  width: 75%;
  padding-left: 1em;
  border: 3px solid black;
}

/*FOOTER*/

footer {
  text-align: center;
  clear: both;
  border: 3px solid black;
}

<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <link rel="stylesheet"
          type="text/css"
          href="semanticTags.css"/>
    <title>
      Semantic Tags
    </title>

This is my header

Navigation

Google

Bing

Yahoo

AOL

Facebook

          Section 1

          Section Body

          Section 2

          Section Body

          Article

          Article Body

footer

        <address>
          DreamRiskers

            email@gmail.com

        </address>

Body:
use position:fixed; css property set nav top to bottom. Below code will help you to get expected output.

/*HEADER*/

header {
  border: 3px solid black;
 margin-left:21%;
}

/*BODY*/

nav {
  float: left;
  clear: both;
  width: 20%;
  border: 3px solid black;
 position:fixed;
 top:0;
 bottom:0;
 height:100%;
}

section {
  float: left;
  width: 75%;
  margin-left: 21%;
  border: 3px solid black;
}
article {
  float: left;
  width: 75%;
  margin-left: 21%;
  border: 3px solid black;
}

/*FOOTER*/

footer {
  text-align: center;
  clear: both;
  border: 3px solid black;
 margin-left:21%;
}

      <header>
        <h1>This is my header</h1>
      </header>

      <nav>
        <h2>Navigation</h2>
        <ul>
          <li><a href="google.com">Google</a></li>
          <li><a href="Bing.com">Bing</a></li>
          <li><a href="Yahoo.com">Yahoo</a></li>
          <li><a href="Aol.com">AOL</a></li>
          <li><a href="Facebook.com">Facebook</a></li>
        </ul>
      </nav>

      <section id="1">
        <h2>
          Section 1
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <section id="2">
        <h2>
          Section 2
        </h2>
        <p>
          Section Body
        </p>
      </section>

      <article>
        <h2>
          Article
        </h2>
        <p>
          Article Body
        </p>
      </article>

      <footer>
        <h2>footer</h2>
        <address>
          DreamRiskers<br>
          <a href="mailto:email@gmail.com">
            email@gmail.com
          </a>
        </address>
      </footer>


问:
TempData not displaying success message Asp.net MVC
I'm using tempdata to give user a "success message" before redirection however at the moment it just redirect without giving the message. Maybe I have it at wrong place, I tried moving it to different parts of the code but it still didn't work.

Index View

```<code>    @{
    ViewBag.Title = "Home Page";
}
@if (TempData["notice"] != null)
{
    <p>@TempData["notice"]</p>
}

<div>
    <img src="~/Content/Images/TWO_Logo.jpg" alt="Logo" />
</div>
<div class="jumbotron">
    <h1></h1>
    <p class="lead">
</div>
</code>```

Home Controller

```<code>namespace com.twcl.it.isms.Controllers
{
    [Authorize(Roles = "Administrator, Issue, Transaction_Edit, Print")]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
TempData["notice"] = "Your item(s) successfully requested";
            ViewBag.SuccessMessage = TempData["SuccesMeassge"];

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult Logoff()
        {
            HttpContext.Session.Abandon();
            Response.Redirect("http://192.168.5.127");
            //Response.StatusCode = 401;
            //Response.End();
            //////throw new HttpException(401, "Please close your browser to complete Log Off");
            return View("Index");
        }
</code>```

答:
In Index Action method just add TempData.Keep("notice"); which will keep tempdata available for next hop.

```<code>public ActionResult Index()
{
    TempData.Keep("notice");
    ViewBag.SuccessMessage = TempData["SuccesMeassge"];
    return View();
}
</code>```

On View to display alert message

```<code>@if (TempData.ContainsKey("notice"))
{
    <script type="text/javascript">
        alert(@TempData["notice"]);
  </script>
}
</code>```

Details about keep and peek.
when-to-use-keep-vs-peek-in-asp-net-mvc

Body:
I'm using tempdata to give user a "success message" before redirection however at the moment it just redirect without giving the message. Maybe I have it at wrong place, I tried moving it to different parts of the code but it still didn't work.

Index View

    @{
    ViewBag.Title = "Home Page";
}
@if (TempData["notice"] != null)
{

@TempData["notice"]

}

Home Controller

namespace com.twcl.it.isms.Controllers
{
    [Authorize(Roles = "Administrator, Issue, Transaction_Edit, Print")]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
TempData["notice"] = "Your item(s) successfully requested";
            ViewBag.SuccessMessage = TempData["SuccesMeassge"];

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult Logoff()
        {
            HttpContext.Session.Abandon();
            Response.Redirect("http://192.168.5.127");
            //Response.StatusCode = 401;
            //Response.End();
            //////throw new HttpException(401, "Please close your browser to complete Log Off");
            return View("Index");
        }

Body:
In Index Action method just add TempData.Keep("notice"); which will keep tempdata available for next hop.

public ActionResult Index()
{
    TempData.Keep("notice");
    ViewBag.SuccessMessage = TempData["SuccesMeassge"];
    return View();
}

On View to display alert message

@if (TempData.ContainsKey("notice"))
{
    <script type="text/javascript">
        alert(@TempData["notice"]);
  </script>
}

Details about keep and peek.
when-to-use-keep-vs-peek-in-asp-net-mvc


问:
Is it possible in MySQL to search a table for where a column only contains 1 comma?
I have this column in a table which is comma delimited to separate the values.

Here's the sample data:

```<code>2003,2004
2003,2005
2003,2006
2003,2004,2005
2003,2007
</code>```

I want to get all data that contains only 1 comma.

I've been playing around with the '%' and '_' wildcards, but I can't seem to get the results I need.

SELECT column FROM table WHERE column like '%_,%'

答:
Maybe another solution is to use regular expression in your case it can look like this ^[0-9]{4},[0-9]{4}$ :

```<code>SELECT * FROM MyTable WHERE ColName REGEXP '^[0-9]{4},[0-9]{4}$'
</code>```

Or if you want all non comma one or more time :

```<code>SELECT * FROM MyTable WHERE ColName REGEXP '^[^,]*,[^,]*$'
</code>```

Body:
I have this column in a table which is comma delimited to separate the values.

Here's the sample data:

2003,2004
2003,2005
2003,2006
2003,2004,2005
2003,2007

I want to get all data that contains only 1 comma.

I've been playing around with the '%' and '_' wildcards, but I can't seem to get the results I need.

SELECT column FROM table WHERE column like '%_,%'

Body:
Maybe another solution is to use regular expression in your case it can look like this ^[0-9]{4},[0-9]{4}$ :

SELECT * FROM MyTable WHERE ColName REGEXP '^[0-9]{4},[0-9]{4}$'

Or if you want all non comma one or more time :

SELECT * FROM MyTable WHERE ColName REGEXP '^[^,]*,[^,]*$'


问:
Wrong week number using DATEPART in SQL Server
I've got the problem that

```<code>select datepart(ww, '20100208')
</code>```

is returning as result week 7 in SQL Server 2000. But 08.02.2010 should be week 6 according to the ISO 8601 specification! This is causing problems in delivery week calculations.

What should I do to get week number values according to ISO 8601?

答:
One easy way to do this is to use isowk instead  of wk as shown here:

```<code>select datepart(isowk, '2010-02-08');
</code>```

Like @MicSim and @AdaTheDev mentioned, this will only work in newer versions (>=2008).

Body:
I've got the problem that

select datepart(ww, '20100208')

is returning as result week 7 in SQL Server 2000. But 08.02.2010 should be week 6 according to the ISO 8601 specification! This is causing problems in delivery week calculations.

What should I do to get week number values according to ISO 8601?

Body:
One easy way to do this is to use isowk instead  of wk as shown here:

select datepart(isowk, '2010-02-08');

Like @MicSim and @AdaTheDev mentioned, this will only work in newer versions (>=2008).


问:
I have a really slow page, how can I figure out of it's the M, V, or C? What kind of timing mechanism would be accurate?
The controller makes a few calls to the model, then it returns some data to the view. The view actually, sadly, (it's not my fault), contains a ton of inline queries and more calls to the Model, yeah I know. Anyways I am tasked with optimizing this really slow page and I am trying to figure out how I can tell which thing is taking the most time. I was just going to put a timer at the start and the end of each 'thing' that the page does and output them to a log with the line number or something. But not sure what the most accurate way to do this is.

```<code>//in controller
StartTimer();
var something = model.something.getsomething(someID);
StopTimerAndLog(3); //line number

<!-- in view -->
<%StartTimer();
var something = model.somethingelse.getanotherthing(someotherID);
StopTimerAndLog(2);%>
</code>```

so on and so forth...

Then the question remains about what timing mechanism to use, I'm sure there must be a question about this already. But I don't know if my situation makes anything unique or not... any ideas?

答:
If you really want to measure like this, I would use the StopWatch class:

```<code>var watch = new StopWatch();
watch.Start();
var something = model.something.getSomething(someID);
watch.Stop();

var time = watch.Elapsed;
</code>```

If you want something really detailed and without writing any extra code...I would suggest the use of a Profiler. It will give you details about exactly what is taking so long and why. My personal favorite is RedGate's ANTS Performance Profiler.

Body:
The controller makes a few calls to the model, then it returns some data to the view. The view actually, sadly, (it's not my fault), contains a ton of inline queries and more calls to the Model, yeah I know. Anyways I am tasked with optimizing this really slow page and I am trying to figure out how I can tell which thing is taking the most time. I was just going to put a timer at the start and the end of each 'thing' that the page does and output them to a log with the line number or something. But not sure what the most accurate way to do this is.

//in controller
StartTimer();
var something = model.something.getsomething(someID);
StopTimerAndLog(3); //line number

<%StartTimer();
var something = model.somethingelse.getanotherthing(someotherID);
StopTimerAndLog(2);%>

so on and so forth...

Then the question remains about what timing mechanism to use, I'm sure there must be a question about this already. But I don't know if my situation makes anything unique or not... any ideas?

Body:
If you really want to measure like this, I would use the StopWatch class:

var watch = new StopWatch();
watch.Start();
var something = model.something.getSomething(someID);
watch.Stop();

var time = watch.Elapsed;

If you want something really detailed and without writing any extra code...I would suggest the use of a Profiler. It will give you details about exactly what is taking so long and why. My personal favorite is RedGate's ANTS Performance Profiler.


问:
Nested queries with aggregate functions Slick
I am building some SQL queries with Slick. I have this query with a few nested queries and I can not figure out how to combine this all into one.

My SQL query:

```<code>select count(*) from (

    select TOP 1 WITH TIES sum(c) cc, c1, c2 from (

    SELECT count(*) c, town_from c1, town_to c2 from trip
    where town_from>=town_to
    group by town_from, town_to
    union all
    SELECT count(*) c,town_to, town_from from trip
    where town_to>town_from
    group by town_from, town_to
    ) as t

    group by c1,c2
    order by cc desc

    ) as tt
</code>```

My unfinished version of this query with Slick:

```<code>val subquery1 = TripTable.table.filter(t => t.townFrom >= t.townTo)
      .groupBy(t => (t.townFrom, t.townTo))
      .map{ case ((townFrom, townTo), group) => (group.length ,townFrom, townTo)}
val subquery2 = TripTable.table.filter(t => t.townTo > t.townFrom)
      .groupBy(t => (t.townFrom, t.townTo))
      .map{ case ((townFrom, townTo), group) => (group.length ,townFrom, townTo)}

    val t = subquery1 union subquery2
val tt = t.map{ case subquery1 => (subquery1._1, subquery1._2, subquery1._3) }
              .groupBy{case (sub1, sub2, sub3) => (sub2, sub3)}
                  .map{ case ((sub1,sub2, sub3), group) => (group.map(_._1).sum.get, sub2, sub3)}
                      .sortBy{ case (sum, sub2, sub3) => sum}
                        .take(1)
db.run(tt.length.result)
</code>```

I would be very grateful for any kind of help!

答:
This query worked for me:</p>

```<code>val subquery1 = TripTable.table.filter(t => t.townFrom >= t.townTo)
      .groupBy(t => (t.townFrom, t.townTo))
        .map{ case ((townFrom, townTo), group) => (group.length, townFrom, townTo)}

    val subquery2 = TripTable.table.filter(t => t.townTo > t.townFrom)
      .groupBy(t => (t.townFrom, t.townTo))
        .map{ case ((townFrom, townTo), group) => (group.length, townFrom, townTo)}

    val t = subquery1 union subquery2
    val tt = t.map { case subquery1 => (subquery1._1, subquery1._2, subquery1._3) }
      .groupBy { case (sub1, sub2, sub3) => (sub2, sub3) }
      .map { case ((sub2, sub3), group) => (group.map(_._1).sum, sub2, sub3) }
      .sortBy { case (sum, sub2, sub3) => sum }
                            .take(1)
    println(tt.length.result.statements)
</code>```

Body:
I am building some SQL queries with Slick. I have this query with a few nested queries and I can not figure out how to combine this all into one.

My SQL query:

select count(*) from (

    select TOP 1 WITH TIES sum(c) cc, c1, c2 from (

    SELECT count(*) c, town_from c1, town_to c2 from trip
    where town_from>=town_to
    group by town_from, town_to
    union all
    SELECT count(*) c,town_to, town_from from trip
    where town_to>town_from
    group by town_from, town_to
    ) as t

    group by c1,c2
    order by cc desc

    ) as tt

My unfinished version of this query with Slick:

val subquery1 = TripTable.table.filter(t => t.townFrom >= t.townTo)
      .groupBy(t => (t.townFrom, t.townTo))
      .map{ case ((townFrom, townTo), group) => (group.length ,townFrom, townTo)}
val subquery2 = TripTable.table.filter(t => t.townTo > t.townFrom)
      .groupBy(t => (t.townFrom, t.townTo))
      .map{ case ((townFrom, townTo), group) => (group.length ,townFrom, townTo)}

    val t = subquery1 union subquery2
val tt = t.map{ case subquery1 => (subquery1._1, subquery1._2, subquery1._3) }
              .groupBy{case (sub1, sub2, sub3) => (sub2, sub3)}
                  .map{ case ((sub1,sub2, sub3), group) => (group.map(_._1).sum.get, sub2, sub3)}
                      .sortBy{ case (sum, sub2, sub3) => sum}
                        .take(1)
db.run(tt.length.result)

I would be very grateful for any kind of help!

Body:
This query worked for me:

val subquery1 = TripTable.table.filter(t => t.townFrom >= t.townTo)
      .groupBy(t => (t.townFrom, t.townTo))
        .map{ case ((townFrom, townTo), group) => (group.length, townFrom, townTo)}

    val subquery2 = TripTable.table.filter(t => t.townTo > t.townFrom)
      .groupBy(t => (t.townFrom, t.townTo))
        .map{ case ((townFrom, townTo), group) => (group.length, townFrom, townTo)}

    val t = subquery1 union subquery2
    val tt = t.map { case subquery1 => (subquery1._1, subquery1._2, subquery1._3) }
      .groupBy { case (sub1, sub2, sub3) => (sub2, sub3) }
      .map { case ((sub2, sub3), group) => (group.map(_._1).sum, sub2, sub3) }
      .sortBy { case (sum, sub2, sub3) => sum }
                            .take(1)
    println(tt.length.result.statements)


问:
split byte array into even and odd byte array and store in file
I am reading a .pst (File Structure) file byte by byte in a byte array, now i want to break the data into two parts like in even and odd, and store it in 2 other files one for even and one for odd  . Below is the code that i am stuck at

```<code>        byte[] array = File.ReadAllBytes("PST_Sample.pst");
        for (int index = 0; index < even.Length; index++)
        {

            //Console.WriteLine(index + " : " + array[index]);
            if ((array[index] % 2) == 0)
            {
                even[index] = array[index];
            }
            else
            {
                odd[index] = array[index];
            }
        }
</code>```

In FOR loop i have tried array.length, even.length nothing is working.

答:
Your test is wrong.  You are testing the bytes in the data, not the index.  It should be:</p>

```<code> for (int index = 0; index < array.Length; index++)
    {

        //Console.WriteLine(index + " : " + array[index]);
        if ((index % 2) == 0)
        {
            even[index/2] = array[index];
        }
        else
        {
            odd[(index - 1)/2] = array[index];
        }
    }
</code>```

Body:
I am reading a .pst (File Structure) file byte by byte in a byte array, now i want to break the data into two parts like in even and odd, and store it in 2 other files one for even and one for odd  . Below is the code that i am stuck at

        byte[] array = File.ReadAllBytes("PST_Sample.pst");
        for (int index = 0; index < even.Length; index++)
        {

            //Console.WriteLine(index + " : " + array[index]);
            if ((array[index] % 2) == 0)
            {
                even[index] = array[index];
            }
            else
            {
                odd[index] = array[index];
            }
        }

In FOR loop i have tried array.length, even.length nothing is working.

Body:
Your test is wrong.  You are testing the bytes in the data, not the index.  It should be:

 for (int index = 0; index < array.Length; index++)
    {

        //Console.WriteLine(index + " : " + array[index]);
        if ((index % 2) == 0)
        {
            even[index/2] = array[index];
        }
        else
        {
            odd[(index - 1)/2] = array[index];
        }
    }


问:
Removing INDIRECT from dynamic column selection
I have researched thoroughly before posting and still can't figure this out.

I currently have a file that uses an INDIRECT logic to gather information from one worksheet to a summary worksheet. The file works perfectly as is. But I'm trying to make it more efficient as right now calculating times are huge due to so much volatility.

In the data worksheet I have a lot of columns, each with a concept and an account number assigned to it.
So, for example:

```<code>                5014255   5324232     5566544
Name   Store    Salary     Taxes    Other Benefit     P1 Weight  P2 Weight
John   Main     222222     50000       30000            0.4        0.6
Jane   Annex    222224     50002       30004            0.3        0.7
</code>```

Then in the summary page, I use a SUMPRODUCT to gather the information per store per account and separating by period, like this as:

```<code>Store  Account     Concept           P1        P2
Main   5014255   Salary            88888.8  133333.2
Main   5324232   Taxes             20000.0   30000.0
Main   5566544   Other Benefit     12000.0   18000.0
Annex  5014255   Salary            66667.2  155556.8
Annex  5324232   Taxes             15000.6   35001.4
Annex  5566544   Other Benefit      9001.2   21002.8
</code>```

This of course is just a basic example. The real file has several more validations and several categories of weights that are used for different accounts. In order to pull the information I have the following formula.

```<code>    =IFNA(SUMPRODUCT(
   INDIRECT(INDEX("'Sheet1'!"&ADDRESS(6,COLUMN($A$5)+MATCH($N5,Sheet1!$1:$1,0)-1,4)&":"&SUBSTITUTE(ADDRESS(1,COLUMN($A$5)+MATCH($N5,Sheet1!$1:$1,0)-1,4),"1","")&$AU$1,1,1)),
    --(Sheet1!$C$6:$C$1754=2018),
    --(Sheet1!$J$6:$J$1754=$I5),
    IF($G5=1,Sheet1!$BN$6:$BN$1754,IF($F5=1,Sheet1!$BA$6:$BA$1754,Sheet1!$AN$6:$AN$1754))
    ),0)
</code>```

The important piece of code is:

```<code>INDIRECT(INDEX("'Sheet1'!"&ADDRESS(6,COLUMN($A$5)+MATCH($N5,Sheet1!$1:$1,0)-1,4)&":"&SUBSTITUTE(ADDRESS(1,COLUMN($A$5)+MATCH($N5,Sheet1!$1:$1,0)-1,4),"1","")&$AU$1,1,1))
</code>```

This uses string manipulation to generate the column range according to the account number. So for example, the account number 5014255 would generate Sheet1!$C$6:$C$1754, so that the values in that column can be gathered according to weight and validations.

So, I'm trying to change the logic to remove volatiles. But so far I haven't been able to do it.

I basically need my summary to find the column where the account number is, so it can do the sumproduct calculations with that column.

Any ideas or suggestions on how to work around this?

答:
To get the full column without volatiles use:

```<code>INDEX(Sheet1!$C$6:$E$1754,0,MATCH($N5,Sheet1!$C$1:$E$1,0))
</code>```

This will return the correct column to the SUMPRODUCT formula

Body:
I have researched thoroughly before posting and still can't figure this out.

I currently have a file that uses an INDIRECT logic to gather information from one worksheet to a summary worksheet. The file works perfectly as is. But I'm trying to make it more efficient as right now calculating times are huge due to so much volatility.

In the data worksheet I have a lot of columns, each with a concept and an account number assigned to it.
So, for example:

                5014255   5324232     5566544
Name   Store    Salary     Taxes    Other Benefit     P1 Weight  P2 Weight
John   Main     222222     50000       30000            0.4        0.6
Jane   Annex    222224     50002       30004            0.3        0.7

Then in the summary page, I use a SUMPRODUCT to gather the information per store per account and separating by period, like this as:

Store  Account     Concept           P1        P2
Main   5014255   Salary            88888.8  133333.2
Main   5324232   Taxes             20000.0   30000.0
Main   5566544   Other Benefit     12000.0   18000.0
Annex  5014255   Salary            66667.2  155556.8
Annex  5324232   Taxes             15000.6   35001.4
Annex  5566544   Other Benefit      9001.2   21002.8

This of course is just a basic example. The real file has several more validations and several categories of weights that are used for different accounts. In order to pull the information I have the following formula.

    =IFNA(SUMPRODUCT(
   INDIRECT(INDEX("'Sheet1'!"&ADDRESS(6,COLUMN($A$5)+MATCH($N5,Sheet1!$1:$1,0)-1,4)&":"&SUBSTITUTE(ADDRESS(1,COLUMN($A$5)+MATCH($N5,Sheet1!$1:$1,0)-1,4),"1","")&$AU$1,1,1)),
    --(Sheet1!$C$6:$C$1754=2018),
    --(Sheet1!$J$6:$J$1754=$I5),
    IF($G5=1,Sheet1!$BN$6:$BN$1754,IF($F5=1,Sheet1!$BA$6:$BA$1754,Sheet1!$AN$6:$AN$1754))
    ),0)

The important piece of code is:

INDIRECT(INDEX("'Sheet1'!"&ADDRESS(6,COLUMN($A$5)+MATCH($N5,Sheet1!$1:$1,0)-1,4)&":"&SUBSTITUTE(ADDRESS(1,COLUMN($A$5)+MATCH($N5,Sheet1!$1:$1,0)-1,4),"1","")&$AU$1,1,1))

This uses string manipulation to generate the column range according to the account number. So for example, the account number 5014255 would generate Sheet1!$C$6:$C$1754, so that the values in that column can be gathered according to weight and validations.

So, I'm trying to change the logic to remove volatiles. But so far I haven't been able to do it.

I basically need my summary to find the column where the account number is, so it can do the sumproduct calculations with that column.

Any ideas or suggestions on how to work around this?

Body:
To get the full column without volatiles use:

INDEX(Sheet1!$C$6:$E$1754,0,MATCH($N5,Sheet1!$C$1:$E$1,0))

This will return the correct column to the SUMPRODUCT formula


问:
How to manually update datatables table with new JSON data
I am using plugin jQuery datatables and load my data which I have loaded in DOM at the bottom of page and initiates plugin in this way:

```<code>var myData = [
    {
        "id": 1,
        "first_name": "John",
        "last_name": "Doe"
    }
];

$('#table').dataTable({
    data: myData
        columns: [
        { data: 'id' },
        { data: 'first_name' },
        { data: 'last_name' }
    ]
});
</code>```

Now. after performing some action I want to get new data using ajax (but not ajax option build in datatables - don't get me wrong!) and update the table with these data. How can i do that using datatables API? The documentation is very confusing and I can not find a solution. Any help will be very much appreciated. Thanks.

答:
Here is solution for legacy datatable 1.9.4</p>

```<code>    var myData = [
      {
        "id": 1,
        "first_name": "Andy",
        "last_name": "Anderson"
      }
   ];
    var myData2 = [
      {
        "id": 2,
        "first_name": "Bob",
        "last_name": "Benson"
      }
    ];

  $('#table').dataTable({
  //  data: myData,
       aoColumns: [
         { mData: 'id' },
         { mData: 'first_name' },
         { mData: 'last_name' }
      ]
  });

 $('#table').dataTable().fnClearTable();
 $('#table').dataTable().fnAddData(myData2);
</code>```

Body:
I am using plugin jQuery datatables and load my data which I have loaded in DOM at the bottom of page and initiates plugin in this way:

var myData = [
    {
        "id": 1,
        "first_name": "John",
        "last_name": "Doe"
    }
];

$('#table').dataTable({
    data: myData
        columns: [
        { data: 'id' },
        { data: 'first_name' },
        { data: 'last_name' }
    ]
});

Now. after performing some action I want to get new data using ajax (but not ajax option build in datatables - don't get me wrong!) and update the table with these data. How can i do that using datatables API? The documentation is very confusing and I can not find a solution. Any help will be very much appreciated. Thanks.

Body:
Here is solution for legacy datatable 1.9.4

    var myData = [
      {
        "id": 1,
        "first_name": "Andy",
        "last_name": "Anderson"
      }
   ];
    var myData2 = [
      {
        "id": 2,
        "first_name": "Bob",
        "last_name": "Benson"
      }
    ];

  $('#table').dataTable({
  //  data: myData,
       aoColumns: [
         { mData: 'id' },
         { mData: 'first_name' },
         { mData: 'last_name' }
      ]
  });

 $('#table').dataTable().fnClearTable();
 $('#table').dataTable().fnAddData(myData2);


问:
React with Google Chromes Puppeteer
Trying to render a react component with chrome puppeteer
 running on my Node.js environment I’m having following problem:

logging element gives me in the headless chrome console: console.log(element) =>

testWrapper in the terminal console.log(testWrapper) => {}

```<code>puppeteer.launch().then(async browser => {

    const page = await browser.newPage();

    const testDocumentPath = path.resolve('./lib/components/util/testDocument.html');
    await page.goto(`file://${testDocumentPath}`);

    const testWrapper = await page.evaluate((selector) => {
        const element = document.querySelector(selector);
        console.log(element);

        return element;
    }, '#test-wrapper');

    console.log(testWrapper);
});
</code>```

So trying to do …

```<code>ReactDOM.render(
    <div>{':)'}</div>,
    testWrapper
);
</code>```

… obviously results in an error (node:90555) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Invariant Violation: _registerComponent(...): Target container is not a DOM element.

I feel like even if I manage to get the DOM element I’m missing something here to inject a react application.

答:
.evaluate does not return a dom element. And, you are trying to modify the elements in different context. The page in the browser window and the context you have in your nodeJS is absolutely different.

Here is a different way to deal with React and Puppeteer.
First, I have an entry file where I export the function to window.

By doing this, I can access it from the browsers context easily. Instead of window, you can actually export it and try expose-loader and so on. I'll use webpack to build it.

```<code>import React from 'react';
import { render } from 'react-dom';

function Hello() {
  return <h1>Hello from React</h1>;
}

function renderIt(domNode) {
  render(<Hello />, domNode);
}

window.renderIt = renderIt;
</code>```

On the webpack config,

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

const loaders = [
  {
    test: /\.jsx?$/,
    exclude: /node_modules/,
    loader: 'babel-loader',
    query: {
      presets: ['babel-preset-es2015', 'babel-preset-react'],
      plugins: []
    }
  }
];

module.exports = {
  entry: './entry.js',
  output: {
    path: __dirname,
    filename: 'bundle.js',
    libraryTarget: 'umd'
  },
  module: {
    loaders: loaders
  }
};
</code>```

Now whenever I run webpack, it'll create a bundle.js file for me. Now let's have a puppeteer file,

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

(async () => {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  await page.goto('https://github.com');
  await page.addScriptTag({ path: require.resolve('./bundle.js') });
  await page.evaluate(() => {
    renderIt(document.querySelector('div.jumbotron.jumbotron-codelines > div > div > div > h1'));
  });
  await page.screenshot({ path: 'example.png' });
  await browser.close();
})();
</code>```

As you can see, I'm using the renderIt function that I exposed to window earlier. And when I run it, here is the result,

Sweet! Hello from react :)

Oh! And if it fails to execute script on the page due to CORS issue, you can inject it instead using the old injectFile function, until they fix their addScriptTag function, or remove deprecation from injectFile.

```<code>/**
 * injects file to puppeteer page context
 * @param  {Object} page     context where to execute the script
 * @param  {String} filePath path of specific script
 * @return {Promise}         Injects content to page context
 */
const fs = require('fs');

async function injectFile(page, filePath) {
  let contents = await new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) return reject(err);
      resolve(data);
    });
  });
  contents += `//# sourceURL=` + filePath.replace(/\n/g, '');
  return page.mainFrame().evaluate(contents);
}

// usage: await injectFile(page, require.resolve('FILE PATH'));
// export it if you want to keep things seperate
</code>```

Title: React with Google Chromes Puppeteer

Body:
Trying to render a react component with chrome puppeteer
 running on my Node.js environment I’m having following problem:

logging element gives me in the headless chrome console: console.log(element) =>

testWrapper in the terminal console.log(testWrapper) => {}

puppeteer.launch().then(async browser => {

    const page = await browser.newPage();

    const testDocumentPath = path.resolve('./lib/components/util/testDocument.html');
    await page.goto(`file://${testDocumentPath}`);

    const testWrapper = await page.evaluate((selector) => {
        const element = document.querySelector(selector);
        console.log(element);

        return element;
    }, '#test-wrapper');

    console.log(testWrapper);
});

So trying to do …

ReactDOM.render(

{':)'}
,
    testWrapper
);

… obviously results in an error (node:90555) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Invariant Violation: _registerComponent(...): Target container is not a DOM element.

I feel like even if I manage to get the DOM element I’m missing something here to inject a react application.

Body:
.evaluate does not return a dom element. And, you are trying to modify the elements in different context. The page in the browser window and the context you have in your nodeJS is absolutely different.

Here is a different way to deal with React and Puppeteer.
First, I have an entry file where I export the function to window.

By doing this, I can access it from the browsers context easily. Instead of window, you can actually export it and try expose-loader and so on. I'll use webpack to build it.

import React from 'react';
import { render } from 'react-dom';

function Hello() {
  return <h1>Hello from React</h1>;
}

function renderIt(domNode) {
  render(<Hello />, domNode);
}

window.renderIt = renderIt;

On the webpack config,

const webpack = require('webpack');

const loaders = [
  {
    test: /\.jsx?$/,
    exclude: /node_modules/,
    loader: 'babel-loader',
    query: {
      presets: ['babel-preset-es2015', 'babel-preset-react'],
      plugins: []
    }
  }
];

module.exports = {
  entry: './entry.js',
  output: {
    path: __dirname,
    filename: 'bundle.js',
    libraryTarget: 'umd'
  },
  module: {
    loaders: loaders
  }
};

Now whenever I run webpack, it'll create a bundle.js file for me. Now let's have a puppeteer file,

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  await page.goto('https://github.com');
  await page.addScriptTag({ path: require.resolve('./bundle.js') });
  await page.evaluate(() => {
    renderIt(document.querySelector('div.jumbotron.jumbotron-codelines > div > div > div > h1'));
  });
  await page.screenshot({ path: 'example.png' });
  await browser.close();
})();

As you can see, I'm using the renderIt function that I exposed to window earlier. And when I run it, here is the result,

Sweet! Hello from react :)

Oh! And if it fails to execute script on the page due to CORS issue, you can inject it instead using the old injectFile function, until they fix their addScriptTag function, or remove deprecation from injectFile.

/**
 * injects file to puppeteer page context
 * @param  {Object} page     context where to execute the script
 * @param  {String} filePath path of specific script
 * @return {Promise}         Injects content to page context
 */
const fs = require('fs');

async function injectFile(page, filePath) {
  let contents = await new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) return reject(err);
      resolve(data);
    });
  });
  contents += `//# sourceURL=` + filePath.replace(/\n/g, '');
  return page.mainFrame().evaluate(contents);
}

// usage: await injectFile(page, require.resolve('FILE PATH'));
// export it if you want to keep things seperate


问:
How do I check the state of a checkbox for macOS applications using Swift
The task seemed relatively simple, I wanted an if statement to determine if a check box is checked or not apparently check boxes but am at a loss

I've tried

if checkbox.state == everythign i can think of but it always errors either EXC_BAD_INSTRUCTION or using wrong cant convert variable type to other variable type

答:
i did this on my project and it worked well

```<code>if sender.state == .on{
            casa_ospiti_text.stringValue = "CASA"
        }
        else{
            casa_ospiti_text.stringValue = "OSPITI"
        }
</code>```

where it changes the value of a textfield (casa_ospiti_text) with constants strings.

Body:
i did this on my project and it worked well

if sender.state == .on{
            casa_ospiti_text.stringValue = "CASA"
        }
        else{
            casa_ospiti_text.stringValue = "OSPITI"
        }

where it changes the value of a textfield (casa_ospiti_text) with constants strings.


问:
Haskell arbitrary typeclass instance return type
From the Haskell Book chapter on Monoids, I am writing quickcheck tests for

```<code>semigroupAssoc :: (Eq m, S.Semigroup m) => m -> m -> m -> Bool
semigroupAssoc a b c =
    (a S.<> (b S.<> c)) == ((a S.<> b) S.<> c)

type IdentAssoc = Identity String -> Identity String -> Identity String -> Bool
</code>```

, invoking with

```<code>quickCheck (semigroupAssoc :: IdentAssoc)
</code>```

Here is the arbitrary typeclass instance

```<code>instance (Arbitrary a) => Arbitrary (Identity a) where
    arbitrary = do
        a <- Test.QuickCheck.arbitrary
        return (Identity a)
</code>```

My question is that in my arbitrary instance, I can return either (Identity a) or just a.  (Identity a) is correct, but just a gives no compiler error and causes an infinite loop when run. Why is this?

答:
Type inference changes the arbitrary call to point at the same instance we are defining right now, causing an infinite loop.

```<code>instance (Arbitrary a) => Arbitrary (Identity a) where
   arbitrary = do
        x <- Test.QuickCheck.arbitrary  -- this calls arbitrary @ a
        return (Identity x)

instance (Arbitrary a) => Arbitrary (Identity a) where
   arbitrary = do
        x <- Test.QuickCheck.arbitrary  -- this calls arbitrary @ (Identity a)
        return x
</code>```

Every time we call a class method, the compiler infers which instance to call.

In the former case, the compiler infers x :: a (only this type makes the code type check!), hence it calls arbitrary @ a.

In the latter case, the compiler infers x :: Identity a (only this type makes the code type check!), hence it calls arbitrary @ (Identity a), causing the infinite loop.

Body:
From the Haskell Book chapter on Monoids, I am writing quickcheck tests for

semigroupAssoc :: (Eq m, S.Semigroup m) => m -> m -> m -> Bool
semigroupAssoc a b c =
    (a S.<> (b S.<> c)) == ((a S.<> b) S.<> c)

type IdentAssoc = Identity String -> Identity String -> Identity String -> Bool

, invoking with

quickCheck (semigroupAssoc :: IdentAssoc)

Here is the arbitrary typeclass instance

instance (Arbitrary a) => Arbitrary (Identity a) where
    arbitrary = do
        a <- Test.QuickCheck.arbitrary
        return (Identity a)

My question is that in my arbitrary instance, I can return either (Identity a) or just a.  (Identity a) is correct, but just a gives no compiler error and causes an infinite loop when run. Why is this?

Body:
Type inference changes the arbitrary call to point at the same instance we are defining right now, causing an infinite loop.

instance (Arbitrary a) => Arbitrary (Identity a) where
   arbitrary = do
        x <- Test.QuickCheck.arbitrary  -- this calls arbitrary @ a
        return (Identity x)

instance (Arbitrary a) => Arbitrary (Identity a) where
   arbitrary = do
        x <- Test.QuickCheck.arbitrary  -- this calls arbitrary @ (Identity a)
        return x

Every time we call a class method, the compiler infers which instance to call.

In the former case, the compiler infers x :: a (only this type makes the code type check!), hence it calls arbitrary @ a.

In the latter case, the compiler infers x :: Identity a (only this type makes the code type check!), hence it calls arbitrary @ (Identity a), causing the infinite loop.