问:
Literal whitespace characters causing pattern to fail (sometimes)
I have this RegEx from my previous question. The problem is that sometimes it works, Sometimes it doesn't. I tried pasting it on an online simulator and got this: https://regex101.com/r/I3tnY4/3

The text is from a file I read using

file_get_contents

The contents of the file are complete but when I run it through the RegEx to filter it:

```<code>        $data = file_get_contents($var);
        $pat  = '/intervals \[\d+\]:\s+\Kxmin = (?P<xmin>\d+(\.\d+)?) \
                \s+xmax = (?P<xmax>\d+(\.\d+)?)\s+text = "(?P<text>[^"]*)"/m';

        // print_r($data);
        preg_match_all($pat, $data, $m);
        $result = array_map(function($a){
            return array_combine(['xmin', 'xmax', 'text'], $a);
        }, array_map(null, $m['xmin'], $m['xmax'], $m['text']));

        print_r($result);
</code>```

it returns an empty array. At first, it was working but when I added a for loop to handle multiple file upload it stopped working.

This also happened before when I tried to process the file right after it was uploaded.

Like this:

```<code>if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target_file)) {
        if (file_exists($target_file)) {
            $data = file_get_contents($target_file);
            $pat  = '/intervals \[\d+\]:\s+\Kxmin = (?P<xmin>\d+(\.\d+)?) \
            \s+xmax = (?P<xmax>\d+(\.\d+)?)\s+text = "(?P<text>[^"]*)"/m';

            preg_match_all($pat, $data, $m);
            $result = array_map(function($a){
               return array_combine(['xmin', 'xmax', 'text'], $a);
            }, array_map(null, $m['xmin'], $m['xmax'], $m['text']));

            print_r($result);
        }
    }
</code>```

With the above code, the RegEx also failed since the $result array was empty. I figured that was because the file was not yet ready to be read or something. Even though when I printed the contents of the file everything was there. So what I did then was to redirect my page to another file that did the RegEx processing and surprisingly it worked there.

答:
It appears that your task is more focused on substring extraction, rather than validation.  For this reason, you can largely reduce the size of your pattern, speed up the execution, and minimize output bloat with the following pattern:

```<code>/xmin = (\S+)\s+xmax = (\S+)\s+text = "([^"]*)/
</code>```

What have I done?  (See this demo for official pattern breakdown)

Remove the leading interval... matching since you are not using it (or more specifically the number inside of []:

Remove \K because you don't need to "restart" the fullstring match -- you aren't using it.

Remove the named capture groups because you are using array_map() and array_combine() to assign these key names anyhow.  Named capture groups cause major output array bloat, and should be avoided unless you have a compelling reason to use them.  The reason they cause bloat is because when you name capture groups, preg_match_all() will write duplicate subarray elements (the named one, and the indexed one) -- this means double the necessary data.  While, yes, you can use named capture groups, this would just mean that you would change your mapping process to remove all of the indexed elements from each subarray ([0],[1],[2],[3]).

Remove the break in your pattern. When you want to accommodate one or more whitespace characters (in your case: newlines, spaces, and possibly tabs) just use \s+.  For the record, you can use whitespaces in your pattern to improve readability, but to do this you need to include x as a flag at the end of your pattern. The x pattern modifier will ignore ALL whitespaces used in the pattern, so beware of this effect.

Replace (?P<xmax>\d+(\.\d+)?) with (\S+).  This will remove the named capture group and the nested capture group, and extract the entire non-whitespace substring.  If you DO want to validate this string, then I advise: (\d+(?:\.\d+)?)  This changes the nested group to "non-capturing" -- again reducing output array bloat.

You were wise to use a negated capture group on the last capture group, this is the most efficient way to match it.  You don't need the trailing ", so that can be removed.

Remove the m pattern modifier.  You aren't using any anchor metacharacters )(^ or $) so the flag has no purpose.

preg_match_all()'s 4th parameter PREG_SET_ORDER will structure your subarrays in such a way that only one array_map() is necessary to set up your multi-dimensional array.

This is how I suggest that you implement it:

Code: (Demo)

```<code>$data='intervals [1]:
    xmin = 0
    xmax = 13.139997023062838
    text = ""
intervals [2]:
    xmin = 13.139997023062838
    xmax = 14.763036269953904
    text = "Cities are like siblings in a large polygamous family."
intervals [3]:
    xmin = 14.763036269953904
    xmax = 17.01
    text = ""';
$pat='/xmin = (\S+)\s+xmax = (\S+)\s+text = "([^"]*)/';
if(preg_match_all($pat,$data,$m,PREG_SET_ORDER)){
    $assoc_multidim=array_map(function($a){return array_combine(['xmin','xmax','text'],array_slice($a,1));},$m);
    var_export($assoc_multidim);
}else{
    echo "substring extraction failed";
}
</code>```

Output:

```<code>array (
  0 =>
  array (
    'xmin' => '0',
    'xmax' => '13.139997023062838',
    'text' => '',
  ),
  1 =>
  array (
    'xmin' => '13.139997023062838',
    'xmax' => '14.763036269953904',
    'text' => 'Cities are like siblings in a large polygamous family.',
  ),
  2 =>
  array (
    'xmin' => '14.763036269953904',
    'xmax' => '17.01',
    'text' => '',
  ),
)
</code>```

An alternative method that makes use of your named capture groups would look like this: (Demo)

```<code>$pat='/xmin = (?P<xmin>\S+)\s+xmax = (?P<xmax>\S+)\s+text = "(?P<text>[^"]*)/';
if(preg_match_all($pat,$data,$m,PREG_SET_ORDER)){
    $assoc_multidim=array_map(function($a){return array_intersect_key($a,['xmin'=>'','xmax'=>'','text'=>'']);},$m);
    var_export($assoc_multidim);
}else{
    echo "substring extraction failed";
}
</code>```

...You see, both techniques require a little bit of clean up (unless your processes to follow don't mind the indexed subarrays), this is why I favor the less bloated array.

Body:
I have this RegEx from my previous question. The problem is that sometimes it works, Sometimes it doesn't. I tried pasting it on an online simulator and got this: https://regex101.com/r/I3tnY4/3

The text is from a file I read using

file_get_contents

The contents of the file are complete but when I run it through the RegEx to filter it:

        $data = file_get_contents($var);
        $pat  = '/intervals \[\d+\]:\s+\Kxmin = (?P<xmin>\d+(\.\d+)?) \
                \s+xmax = (?P<xmax>\d+(\.\d+)?)\s+text = "(?P<text>[^"]*)"/m';

        // print_r($data);
        preg_match_all($pat, $data, $m);
        $result = array_map(function($a){
            return array_combine(['xmin', 'xmax', 'text'], $a);
        }, array_map(null, $m['xmin'], $m['xmax'], $m['text']));

        print_r($result);

it returns an empty array. At first, it was working but when I added a for loop to handle multiple file upload it stopped working.

This also happened before when I tried to process the file right after it was uploaded.

Like this:

if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target_file)) {
        if (file_exists($target_file)) {
            $data = file_get_contents($target_file);
            $pat  = '/intervals \[\d+\]:\s+\Kxmin = (?P<xmin>\d+(\.\d+)?) \
            \s+xmax = (?P<xmax>\d+(\.\d+)?)\s+text = "(?P<text>[^"]*)"/m';

            preg_match_all($pat, $data, $m);
            $result = array_map(function($a){
               return array_combine(['xmin', 'xmax', 'text'], $a);
            }, array_map(null, $m['xmin'], $m['xmax'], $m['text']));

            print_r($result);
        }
    }

With the above code, the RegEx also failed since the $result array was empty. I figured that was because the file was not yet ready to be read or something. Even though when I printed the contents of the file everything was there. So what I did then was to redirect my page to another file that did the RegEx processing and surprisingly it worked there.

Body:
It appears that your task is more focused on substring extraction, rather than validation.  For this reason, you can largely reduce the size of your pattern, speed up the execution, and minimize output bloat with the following pattern:

/xmin = (\S+)\s+xmax = (\S+)\s+text = "([^"]*)/

What have I done?  (See this demo for official pattern breakdown)

Remove the leading interval... matching since you are not using it (or more specifically the number inside of []:

Remove \K because you don't need to "restart" the fullstring match -- you aren't using it.

Remove the named capture groups because you are using array_map() and array_combine() to assign these key names anyhow.  Named capture groups cause major output array bloat, and should be avoided unless you have a compelling reason to use them.  The reason they cause bloat is because when you name capture groups, preg_match_all() will write duplicate subarray elements (the named one, and the indexed one) -- this means double the necessary data.  While, yes, you can use named capture groups, this would just mean that you would change your mapping process to remove all of the indexed elements from each subarray ([0],[1],[2],[3]).

Remove the break in your pattern. When you want to accommodate one or more whitespace characters (in your case: newlines, spaces, and possibly tabs) just use \s+.  For the record, you can use whitespaces in your pattern to improve readability, but to do this you need to include x as a flag at the end of your pattern. The x pattern modifier will ignore ALL whitespaces used in the pattern, so beware of this effect.

Replace (?P<xmax>\d+(\.\d+)?) with (\S+).  This will remove the named capture group and the nested capture group, and extract the entire non-whitespace substring.  If you DO want to validate this string, then I advise: (\d+(?:\.\d+)?)  This changes the nested group to "non-capturing" -- again reducing output array bloat.

You were wise to use a negated capture group on the last capture group, this is the most efficient way to match it.  You don't need the trailing ", so that can be removed.

Remove the m pattern modifier.  You aren't using any anchor metacharacters )(^ or $) so the flag has no purpose.

preg_match_all()'s 4th parameter PREG_SET_ORDER will structure your subarrays in such a way that only one array_map() is necessary to set up your multi-dimensional array.

This is how I suggest that you implement it:

Code: (Demo)

$data='intervals [1]:
    xmin = 0
    xmax = 13.139997023062838
    text = ""
intervals [2]:
    xmin = 13.139997023062838
    xmax = 14.763036269953904
    text = "Cities are like siblings in a large polygamous family."
intervals [3]:
    xmin = 14.763036269953904
    xmax = 17.01
    text = ""';
$pat='/xmin = (\S+)\s+xmax = (\S+)\s+text = "([^"]*)/';
if(preg_match_all($pat,$data,$m,PREG_SET_ORDER)){
    $assoc_multidim=array_map(function($a){return array_combine(['xmin','xmax','text'],array_slice($a,1));},$m);
    var_export($assoc_multidim);
}else{
    echo "substring extraction failed";
}

Output:

array (
  0 =>
  array (
    'xmin' => '0',
    'xmax' => '13.139997023062838',
    'text' => '',
  ),
  1 =>
  array (
    'xmin' => '13.139997023062838',
    'xmax' => '14.763036269953904',
    'text' => 'Cities are like siblings in a large polygamous family.',
  ),
  2 =>
  array (
    'xmin' => '14.763036269953904',
    'xmax' => '17.01',
    'text' => '',
  ),
)

An alternative method that makes use of your named capture groups would look like this: (Demo)

$pat='/xmin = (?P<xmin>\S+)\s+xmax = (?P<xmax>\S+)\s+text = "(?P<text>[^"]*)/';
if(preg_match_all($pat,$data,$m,PREG_SET_ORDER)){
    $assoc_multidim=array_map(function($a){return array_intersect_key($a,['xmin'=>'','xmax'=>'','text'=>'']);},$m);
    var_export($assoc_multidim);
}else{
    echo "substring extraction failed";
}

...You see, both techniques require a little bit of clean up (unless your processes to follow don't mind the indexed subarrays), this is why I favor the less bloated array.


来源: stackexchange

问:
Function template specialization with templated typename
I have a template method in some class

```<code>template<typename T> int get(T &value) const {
    ...
}
</code>```

And several specializations

```<code>template<> int AAA::get<int>(int &val) const;
template<> int AAA::get<AAA>(AAA &val) const;
</code>```

There is a templated type

```<code>template<const int SIZE> class BBB{
    ...
};
</code>```

and I need to specialize my template method with this type.

```<code>template<> int AAA::get<BBB<SIZE>>(BBB<SIZE> &val) const;
</code>```

I know that function template partial specialization is disabled.
But maybe there be a solution for this particular case?

答:
You can turn it into template class specialization:</p>

```<code>class AAA
{
    template<typename T> class get_impl
    {
        public: static int get(T & value) { return(0); }
    };

    public: template<typename T> int get(T & value) const
    {
        return(get_impl<T>::get(value));
    }
};

template<> class AAA::
get_impl<int>
{
    public: static int get(int & value) { return(0); }
};

template<> class AAA::
get_impl<AAA>
{
    public: static int get(AAA & value) { return(0); }
};

template<int SIZE> class BBB{};

template<int SIZE> class AAA::
get_impl<BBB<SIZE>>
{
    public: static int get(BBB<SIZE> & value) { return(0); }
};

int main()
{
    AAA a{};
    BBB<5> b{};
    a.get(b);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a template method in some class

template<typename T> int get(T &value) const {
    ...
}

And several specializations

template<> int AAA::get<int>(int &val) const;
template<> int AAA::get<AAA>(AAA &val) const;

There is a templated type

template<const int SIZE> class BBB{
    ...
};

and I need to specialize my template method with this type.

template<> int AAA::get<BBB<SIZE>>(BBB<SIZE> &val) const;

I know that function template partial specialization is disabled.
But maybe there be a solution for this particular case?

Body:
You can turn it into template class specialization:

class AAA
{
    template<typename T> class get_impl
    {
        public: static int get(T & value) { return(0); }
    };

    public: template<typename T> int get(T & value) const
    {
        return(get_impl<T>::get(value));
    }
};

template<> class AAA::
get_impl<int>
{
    public: static int get(int & value) { return(0); }
};

template<> class AAA::
get_impl<AAA>
{
    public: static int get(AAA & value) { return(0); }
};

template<int SIZE> class BBB{};

template<int SIZE> class AAA::
get_impl<BBB<SIZE>>
{
    public: static int get(BBB<SIZE> & value) { return(0); }
};

int main()
{
    AAA a{};
    BBB<5> b{};
    a.get(b);
}


问:
numpy sign and fraction
What is the pitfall I'm falling into (apart from blindly applying a numpy method to some object it was probably not designed for)?

```<code>Python 3.4.3 (default, Nov 28 2017, 16:41:13)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy, fractions
>>> numpy.__version__
'1.8.2'
>>> numpy.sign(1)
1
>>> fractions.Fraction(1)
Fraction(1, 1)
>>> numpy.sign(fractions.Fraction(1))
-1
>>>
</code>```

答:
This seems to be a bug with the particular version of numpy you are using. It works for me. Though in general, numpy may not support fractions, going through the documentation of numpy.sign, no special case about fractions is mentioned per se, only that it accepts numbers and outputs the sign.

```<code>In [14]: import numpy, fractions

In [15]: numpy.sign(1)
    ...:
Out[15]: 1

In [16]: fractions.Fraction(1)
    ...:
Out[16]: Fraction(1, 1)

In [17]: numpy.sign(fractions.Fraction(1))
Out[17]: 1L
</code>```

Title: numpy sign and fraction

Body:
What is the pitfall I'm falling into (apart from blindly applying a numpy method to some object it was probably not designed for)?

Python 3.4.3 (default, Nov 28 2017, 16:41:13)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy, fractions
>>> numpy.__version__
'1.8.2'
>>> numpy.sign(1)
1
>>> fractions.Fraction(1)
Fraction(1, 1)
>>> numpy.sign(fractions.Fraction(1))
-1
>>>

Body:
This seems to be a bug with the particular version of numpy you are using. It works for me. Though in general, numpy may not support fractions, going through the documentation of numpy.sign, no special case about fractions is mentioned per se, only that it accepts numbers and outputs the sign.

In [14]: import numpy, fractions

In [15]: numpy.sign(1)
    ...:
Out[15]: 1

In [16]: fractions.Fraction(1)
    ...:
Out[16]: Fraction(1, 1)

In [17]: numpy.sign(fractions.Fraction(1))
Out[17]: 1L


问:
Cutting a UIImageView according to UIBezier?
I have a UIImageView, with a certain image.
I also have a UIBezierPath in some strange shape.
I would like to cut the image to that shape and return a new image in that shape.

In the form of :

```<code>func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView
</code>```

答:
Use UIGraphicsImageRenderer to make an image with a clipping path.  Here is a Playground:</p>

```<code>import PlaygroundSupport
import UIKit

let imageToCrop = UIImage(named: "test.jpg")!
let size = imageToCrop.size
let cutImage = UIGraphicsImageRenderer(size: size).image { imageContext in
    let context = imageContext.cgContext
    let clippingPath = UIBezierPath(ovalIn: CGRect(origin: .zero, size: size)).cgPath
    context.addPath(clippingPath)
    context.clip(using: .evenOdd)
    imageToCrop.draw(at: .zero)
}

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
imageView.image = cutImage
PlaygroundPage.current.liveView = imageView
</code>```

Body:
I have a UIImageView, with a certain image.
I also have a UIBezierPath in some strange shape.
I would like to cut the image to that shape and return a new image in that shape.

In the form of :

func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView

Body:
Use UIGraphicsImageRenderer to make an image with a clipping path.  Here is a Playground:

import PlaygroundSupport
import UIKit

let imageToCrop = UIImage(named: "test.jpg")!
let size = imageToCrop.size
let cutImage = UIGraphicsImageRenderer(size: size).image { imageContext in
    let context = imageContext.cgContext
    let clippingPath = UIBezierPath(ovalIn: CGRect(origin: .zero, size: size)).cgPath
    context.addPath(clippingPath)
    context.clip(using: .evenOdd)
    imageToCrop.draw(at: .zero)
}

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
imageView.image = cutImage
PlaygroundPage.current.liveView = imageView


问:
Mongodb aggregate arguments to $lookup must be strings
```<code>        db.absences.insert([
           { "_id" : 1, "student" : "Ann Aardvark", sickdays: [ new Date ("2018-05-01"),new Date ("2018-08-23") ] },
           { "_id" : 2, "student" : "Zoe Zebra", sickdays: [ new Date ("2018-02-01"),new Date ("2018-05-23") ] },
        ])

    db.holidays.insert([
       { "_id" : 1, year: 2018, name: "New Years", date: new Date("2018-01-01") },
       { "_id" : 2, year: 2018, name: "Pi Day", date: new Date("2018-03-14") },
       { "_id" : 3, year: 2018, name: "Ice Cream Day", date: new Date("2018-07-15") },
       { "_id" : 4, year: 2017, name: "New Years", date: new Date("2017-01-01") },
       { "_id" : 5, year: 2017, name: "Ice Cream Day", date: new Date("2017-07-16") }
    ])

db.absences.aggregate([
   {
      $lookup:
         {
           from: "holidays",
           pipeline: [
              { $match: { year: 2018 } },
              { $project: { _id: 0, date: { name: "$name", date: "$date" } } },
              { $replaceRoot: { newRoot: "$date" } }
           ],
           as: "holidays"
         }
    }
])
</code>```

I'm trying to use pipeline in lookup for aggregation query. Having this as same as from the Mongodb documentation, it still gives an error

```<code>Unable to execute the selected commands

Mongo Server error (MongoCommandException): Command failed with error 4570: 'arguments to $lookup must be strings, pipeline: [ { $match: { year: 2018.0 } }, { $project: { _id: 0.0, date: { name: "$name", date: "$date" } } }, { $replaceRoot: { newRoot: "$date" } } ] is type array' on server localhost:27017.

The full response is:
{
    "ok" : 0.0,
    "errmsg" : "arguments to $lookup must be strings, pipeline: [ { $match: { year: 2018.0 } }, { $project: { _id: 0.0, date: { name: \"$name\", date: \"$date\" } } }, { $replaceRoot: { newRoot: \"$date\" } } ] is type array",
    "code" : NumberInt(4570),
    "codeName" : "Location4570"
}
</code>```

I'm using mongodb v3.4.

答:
In $lookup you could just join the collectionfirst and doing the match, project and etc later after lookup. And you should have the foreign field that referring to holidays collection.

Like :

```<code>{
  $lookup:
     {
       from: "holidays",
       localField: "holidaysID", //yourLocalfield, it is local field in absences. you should have it to join 2 collections
       foreignField : "_id", //theforeignfield, it is _id in the holidays
       as: "holidays"
     }
},{ $match: { year: 2018 } },
{ $project: { _id: 0, date: { name: "$name", date: "$date" } } },
{ $replaceRoot: { newRoot: "$date" } }
</code>```

Hope it helps.

Body:
        db.absences.insert([
           { "_id" : 1, "student" : "Ann Aardvark", sickdays: [ new Date ("2018-05-01"),new Date ("2018-08-23") ] },
           { "_id" : 2, "student" : "Zoe Zebra", sickdays: [ new Date ("2018-02-01"),new Date ("2018-05-23") ] },
        ])

    db.holidays.insert([
       { "_id" : 1, year: 2018, name: "New Years", date: new Date("2018-01-01") },
       { "_id" : 2, year: 2018, name: "Pi Day", date: new Date("2018-03-14") },
       { "_id" : 3, year: 2018, name: "Ice Cream Day", date: new Date("2018-07-15") },
       { "_id" : 4, year: 2017, name: "New Years", date: new Date("2017-01-01") },
       { "_id" : 5, year: 2017, name: "Ice Cream Day", date: new Date("2017-07-16") }
    ])

db.absences.aggregate([
   {
      $lookup:
         {
           from: "holidays",
           pipeline: [
              { $match: { year: 2018 } },
              { $project: { _id: 0, date: { name: "$name", date: "$date" } } },
              { $replaceRoot: { newRoot: "$date" } }
           ],
           as: "holidays"
         }
    }
])

I'm trying to use pipeline in lookup for aggregation query. Having this as same as from the Mongodb documentation, it still gives an error

Unable to execute the selected commands

Mongo Server error (MongoCommandException): Command failed with error 4570: 'arguments to $lookup must be strings, pipeline: [ { $match: { year: 2018.0 } }, { $project: { _id: 0.0, date: { name: "$name", date: "$date" } } }, { $replaceRoot: { newRoot: "$date" } } ] is type array' on server localhost:27017.

The full response is:
{
    "ok" : 0.0,
    "errmsg" : "arguments to $lookup must be strings, pipeline: [ { $match: { year: 2018.0 } }, { $project: { _id: 0.0, date: { name: \"$name\", date: \"$date\" } } }, { $replaceRoot: { newRoot: \"$date\" } } ] is type array",
    "code" : NumberInt(4570),
    "codeName" : "Location4570"
}

I'm using mongodb v3.4.

Body:
In $lookup you could just join the collectionfirst and doing the match, project and etc later after lookup. And you should have the foreign field that referring to holidays collection.

Like :

{
  $lookup:
     {
       from: "holidays",
       localField: "holidaysID", //yourLocalfield, it is local field in absences. you should have it to join 2 collections
       foreignField : "_id", //theforeignfield, it is _id in the holidays
       as: "holidays"
     }
},{ $match: { year: 2018 } },
{ $project: { _id: 0, date: { name: "$name", date: "$date" } } },
{ $replaceRoot: { newRoot: "$date" } }

Hope it helps.


问:
Cropping images to square in Xamarin.Forms
I'm trying to get a user to select/take a picture and then getting a crop view up. I have managed to do this using this library:
https://github.com/XAM-Consulting/Xam.Plugins.ImageCropper

But I want to force the image to be a square, not any aspect ratio the user pleases. Is there anyone who knows how to do this?

Is there any other library/plugin that I can use for this?

答:
You can use this: https://github.com/daniel-luberda/DLToolkit.Forms.Controls/tree/master/ImageCropView</p>

```<code><imgcrop:ImageCropView HeightRequest="300" WidthRequest="300" x:Name="cropView"
    Source="http://photos2.insidercdn.com/iphone4scamera-111004-full.JPG">
</imgcrop:ImageCropView>
</code>```

Body:
You can use this: https://github.com/daniel-luberda/DLToolkit.Forms.Controls/tree/master/ImageCropView

<imgcrop:ImageCropView HeightRequest="300" WidthRequest="300" x:Name="cropView"
    Source="http://photos2.insidercdn.com/iphone4scamera-111004-full.JPG">
</imgcrop:ImageCropView>


问:
How to split a file by a multi-character delimiter?
On Unix, without adding anything to the OS (i.e. only using grep, awk, sed, cut, etc.), how can I extract the "text" line in only the "codeView" section (and ignore that in the "probableStartLocationView" section)?

```<code>. . .
      "events" : [ {
"id" : "12345",
"important" : true,
"type" : "Creation",
"description" : "Something happened here",
"extraDetails" : null,
"codeView" : {
  "lines" : [ {
    "fragments" : [ {
      "type" : "NORMAL_CODE",
      "value" : "str = wrapper.getParameter("
    }, {
      "type" : "CODE_STRING",
      "value" : ""abcd""
    }, {
      "type" : "NORMAL_CODE",
      "value" : ")"
    } ],
    "text" : "str = wrapper.getParameter("abcd")"
  } ],
  "nested" : false
},
"probableStartLocationView" : {
  "lines" : [ {
    "fragments" : [ {
      "type" : "STACKTRACE_LINE",
      "value" : "<init>() @ JSONInputData.java:72"
    } ],
    "text" : "<init>() @ JSONInputData.java:72"
  } ],
  "nested" : false
},
. . .
</code>```

答:
The right way with jq processor (assuming that .events is a key on the 1st level of the input JSON structure):

```<code>jq -r '.events[0].codeView.lines[0].text' input.json
</code>```

The output:

```<code>str = wrapper.getParameter("abcd")
</code>```

Body:
On Unix, without adding anything to the OS (i.e. only using grep, awk, sed, cut, etc.), how can I extract the "text" line in only the "codeView" section (and ignore that in the "probableStartLocationView" section)?

. . .
      "events" : [ {
"id" : "12345",
"important" : true,
"type" : "Creation",
"description" : "Something happened here",
"extraDetails" : null,
"codeView" : {
  "lines" : [ {
    "fragments" : [ {
      "type" : "NORMAL_CODE",
      "value" : "str = wrapper.getParameter("
    }, {
      "type" : "CODE_STRING",
      "value" : ""abcd""
    }, {
      "type" : "NORMAL_CODE",
      "value" : ")"
    } ],
    "text" : "str = wrapper.getParameter("abcd")"
  } ],
  "nested" : false
},
"probableStartLocationView" : {
  "lines" : [ {
    "fragments" : [ {
      "type" : "STACKTRACE_LINE",
      "value" : "<init>() @ JSONInputData.java:72"
    } ],
    "text" : "<init>() @ JSONInputData.java:72"
  } ],
  "nested" : false
},
. . .

Body:
The right way with jq processor (assuming that .events is a key on the 1st level of the input JSON structure):

jq -r '.events[0].codeView.lines[0].text' input.json

The output:

str = wrapper.getParameter(&quot;abcd&quot;)


问:
sqlplus in oracle: second column is wrapped/shows up on next line instead of the same line as first
I have a formatting question for you all today.

I'm using the listagg function for the first time and I get the results I want, but the second column is getting wrapped around and appearing on the line underneath column1. I have adjusted my linesizes and everything, but still get the same issue. Keep in mind that I am working with sqlplus in an oracle environment.

Here is the query:

```<code>select lit_id "Bookid",listagg(Auname, ',')
        WITHIN GROUP
        (order by Auname) "Author"
        from LITWORK_AUTHOR
        group by lit_id;
</code>```

Here is what I get:

```<code>    Bookid
----------
Author
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
      1101
Dilbert,Emerson,Sartre

      1102
Axel,Sartre

      1103
Breese,Marquez

      1104
Groom,Young

      1105
Blake,Julian,Scott,Verde,Young

      1106
Black,Sartre

      2007
Emerson,Pell,Simon

      2008
Codd,Rogers,Sartre,Young

8 rows selected.
</code>```

This is what I want: (example of first few lines)

```<code>Bookid   Author
  1101   Dilbert,Emerson,Sartre
  1102   Axel,Sartre
  1103   Breese,Marquez
</code>```

Thanks in advance.

答:
```<code>COLUMN Bookid Format 99999

COLUMN Author Format A50

select lit_id "Bookid",listagg(Auname, ',')
      WITHIN GROUP
      (order by Auname) "Author"
      FROM LITWORK_AUTHOR
      GROUP BY lit_id;
</code>```

This got the exact format that I wanted

Body:
I have a formatting question for you all today.

I'm using the listagg function for the first time and I get the results I want, but the second column is getting wrapped around and appearing on the line underneath column1. I have adjusted my linesizes and everything, but still get the same issue. Keep in mind that I am working with sqlplus in an oracle environment.

Here is the query:

select lit_id "Bookid",listagg(Auname, ',')
        WITHIN GROUP
        (order by Auname) "Author"
        from LITWORK_AUTHOR
        group by lit_id;

Here is what I get:

    Bookid
----------
Author
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
      1101
Dilbert,Emerson,Sartre

      1102
Axel,Sartre

      1103
Breese,Marquez

      1104
Groom,Young

      1105
Blake,Julian,Scott,Verde,Young

      1106
Black,Sartre

      2007
Emerson,Pell,Simon

      2008
Codd,Rogers,Sartre,Young

8 rows selected.

This is what I want: (example of first few lines)

Bookid   Author
  1101   Dilbert,Emerson,Sartre
  1102   Axel,Sartre
  1103   Breese,Marquez

Thanks in advance.

Body:
COLUMN Bookid Format 99999

COLUMN Author Format A50

select lit_id "Bookid",listagg(Auname, ',')
      WITHIN GROUP
      (order by Auname) "Author"
      FROM LITWORK_AUTHOR
      GROUP BY lit_id;

This got the exact format that I wanted


问:
Symfony 1.4 Error 400 on the home page in prod env (not in dev env)
I have made an tested an application on my computer and all is working fine (I used only the dev environment via the frontend_dev.php page).

When I deploy this application on the test server, I have the error 400 Bad Request below:

Bad Request

Your browser sent a request that this server could not understand.

I accessed to the website with the normal URL.
I'm using symfony 1.4 with doctrine (no others plugins are involved), wamp 2 (php 5.3, apache 2.0.59).

If I try to access the application with the dev environment, it works.

答: Try checking if the no_script property on your application setting.yml file. If should be set to False, clear cache and try again


问:
generate an Excel file using PHP
I'm new with PHP, I'm developping a WEB application that display a table with informations from an SQL server DATA BASE, the problem that I want to add a button to generate an EXCEL file that contains the table displayed? Is that possible??
@Ranjit this is the PHP code that displays the table and generate the excel file

edit 1

```<code><?php
$ch="";
if(isset($_POST['historique']))
{
    if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
    {
                $ch= "(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
        ?>
<table id="tab" border="1">
                <tr>
              <th><font color="red">Date</font></th>
                <th><font color="red">Agent</font></th>
            <th><font color="red">numéro</font></th>
                </tr>
<?php

$search = " // my query
where operationDate between" .$ch;
$stmt = mssql_query($search);
                             while ($data = mssql_fetch_assoc($stmt))
                             {
                                     ?>
     <tr>
 <td><?php echo utf8_encode ($data['operationDate']);?></td>
 <td><?php echo utf8_encode ($data['fullName']);?></td>
 <td><?php echo utf8_encode ($data['number']);?></td>
                                     </tr>
<?php
     } }

     ?>
        </table>
<?php
}
$output ='';
if(isset($_POST['excel']))
{
    if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
    {
    $rq = "// my query
                                 where operationDate between" ."(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
    $res = mssql_query($rq);
  if(mssql_num_rows($res)>0)
  {
    $output.='<table border=1>
            <tr>
                  <th>Date</th>
                  <th>Depanneur</th>
                  <th>numéro</th>
              </tr>
              ';
              while ($row=mssql_fetch_array($res))
              {
                $output .='
                <tr>
                    <td>'.$row["operationDate"].'</td>
                    <td>'.$row["fullName"].'</td>
                    <td>'.$row["number"].'</td>
                </tr>';
              }
                            $output .='</table>';
              header("Content-Type: application/xls;charset=UTF-8");
              header("Content-Disposition: attachement; filename=file.xls");

              echo $output;
                            //mssql_close($conn);
}}}
?>
</code>```

答:
You'll have to select the data manually then insert them into the excel sheet, there's php library called PHPEXCEL you can use it.

See this
http://www.c-sharpcorner.com/article/export-to-excel-in-php-with-my-sql/

Title: generate an Excel file using PHP

Body:
I'm new with PHP, I'm developping a WEB application that display a table with informations from an SQL server DATA BASE, the problem that I want to add a button to generate an EXCEL file that contains the table displayed? Is that possible??
@Ranjit this is the PHP code that displays the table and generate the excel file

edit 1

<?php
$ch="";
if(isset($_POST['historique']))
{
    if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
    {
                $ch= "(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
        ?>

              Date
                Agent
            numéro

<?php

$search = " // my query
where operationDate between" .$ch;
$stmt = mssql_query($search);
                             while ($data = mssql_fetch_assoc($stmt))
                             {
                                     ?>

 <?php echo utf8_encode ($data['operationDate']);?>
 <?php echo utf8_encode ($data['fullName']);?>
 <?php echo utf8_encode ($data['number']);?>

<?php
     } }

     ?>

<?php
}
$output ='';
if(isset($_POST['excel']))
{
    if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
    {
    $rq = "// my query
                                 where operationDate between" ."(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
    $res = mssql_query($rq);
  if(mssql_num_rows($res)>0)
  {
    $output.='

                  Date
                  Depanneur
                  numéro

              ';
              while ($row=mssql_fetch_array($res))
              {
                $output .='

                    '.$row["operationDate"].'
                    '.$row["fullName"].'
                    '.$row["number"].'

';
              }
                            $output .='
';
              header("Content-Type: application/xls;charset=UTF-8");
              header("Content-Disposition: attachement; filename=file.xls");

              echo $output;
                            //mssql_close($conn);
}}}
?>


答:
Instead of specialization, use overloads:</p>

```<code>int AAA::get(int &val) const;
int AAA::get(AAA &val) const;
template <int Size> int AAA::get(BBB<SIZE> &val) const;
</code>```

Title: Function template specialization with templated typename

Body:
Instead of specialization, use overloads:

int AAA::get(int &val) const;
int AAA::get(AAA &val) const;
template <int Size> int AAA::get(BBB<SIZE> &val) const;


问:
Updating a Tab view text
I am beginning with Android and I have a NavigationView along with Tabular layout. I want to change the values in the tabs fragments based on the selection made in the navigation view. Here is my code-

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    Context mainActivityContext;
    Intent serviceIntent;

    SharedPreferences sharedPref;
    SharedPreferences.Editor editor;

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private String valSelected = "";
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editor  = sharedPref.edit();

        mainActivityContext = this;

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.sel1) {

            valSelected = "First";
            NotificationFragment fragment_obj = (NotificationFragment)getSupportFragmentManager().
                    findFragmentById(R.id.title_notification);

            fragment_obj.updateView();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public static class PlaceholderFragment extends Fragment {

        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main2, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);

             textView.setText("HELLO");
            return rootView;
        }
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {

            if(position == 0) {
                return new NotificationFragment();

            }
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {

            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Tab1";
                case 1:
                    return "Tab2";
                case 2:
                    return "Tab3";
                case 3:
                    return "Tab4";

            }
            return null;
        }

        @Override
        public int getItemPosition(Object object) {
            if (object instanceof NotificationFragment) {
                ((NotificationFragment)object).updateView();
            }
            return super.getItemPosition(object);
        }
    }
}
</code>```

This is my NotificationFragment
NotificationFragment.java

```<code>public class NotificationFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        View rootView = inflater.inflate(R.layout.notification_layout, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.title_notification);

        textView.setText(MainActivity.coinSelected.toUpperCase());
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void updateView(){
        TextView text = (TextView) this.getView().findViewById(R.id.title_notification);
        text.setText(MainActivity.valSelected);
    }

}
</code>```

But when I try to update the value in my MainActivity using

```<code>NotificationFragment fragment_obj = (NotificationFragment)getSupportFragmentManager().
                    findFragmentById(R.id.title_notification);
</code>```

it gives me null.

Edit
Here is the notification layout file:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/title_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BTC/USD"
        android:textSize="26dp"/>

</LinearLayout>
</code>```

答: I faced this problem once when in my MainActivity.java i was importing android.support.v4.app.Fragment; and in my other class i was importing android.app.Fragment. I changed it to the same thing and findFragmentById(R.id) now returned the right fragment.</p>

Title: Updating a Tab view text

Body:
I am beginning with Android and I have a NavigationView along with Tabular layout. I want to change the values in the tabs fragments based on the selection made in the navigation view. Here is my code-

MainActivity.java

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    Context mainActivityContext;
    Intent serviceIntent;

    SharedPreferences sharedPref;
    SharedPreferences.Editor editor;

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private String valSelected = "";
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editor  = sharedPref.edit();

        mainActivityContext = this;

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.sel1) {

            valSelected = "First";
            NotificationFragment fragment_obj = (NotificationFragment)getSupportFragmentManager().
                    findFragmentById(R.id.title_notification);

            fragment_obj.updateView();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public static class PlaceholderFragment extends Fragment {

        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main2, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);

             textView.setText("HELLO");
            return rootView;
        }
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {

            if(position == 0) {
                return new NotificationFragment();

            }
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {

            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Tab1";
                case 1:
                    return "Tab2";
                case 2:
                    return "Tab3";
                case 3:
                    return "Tab4";

            }
            return null;
        }

        @Override
        public int getItemPosition(Object object) {
            if (object instanceof NotificationFragment) {
                ((NotificationFragment)object).updateView();
            }
            return super.getItemPosition(object);
        }
    }
}

This is my NotificationFragment
NotificationFragment.java

public class NotificationFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        View rootView = inflater.inflate(R.layout.notification_layout, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.title_notification);

        textView.setText(MainActivity.coinSelected.toUpperCase());
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void updateView(){
        TextView text = (TextView) this.getView().findViewById(R.id.title_notification);
        text.setText(MainActivity.valSelected);
    }

}

But when I try to update the value in my MainActivity using

NotificationFragment fragment_obj = (NotificationFragment)getSupportFragmentManager().
                    findFragmentById(R.id.title_notification);

it gives me null.

Edit
Here is the notification layout file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/title_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BTC/USD"
        android:textSize="26dp"/>

</LinearLayout>


问:
Email Campaign - Navbar Move To Bottom In Mobile View

Hi, I am trying to come up with a responsive email campaign such that the navbar at the top will move to the bottom once in mobile site. I tried but can't seems to figure out. The example of what I am trying to achieve is here example

I am using HTML and CSS.

This is my navbar code in desktop view,

```<code>.nav {
font-family: Arial, sans-serif;
font-size: 14px;
color: #272727;
font-weight: normal;
line-height: 14px;
mso-line-height-rule: exactly;
text-align: center;
vertical-align: top;
}

.nav a { color: #272727; text-decoration: none; }
</code>```

The HTML:

```<code>     <table border="0" cellspacing="0" cellpadding="0" align="right" class="deviceWidth">
      <tr>
           <td>
           <!-- Start: Nav 1 -->
           <table border="0" cellpadding="0" cellspacing="0" align="left" class="deviceWidth">
             <tr>
             <td align="center" valign="top" style="padding: 45px 0 15px 20px;" class="nav navPaddingForMobile whiteBackgroundForMobile">
                <a href="http://www.example.com">HOME</a>
             </td>
             </tr>
           </table>
         <!-- End: Nav 1 -->

 <!--[if (gte mso 9)|(IE)]></td><td style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0;"><![endif]-->

     <!-- Start: Nav 2 -->
     <table border="0" cellpadding="0" cellspacing="0" align="left" class="deviceWidth">
     <tr>
       <td align="center" style="padding: 45px 0 15px 20px;" class="nav navPaddingForMobile whiteBackgroundForMobile">
        <a href="http://www.example.com">FAVOURITE</a>
       </td>
     </tr>
    </table>
   <!-- End: Nav 2 -->

<!--[if (gte mso 9)|(IE)]></td><td style="border-collapse: collapse; mso-table-lspace: 0; mso-table-rspace: 0;"><![endif]-->

    <!-- Start: Nav 3 -->
    <table border="0" cellpadding="0" cellspacing="0" align="left" class="deviceWidth">
     <tr>
     <td align="center" valign="top" style="padding: 45px 0 15px 20px;" class="nav navPaddingForMobile whiteBackgroundForMobile">
       <a href="http://www.example.com">FAQ</a>
    </td>
     </tr>
    </table>
  <!-- End: Nav 3 -->
  </td>
</tr>
</table>
</code>```

答:
using Position + Float + Media Query:

* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    -o-box-sizing: border-box;
    box-sizing: border-box;
    font-family: tahoma;
    margin: 0;
    padding: 0;
}
header,main, nav, aside, footer {
    text-align: center;
    padding: 15px;
    color: #fff
}
header { background: #0C65A7 }
main { background: #16A2C5 }
nav { background: #124B78 }
aside { background: #5275AD }
footer { background: #7CCCE3 }

.container {
    position: relative;
    overflow: hidden;
    padding-top: 45px
}
nav {
    position: absolute;
    width: 100%;
    top: 0
}
main, aside {
    float: left;
    height: calc(100vh - 145px)
}
main { width: 70% }
aside { width: 30% }
@media(max-width: 400px) {
    .container { padding: 0 }
    main, aside { width: 100%; height: 250px }
    nav { position: static; clear: both }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>Header</header>
<div class="container">
    <main>Main</main>
    <nav>Nav</nav>
    <aside>Aside</aside>
</div>
<footer>Footer</footer></code>```

Body:
Hi, I am trying to come up with a responsive email campaign such that the navbar at the top will move to the bottom once in mobile site. I tried but can't seems to figure out. The example of what I am trying to achieve is here example

I am using HTML and CSS.

This is my navbar code in desktop view,

.nav {
font-family: Arial, sans-serif;
font-size: 14px;
color: #272727;
font-weight: normal;
line-height: 14px;
mso-line-height-rule: exactly;
text-align: center;
vertical-align: top;
}

.nav a { color: #272727; text-decoration: none; }

The HTML:

                HOME

        FAVOURITE

       FAQ

Body:
using Position + Float + Media Query:

* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    -o-box-sizing: border-box;
    box-sizing: border-box;
    font-family: tahoma;
    margin: 0;
    padding: 0;
}
header,main, nav, aside, footer {
    text-align: center;
    padding: 15px;
    color: #fff
}
header { background: #0C65A7 }
main { background: #16A2C5 }
nav { background: #124B78 }
aside { background: #5275AD }
footer { background: #7CCCE3 }

.container {
    position: relative;
    overflow: hidden;
    padding-top: 45px
}
nav {
    position: absolute;
    width: 100%;
    top: 0
}
main, aside {
    float: left;
    height: calc(100vh - 145px)
}
main { width: 70% }
aside { width: 30% }
@media(max-width: 400px) {
    .container { padding: 0 }
    main, aside { width: 100%; height: 250px }
    nav { position: static; clear: both }
}

<header>Header</header>
<div class="container">
    <main>Main</main>
    <nav>Nav</nav>
    <aside>Aside</aside>
</div>
<footer>Footer</footer>


问:
Targeting ARM architecture with .NET compiler
When you compile windows application in .NET you can set "Platform Target" to be x86 or x64. This would optimize your code to a specific architecture of the processor and allow to escape IL.
Does anyone know if there's something that would allow to achieve the same result for Windows Mobile application? I'm only interested in running my application on ARM architecture.</p>

答:
I don't believe specifying the platform target does optimise the generated IL for the given architecture. Instead, it says, "I only run on the specified architecture, because I contain P/Invoke calls specific to that architecture." At least, that's my understanding of it. It means that when running on an x64 machine, an executable can run under the 32 bit version of the CLR for compatibility.

How this fits in with the compact framework (which I assume is your actual platform?) I'm not sure.

OwnerDisplayName: Ilya Volodin

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jon Skeet


问:
How can I get today's timestamp in PHP
I tried

```<code>$dtToday = DateTime::createFromFormat('Y-m-d', date('Y-m-d'));
</code>```

but when I output it

```<code>die($dtToday->format('d M Y g:i:s a'));
</code>```

I still get the time eg "22 Jan 2011 4:53:59 pm". Why is that?

UPDATE

Ah... many people misunderstood me, my bad, I forgot to point out the main point. I created the date with just the date portion, I don't want the time. So I'd expect something like

```<code>22 Jan 2011 12:00:00 am
</code>```

答:
You are getting "22 Jan 2011 4:53:59 pm" because those are the rules you format your date with :

d (day) : 22

M (Month) : Jan

Y (Year) : 2011

g (12-hour format) : 4

i (minutes): 53

s (seconds): 59

a (am/pm): pm

Be more speciffic about the format would you like your timestamp to have.
I suggest you take a peak at the php date documentation.

Title: How can I get today's timestamp in PHP

Body:
I tried

$dtToday = DateTime::createFromFormat('Y-m-d', date('Y-m-d'));

but when I output it

die($dtToday->format('d M Y g:i:s a'));

I still get the time eg "22 Jan 2011 4:53:59 pm". Why is that?

UPDATE

Ah... many people misunderstood me, my bad, I forgot to point out the main point. I created the date with just the date portion, I don't want the time. So I'd expect something like

22 Jan 2011 12:00:00 am


问:
Creating project on Google Cloud Platform causes "Unknown error"
I am trying to create my first project on Google Cloud Platform for my organization and get an 'Unknown error'.

I have:

An active billing account.

A unique project name (actually tried many different names, see the screenshot).

Screenshot of Google Cloud Console

Answers Unknown error creating a project and Anyone else encountering "unknown error" when Initializing Cloud Engine? mention the same error, but but not helpful.

One specialty - my organization is a user of legacy Google Apps for Business. But this things shall not be related, right?

答:
The project could not be created because Google Developers Console App was disabled for the organisation.

Solution

Go to your G Suite console (admin.google.com).

Search for "Google Developers Console" (Apps -> Additional Google services).

Right click on vertical dots (kebab menu) and set "ON for everyone".

Than you can go back to console.cloud.google.com and create the project.


问:
Passed prop to vue-router is not set immediately
I have set up my vue-router like so:

```<code><router-view action="/test"></router-view>
</code>```

In one of my router components I have set up a prop like this:

```<code>props: {
    action: {
        required: true,
        type: String
    }
}
</code>```

But this results in an error:

vue.esm.js:574 [Vue warn]: Missing required prop: "action"

If I simply echo out the action inside my template it has been set though and the vue devtools look fine:

```<code>{{ action }}
</code>```

It seems the prop simply does not reach the component fast enough for the initial required check.

Am I wrong to assume this should simply work?

答:
Blockquote

Bind data with the colon:. Change your router tag  to

```<code><router-view :action="'/test'"></router-view>
</code>```

Body:
I have set up my vue-router like so:

<router-view action="/test"></router-view>

In one of my router components I have set up a prop like this:

props: {
    action: {
        required: true,
        type: String
    }
}

But this results in an error:

vue.esm.js:574 [Vue warn]: Missing required prop: "action"

If I simply echo out the action inside my template it has been set though and the vue devtools look fine:

{{ action }}

It seems the prop simply does not reach the component fast enough for the initial required check.

Am I wrong to assume this should simply work?

Body:
Blockquote

Bind data with the colon:. Change your router tag  to

<router-view :action="'/test'"></router-view>


问:
Cannot read property 'replace' of undefined with gem nested_form_fields gem
I'm using gem 'nested_form_fields', but when i click on remove it gives me error in browser console

Uncaught TypeError: Cannot read property 'replace' of undefined
  also it doesn't work as accepted to add or remove nested attributes.

model: -

```<code>class User < ApplicationRecord
    has_many :photos
    accepts_nested_attributes_for :photos, allow_destroy: true
end
</code>```

controller: -

```<code>  def new
    @user = User.new
    @user.photos.build if @user.photos.none?
  end
</code>```

view: - new.html.erb

```<code><%= form_for @user do |f| %>
  <%= render 'shared/errors', object: @user %>
  <div class="form-group">
    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control'%>
  </div>
   <%=f.nested_fields_for :photos do |photo|%>
    <%=photo.remove_nested_fields_link 'Remove'%>
    <%=photo.file_field :attachment%>
    <%=photo.add_nested_fields_link :photos, 'Next Photo'%>
   <%end%>
  <%= f.submit 'Submit', class: 'btn btn-primary' %>
<% end %>
</code>```

application.js.erb :-

```<code>//= require jquery
//= require jquery_ujs
//= require nested_form_fields
//= require jquery-ui
//= require turbolinks
//= require_tree .
</code>```

kindly help me out.

答:
I think may be it is because of these line of code

```<code><%=photo.add_nested_fields_link :photos, 'Next Photo'%>
</code>```

remove_nested_fields_link needs to be called within the nested_fields_for call and add_nested_fields_link outside of it via the parent builder.

so it should be

```<code><%= f.add_nested_fields_link :photos, 'Next Photo'%>
</code>```

So code look like

```<code><%= form_for @user do |f| %>
  <%= render 'shared/errors', object: @user %>
  <div class="form-group">
    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control'%>
  </div>
   <%=f.nested_fields_for :photos do |photo|%>
    <%=photo.remove_nested_fields_link 'Remove'%>
    <%=photo.file_field :attachment%>
   <%end%>
   <%=f.add_nested_fields_link :photos, 'Next Photo'%>
  <%= f.submit 'Submit', class: 'btn btn-primary' %>
<% end %>
</code>```

Body:
I'm using gem 'nested_form_fields', but when i click on remove it gives me error in browser console

Uncaught TypeError: Cannot read property 'replace' of undefined
  also it doesn't work as accepted to add or remove nested attributes.

model: -

class User < ApplicationRecord
    has_many :photos
    accepts_nested_attributes_for :photos, allow_destroy: true
end

controller: -

  def new
    @user = User.new
    @user.photos.build if @user.photos.none?
  end

view: - new.html.erb

<%= form_for @user do |f| %>
  <%= render 'shared/errors', object: @user %>

    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>

    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control'%>

   <%=f.nested_fields_for :photos do |photo|%>
    <%=photo.remove_nested_fields_link 'Remove'%>
    <%=photo.file_field :attachment%>
    <%=photo.add_nested_fields_link :photos, 'Next Photo'%>
   <%end%>
  <%= f.submit 'Submit', class: 'btn btn-primary' %>
<% end %>

application.js.erb :-

//= require jquery
//= require jquery_ujs
//= require nested_form_fields
//= require jquery-ui
//= require turbolinks
//= require_tree .

kindly help me out.

Body:
I think may be it is because of these line of code

<%=photo.add_nested_fields_link :photos, 'Next Photo'%>

remove_nested_fields_link needs to be called within the nested_fields_for call and add_nested_fields_link outside of it via the parent builder.

so it should be

<%= f.add_nested_fields_link :photos, 'Next Photo'%>

So code look like

<%= form_for @user do |f| %>
  <%= render 'shared/errors', object: @user %>
  <div class="form-group">
    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control'%>
  </div>
   <%=f.nested_fields_for :photos do |photo|%>
    <%=photo.remove_nested_fields_link 'Remove'%>
    <%=photo.file_field :attachment%>
   <%end%>
   <%=f.add_nested_fields_link :photos, 'Next Photo'%>
  <%= f.submit 'Submit', class: 'btn btn-primary' %>
<% end %>


问:
Linux How to change the Interrupt vector table device driver with my device driver?
I want to replace the keyboard device driver with my own device driver, that will just see if I pressed exit and if so will print the time (and if not, it will pass control to the normal device driver that I removed). </p>

答:
About changing vector table. It is not done by driver. Linux kernel setup interrupt vector table during booting system.

In linux a device is bound to a driver. If you want original driver not to work, you have to unload it and load your driver. Both can't work at same time. Also you need to build both drivers as loadable modules.


Title: In python. Use the format of one list to another list

Body:
list1 = [['WA', 'WA'], ['DC'], ['HI'], ['NJ', 'NJ', 'NJ', 'NJ', 'NJ'], ['TX', 'TX', 'TX'], ['LA', 'LA'], ['NC'], ['NY'], ['IL', 'IL'], ['GA'], ['MA'], ['AZ']]

list2 = [0.875, 10.875, 0, 0, 0, 0, 0.0, 0.0, 10.0, 0, 0, 0, 0.625, -0.25, 0, 10.0, 0.5, 0, 0, 10.0, 9.25]

I want the list3 be like this:

list 3 = [[0.875, 10.875], [0], [0], [0, 0, 0.0, 0.0, 10.0], [0, 0, 0], [0.625, -0.25], [0], [10.0], [0.5, 0], [0], [10.0], [9.25]]

I had already get the index of the list1 like that:

index_list = [[0, 1], [2], [3], [4, 5, 6, 7, 8], [9, 10, 11], [12, 13], [14], [15], [16, 17], [18], [19], [20]]

Body:
How about an iterator solution:

list1 = [['WA', 'WA'], ['DC'], ['HI'], ['NJ', 'NJ', 'NJ', 'NJ', 'NJ'], ['TX', 'TX', 'TX'], ['LA', 'LA'], ['NC'], ['NY'], ['IL', 'IL'], ['GA'], ['MA'], ['AZ']]

list2 = [0.875, 10.875, 0, 0, 0, 0, 0.0, 0.0, 10.0, 0, 0, 0, 0.625, -0.25, 0, 10.0, 0.5, 0, 0, 10.0, 9.25]

f = (x for x in list2)  # iterator

list3 = []
for sub in list1:
  for i, _ in enumerate(sub):
    sub[i] = next(f)  # go fetch me the next element of list2
  list3.append(sub)
print(list3)  # -> [[0.875, 10.875], [0], [0], [0, 0, 0.0, 0.0, 10.0], [0, 0, 0], [0.625, -0.25], [0], [10.0], [0.5, 0], [0], [10.0], [9.25]]**


问:
DAO method can be annotated with only one of the following:Insert,Delete,Query,Update
Im new of Room library and want to make simple project .

Here is entity class.

```<code>@Entity(tableName = "user")
public class User {

    @PrimaryKey
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

Here is dao class.

```<code>@Dao
public interface UserDao extends Dao {

    @Query("SELECT * FROM user")
    List<User> getAll();

    @Insert
    void insert(User users);

}
</code>```

Here is AppDatabase class.

```<code>@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase INSTANCE;

    public abstract UserDao userDao();

    public static AppDatabase getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "database-test")
                            .allowMainThreadQueries()
                            .build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}
</code>```

And here is my mainactivity.

```<code>User user = new User();
        user.setName("Test");
        user.setId(2);

        AppDatabase.getAppDatabase(this).userDao().insert(user);
        AppDatabase.getAppDatabase(this).userDao().getAll();
</code>```

But when I run this code above . I get error behind below .

Error:(14, 8) error: Abstract method in DAO must be annotated with
  interface android.arch.persistence.room.Query AND interface
  android.arch.persistence.room.Insert

I search it but cannot find anything . Thanks for any suggestion .

答:
For my need , i've used an abstract class like this : </p>

```<code>public interface IMainDao {
String getId();
}

@Dao
public abstract class UserDao extends IMainDao {

@Query("SELECT * FROM user")
List<User> getAll();

//from IUserDao
@Override
public String getId() {
    return "";
  }
}
</code>```

Body:
Im new of Room library and want to make simple project .

Here is entity class.

@Entity(tableName = "user")
public class User {

    @PrimaryKey
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Here is dao class.

@Dao
public interface UserDao extends Dao {

    @Query("SELECT * FROM user")
    List<User> getAll();

    @Insert
    void insert(User users);

}

Here is AppDatabase class.

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase INSTANCE;

    public abstract UserDao userDao();

    public static AppDatabase getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "database-test")
                            .allowMainThreadQueries()
                            .build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}

And here is my mainactivity.

User user = new User();
        user.setName("Test");
        user.setId(2);

        AppDatabase.getAppDatabase(this).userDao().insert(user);
        AppDatabase.getAppDatabase(this).userDao().getAll();

But when I run this code above . I get error behind below .

Error:(14, 8) error: Abstract method in DAO must be annotated with
  interface android.arch.persistence.room.Query AND interface
  android.arch.persistence.room.Insert

I search it but cannot find anything . Thanks for any suggestion .

Body:
For my need , i've used an abstract class like this :

public interface IMainDao {
String getId();
}

@Dao
public abstract class UserDao extends IMainDao {

@Query("SELECT * FROM user")
List<User> getAll();

//from IUserDao
@Override
public String getId() {
    return "";
  }
}


问:
How can I generate these signals in Simulink?
The signals are:

Tb is bit time = 0.001s. Basically, first is square wave with 50% duty cycle and second is with 100 percent duty cycle. I tried using Pulse Generator, it is not giving me negative output and it does not let me choose 100 for duty cycle.

How can I do this in Simulink?

答:
Behold, the Simulink model that generates the first signal:

The amplitude of the Pulse Generator is set to 2/sqrt(Tb), the duty cycle to 50%, and the period to Tb, where Tb is a variable in the (model) workspace.

As for the second graph; a square wave with 100% duty cycle:

There is, of course, no difference between a constant-valued signal and a square wave with 100% duty cycle, which is what Simulink nags about. I don't know why the Mathworks decided to explicitly forbid 100% duty cycles from Pulse Generator blocks, but oh well.


问:
Preventing unncessary cursor after maxlength complete on input
```<code><input type="text" maxlength="3" style="letter-spacing: 0.9em;">
</code>```

We can put the cursor from our mouse to fourth position. How can we prevent this?

fiddle

答:
You can use blur() to focus out

<input type="text" maxlength="3" onkeyup="if(this.value.length == 3) this.blur()">```
</div>
</div>
</p>

<p><strong>Update</strong></p>

<p>Also you can disable when you click or select using keyboard too using <code>onfocus()</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" maxlength="3" onkeyup="if(this.value.length == 3) this.blur()" onfocus="if(this.value.length == 3) this.blur()"></code>```

Hope it helps

Body:
<input type="text" maxlength="3" style="letter-spacing: 0.9em;">

We can put the cursor from our mouse to fourth position. How can we prevent this?

fiddle

Body:
You can use blur() to focus out

<input type="text" maxlength="3" onkeyup="if(this.value.length == 3) this.blur()">

Update

Also you can disable when you click or select using keyboard too using onfocus()

<input type="text" maxlength="3" onkeyup="if(this.value.length == 3) this.blur()" onfocus="if(this.value.length == 3) this.blur()">

Hope it helps


问:
Get UID firebase auth in variable
Is there a way to get your UID from firebase into a variable? I tried this but the variable is undefined.</p>

```<code>var userUID;

firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
        userUID = user.uid;
    } else {}
});

console.log(userUID);
</code>```

答: onAuthStateChanged is not a synchronous operation. This is why console.log(uid) immediately after will return undefined. You have to wait for the operation to resolve with the current user before you run the logic that needs this uid.

Title: Get UID firebase auth in variable

Body:
Is there a way to get your UID from firebase into a variable? I tried this but the variable is undefined.

var userUID;

firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
        userUID = user.uid;
    } else {}
});

console.log(userUID);


问:
I want to display job with company that related to single postjob by category in laravel?
I have three table below:
I want to display all Related job post by category in Single jobpost. and I already have single job post page but in the same single job page I want to display related jobs in the left side. see my picture!

what is controller should be and in the Single job page (view) should be? please help?

My jobController

```<code> public function show($id, $company_id)
    {
        $singleJob = Job::find($id);
        $company = Company::find($company_id);
        $similarJob = Job::with('company')->where('category_id', $id)->get();
        return view('pages.single-job')->with([
            'singleJob'=> $singleJob,
            'company'=> $company,
            'similarJob' => $similarJob,
        ]);
    }
</code>```

My relationship

```<code>job.php
public function company(){
    return $this->belongsTo(Company::class);
}

Job.php
public function category(){
return $this->belongsTo(Category::class);
}

//category.php
 public function job(){
        return $this->hasMany(Job::class);
    }

//company.php
    public function job(){
        return $this->hasMany(Job::class);
    }
</code>```

Job table

```<code>    Schema::create('jobs', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('company_id');
        $table->string('jobTitle');
        $table->longText('jobDescription');
</code>```

Company Table

```<code>Schema::create('company_types', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('admin_id');
            $table->string('name');
            $table->timestamps();
        });
</code>```

Category table

```<code> Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('name');
            $table->timestamps();
        });
</code>```

答:
You can use whereHas like this :

```<code>public function show($id, $company_id)
{
    $singleJob = Job::find($id);
    $company = Company::find($company_id);
    $similarJobs = Job::with('company')
                       ->whereHas('category', function ($query) use($singleJob) {
                                $query->where('id', $singleJob->category->id);
                            })
                       ->get();
    return view('pages.single-job')->with([
        'singleJob'=> $singleJob,
        'company'=> $company,
        'similarJobs' => $similarJobs,
    ]);
}
</code>```

And in the view you can use it like this :

```<code>@foreach ($similarJobs as $similarJob)
    // Add the job partial, componnent or just your HTML here for showing the Job
@endforeach
</code>```

For the question in the comment, to find jobs that have a company that belongs to a given industry :

```<code>$some_industry_type_id = 1;
$jobsOfIndustryType = Job::whereHas('company', function ($query) use($some_industry_type_id) {
                                    $query->where('industry_type_id', $some_industry_type_id);
                                })
                           ->get();
</code>```

Body:
I have three table below:
I want to display all Related job post by category in Single jobpost. and I already have single job post page but in the same single job page I want to display related jobs in the left side. see my picture!

what is controller should be and in the Single job page (view) should be? please help?

My jobController

 public function show($id, $company_id)
    {
        $singleJob = Job::find($id);
        $company = Company::find($company_id);
        $similarJob = Job::with('company')->where('category_id', $id)->get();
        return view('pages.single-job')->with([
            'singleJob'=> $singleJob,
            'company'=> $company,
            'similarJob' => $similarJob,
        ]);
    }

My relationship

job.php
public function company(){
    return $this->belongsTo(Company::class);
}

Job.php
public function category(){
return $this->belongsTo(Category::class);
}

//category.php
 public function job(){
        return $this->hasMany(Job::class);
    }

//company.php
    public function job(){
        return $this->hasMany(Job::class);
    }

Job table

    Schema::create('jobs', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('company_id');
        $table->string('jobTitle');
        $table->longText('jobDescription');

Company Table

Schema::create('company_types', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('admin_id');
            $table->string('name');
            $table->timestamps();
        });

Category table

 Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('name');
            $table->timestamps();
        });

Body:
You can use whereHas like this :

public function show($id, $company_id)
{
    $singleJob = Job::find($id);
    $company = Company::find($company_id);
    $similarJobs = Job::with('company')
                       ->whereHas('category', function ($query) use($singleJob) {
                                $query->where('id', $singleJob->category->id);
                            })
                       ->get();
    return view('pages.single-job')->with([
        'singleJob'=> $singleJob,
        'company'=> $company,
        'similarJobs' => $similarJobs,
    ]);
}

And in the view you can use it like this :

@foreach ($similarJobs as $similarJob)
    // Add the job partial, componnent or just your HTML here for showing the Job
@endforeach

For the question in the comment, to find jobs that have a company that belongs to a given industry :

$some_industry_type_id = 1;
$jobsOfIndustryType = Job::whereHas('company', function ($query) use($some_industry_type_id) {
                                    $query->where('industry_type_id', $some_industry_type_id);
                                })
                           ->get();


问:
On adding a class, .click does not trigger - Using jQuery
I added a span with a class, but .click does not trigger.

Adding a span class code

```<code>var TA = '<span class="TS" id="'+$('#TT').attr('value')+'" style=" color:#fff; margin-left:5px; font-family:arial; font-size:12px">* '+$('#TT').attr('value')+'</span>';
$('#QLT').append(TA);
</code>```

This adds a span .TS to a div .TX. I want to trigger .TS using .click, the code

```<code>  $('.TS').click(function() {
   alert("ok");

  });
</code>```

But this does not trigger.  What is wrong, Appreciate all assistance.

Thanks
Jean

答:
You probably defined the click handler before you did $('#QLT').append(TA). Thus the click handler didn't know about the new element with class .TS when it was bound.

You can manually re-bind it, or use jQuery's cool live function, which will automatically bind when a new element with class TS is inserted into the DOM:

```<code>$('.TS').live('click', function() {
   alert("ok");
  });
</code>```

Body:
I added a span with a class, but .click does not trigger.

Adding a span class code

var TA = '* '+$('#TT').attr('value')+'';
$('#QLT').append(TA);

This adds a span .TS to a div .TX. I want to trigger .TS using .click, the code

  $('.TS').click(function() {
   alert("ok");

  });

But this does not trigger.  What is wrong, Appreciate all assistance.

Thanks
Jean

Body:
You probably defined the click handler before you did $('#QLT').append(TA). Thus the click handler didn't know about the new element with class .TS when it was bound.

You can manually re-bind it, or use jQuery's cool live function, which will automatically bind when a new element with class TS is inserted into the DOM:

$('.TS').live('click', function() {
   alert("ok");
  });


问:
Bottom navbar show/hide on 1-click - CSS
On my mobile screen I have at the bottom of the main content a navbar with the title just popping up.

I would like when I touch the title, to animate the transition to show the whole hidden div.

And then when I click again on the title it animates back towards its initial position.

I managed to only do the first part with jQuery without animation.
If you have any suggestions in full CSS I'm also interested.

$('.open-nav').click(function () {
    $('.navbar-bottom').css('bottom', '0');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
    width: 200px;
    border: 1px solid black;
    height: 100vh;
}
.open-nav {
    cursor: pointer;
}
.navbar-bottom {
    height: 158px;
    background-color: yellow;
    width: 100%;
    display: flex;
    flex-direction: column;
    position: fixed;
    bottom: -112px;
    width: 200px;
}</code>```

WHAT OFFER ?

DO AN OFFER

                OFFER HIM

                OFFER YOU

                OFFER THEM

                OFFER THAT

```

答:
Use toggleClass() to toggle the hidden div and transition for the animation

$('.open-nav').click(function() {
  $('.navbar-bottom').toggleClass("opened");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 200px;
  border: 1px solid black;
  height: 100vh;
}

.open-nav {
  cursor: pointer;
}

.navbar-bottom {
  height: 158px;
  background-color: yellow;
  width: 100%;
  display: flex;
  flex-direction: column;
  position: fixed;
  bottom: -112px;
  width: 200px;
  transition: all .5s;
}

.opened {
  bottom: 0;
}</code>```

WHAT OFFER ?

DO AN OFFER

          OFFER HIM

          OFFER YOU

          OFFER THEM

          OFFER THAT

```

Body:
On my mobile screen I have at the bottom of the main content a navbar with the title just popping up.

I would like when I touch the title, to animate the transition to show the whole hidden div.

And then when I click again on the title it animates back towards its initial position.

I managed to only do the first part with jQuery without animation.
If you have any suggestions in full CSS I'm also interested.

$('.open-nav').click(function () {
    $('.navbar-bottom').css('bottom', '0');
});

.container {
    width: 200px;
    border: 1px solid black;
    height: 100vh;
}
.open-nav {
    cursor: pointer;
}
.navbar-bottom {
    height: 158px;
    background-color: yellow;
    width: 100%;
    display: flex;
    flex-direction: column;
    position: fixed;
    bottom: -112px;
    width: 200px;
}

WHAT OFFER ?

DO AN OFFER

                OFFER HIM

                OFFER YOU

                OFFER THEM

                OFFER THAT

Body:
Use toggleClass() to toggle the hidden div and transition for the animation

$('.open-nav').click(function() {
  $('.navbar-bottom').toggleClass("opened");
});

.container {
  width: 200px;
  border: 1px solid black;
  height: 100vh;
}

.open-nav {
  cursor: pointer;
}

.navbar-bottom {
  height: 158px;
  background-color: yellow;
  width: 100%;
  display: flex;
  flex-direction: column;
  position: fixed;
  bottom: -112px;
  width: 200px;
  transition: all .5s;
}

.opened {
  bottom: 0;
}

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

<div class="container">
  <p>WHAT OFFER ?</p>

  <nav class="navbar-bottom">
    <div class="open-nav">
      <h3>DO AN OFFER</h3>
    </div>
    <div class="nav-content">
      <ul>
        <li>
          <a href="#">OFFER HIM</a>
        </li>
        <li>
          <a href="#">OFFER YOU</a>
        </li>
        <li>
          <a href="#">OFFER THEM</a>
        </li>
        <li>
          <a href="#">OFFER THAT</a>
        </li>
      </ul>
    </div>
  </nav>
  <div>


问:
How can I dynamically create a new .java file from a Java program?
I want to create a one .java from the Java program.  When I run the program, automatically one Java file will created in my project, and also create some run time (dynamic) variable in that file.  How can I do this?

I know for this I have to use a Reflection API like Class and Method, but what are the methods in Class and Method to do this?

答:
Apparently you want to create a new class at Runtime and use it. You can sure create a .javafile, compile it and load it from a custom class loader but that's probably not the best/easiest thing to do. Here are a bunch of solutions:

First of all if you want to extend an interface, you can use the Proxy from the Java Reflection API.

It you want to extend a class rather than implements an interface or create a class out of the blue you need to use a library to create bytecode. You can find a bunch of them on http://www.java-opensource.com/open-source/bytecode-libraries.html. Among these libraries I like javassist mainly because it is the only library to my knowledge letting you enter Java code directly rather than bytecode.

A last solution should be to use a framework like Groovy or BSH to interpret pseudo-java code.


问:
Git "push --delete" blocked remotely by update hook

I need a way to delete Git repository branches more conveniently cause an `update hook' is blocking them:

Command

git push -v -f --no-verify --delete origin test_branch
```

<h3>Output</h3>

<pre class="lang-none prettyprint-override"><code>remote: fatal: Not a valid commit name 0000000000000000000000000000000000000000
remote: error: hook declined to update refs/heads/test_branch
</code>```

I'm currently disabling the update hook temporarily, performing the delete, and then restoring the hook, so I'm looking for suggestions for something better, even perhaps altering the Perl Git hook.

I don't know anything about Perl or Git hooks, so I have these questions

I can't give a message to the push action. What is the best way to achieve something like this?

Is there any way to get the push --delete event from the hook?

Something like

if ${push --delete} then skip hook checks
```</li>
<li><p>Is there any way to create a custom parameter to the <code>push</code> operation in order to skip the hook? Something like</p>

<pre class="lang-none prettyprint-override"><code>if command line contains --imgod then skip hook checks
</code>```

I'm totally groping in the dark.

This is the update hook definition from the Git documentation

UPDATE HOOK
  This hook is invoked by git-receive-pack on the remote repository, which happens when a git push is done on a local
  repository. Just before updating the ref on the remote repository, the
  update hook is invoked. Its exit status determines the success or
  failure of the ref update.

The hook executes once for each ref to be updated, and takes three
  parameters:

the name of the ref being updated,

the old object name stored in the ref,

and the new object name to be stored in the ref

A zero exit from the update hook allows the ref to be updated. Exiting
  with a non-zero status prevents git-receive-pack from updating that
  ref.

This hook can be used to prevent forced update on certain refs by
  making sure that the object name is a commit object that is a
  descendant of the commit object named by the old object name. That is,
  to enforce a "fast-forward only" policy.

It could also be used to log the old..new status. However, it does not
  know the entire set of branches, so it would end up firing one e-mail
  per ref when used naively, though. The post-receive hook is more
  suited to that.

In an environment that restricts the users' access only to git
  commands over the wire, this hook can be used to implement access
  control without relying on filesystem ownership and group membership.
  See git-shell[1] for how you might use the login shell to restrict the
  user’s access to only git commands.

Both standard output and standard error output are forwarded to git
  send-pack on the other end, so you can simply echo messages for the
  user.

The default update hook, when enabled—and with hooks.allowunannotated
  config option unset or set to false—prevents unannotated tags to be
  pushed.

ANSWER:

i found a way to catch the branch deletion event into the update hook and to skip the logic of the hook in all the other cases:

zero="0000000000000000000000000000000000000000"
if [ "$refname" == "refs/heads/*"] && [ "$newrev" == "$zero" ];
then
      exit 0
else
      perform_your_checks()
fi
```

more info can be found in the update.sample GIT template.

答:
I can't give a message to the push action. What is the best way to achieve something like this?

You can't. What does that even mean?

Is there any way to get the push --delete event from the hook? Something like if ${push --delete} then skip hook checks

Yes, as you can see from the error message you got, in the case of a delete, the third argument ("new object name") will be 0000000000000000000000000000000000000000, which you can check for.

Is there any way to create a custom parameter to the push operation in order to skip the hook?

No. A client can't decide whether or not hooks are run on the server. This is a deliberate decision to allow servers to enforce policy through hooks.

Body:
I need a way to delete Git repository branches more conveniently cause an `update hook' is blocking them:

Command

git push -v -f --no-verify --delete origin test_branch

Output

remote: fatal: Not a valid commit name 0000000000000000000000000000000000000000
remote: error: hook declined to update refs/heads/test_branch

I'm currently disabling the update hook temporarily, performing the delete, and then restoring the hook, so I'm looking for suggestions for something better, even perhaps altering the Perl Git hook.

I don't know anything about Perl or Git hooks, so I have these questions

I can't give a message to the push action. What is the best way to achieve something like this?

Is there any way to get the push --delete event from the hook?

Something like

if ${push --delete} then skip hook checks

Is there any way to create a custom parameter to the push operation in order to skip the hook? Something like

if command line contains --imgod then skip hook checks

I'm totally groping in the dark.

This is the update hook definition from the Git documentation

UPDATE HOOK
  This hook is invoked by git-receive-pack on the remote repository, which happens when a git push is done on a local
  repository. Just before updating the ref on the remote repository, the
  update hook is invoked. Its exit status determines the success or
  failure of the ref update.

The hook executes once for each ref to be updated, and takes three
  parameters:

the name of the ref being updated,

the old object name stored in the ref,

and the new object name to be stored in the ref

A zero exit from the update hook allows the ref to be updated. Exiting
  with a non-zero status prevents git-receive-pack from updating that
  ref.

This hook can be used to prevent forced update on certain refs by
  making sure that the object name is a commit object that is a
  descendant of the commit object named by the old object name. That is,
  to enforce a "fast-forward only" policy.

It could also be used to log the old..new status. However, it does not
  know the entire set of branches, so it would end up firing one e-mail
  per ref when used naively, though. The post-receive hook is more
  suited to that.

In an environment that restricts the users' access only to git
  commands over the wire, this hook can be used to implement access
  control without relying on filesystem ownership and group membership.
  See git-shell[1] for how you might use the login shell to restrict the
  user’s access to only git commands.

Both standard output and standard error output are forwarded to git
  send-pack on the other end, so you can simply echo messages for the
  user.

The default update hook, when enabled—and with hooks.allowunannotated
  config option unset or set to false—prevents unannotated tags to be
  pushed.

ANSWER:

i found a way to catch the branch deletion event into the update hook and to skip the logic of the hook in all the other cases:

zero="0000000000000000000000000000000000000000"
if [ "$refname" == "refs/heads/*"] && [ "$newrev" == "$zero" ];
then
      exit 0
else
      perform_your_checks()
fi

more info can be found in the update.sample GIT template.


问:
React Native 0.40.0: Ordered comparison between pointer and zero ('NSNumber *' and 'int')
I have a React Native project that is still on 0.40.0 and when I try to build in XCode for Simulator:

Ordered comparison between pointer and zero ('NSNumber *' and 'int')

It's in the file RCTJavaScriptLoader.mm in React.xcodeproj > React > Base

Because this error happens in a React Native file I have no idea what it is trying to tell me. The code block is:

```<code>- (NSString *)description
{
  NSMutableString *desc = [NSMutableString new];
  [desc appendString:_status ?: @"Loading"];

  if (_total > 0) { // ERROR HAPPENS HERE
    [desc appendFormat:@" %ld%% (%@/%@)", (long)(100 * [_done integerValue] / [_total integerValue]), _done, _total];
  }
  [desc appendString:@"\u2026"];
  return desc;
}
</code>```

I have tried to clean the project, I even deleted the ios folder and regenerated it by using react-native upgrade and it didn't help after I linked everything.

答:
Explanation on the issue:

if (_total > 0) => if ([_total integerValue] > 0) because _total is a NSNumber. Related question on SO.

For the rest, it's an issue on React-Native that have been fixed since the 3th of January on that commit.
According to the commit, it should be then fixed on version >= v0.51.0-rc.3 and it still fixed on the current version (no regression).

The recommendation is then to update your React version.

Body:
I have a React Native project that is still on 0.40.0 and when I try to build in XCode for Simulator:

Ordered comparison between pointer and zero ('NSNumber *' and 'int')

It's in the file RCTJavaScriptLoader.mm in React.xcodeproj > React > Base

Because this error happens in a React Native file I have no idea what it is trying to tell me. The code block is:

- (NSString *)description
{
  NSMutableString *desc = [NSMutableString new];
  [desc appendString:_status ?: @"Loading"];

  if (_total > 0) { // ERROR HAPPENS HERE
    [desc appendFormat:@" %ld%% (%@/%@)", (long)(100 * [_done integerValue] / [_total integerValue]), _done, _total];
  }
  [desc appendString:@"\u2026"];
  return desc;
}

I have tried to clean the project, I even deleted the ios folder and regenerated it by using react-native upgrade and it didn't help after I linked everything.