问:
laravel jquery select2 multiselect - initialize selected elements
Good morning everybody, I'm stuck while trying to set initial selected options (got through an ajax requests) to a jquery select2 (multi-select). If I use the control, multi selection works just fine. The problem arise when I have to edit a previously saved model, as none of the options I previously selected are shown.

This is my view:

```<code><div class="form-group {{ $errors->has('pubblicazione_giuridica_id') ? 'has-error' : ''}}">
    {!! Form::label('pubblicazione_giuridica_id', 'Law Pubs', ['class' => 'col-sm-3 control-label']) !!}
    <div class="col-sm-6">
        {!! Form::select('pubblicazione_giuridica_id[]', [$pubGiurList], null, ['class' => 'form-control', 'id'=>'select-pgiur', 'multiple'=>'multiple']) !!}
        {!! $errors->first('pubblicazione_giuridica_id', '<p class="help-block">:message</p>') !!}
    </div>
</code>```

The javascript:

```<code>$('#select-pgiur').select2({
    ajax: {
        url: "{!! URL::to('/gare/proc-getpubgiur') !!}",
        dataType: 'json',
        delay: 150,
        data: function (params) {
            return { q: params.term, };
        },
        processResults: function (data, params) {
            return { results: data.items, };
        },
        cache: true
    },
    language: 'it',
    theme: "bootstrap",
    placeholder: "Choose an option."
});
</code>```

The Controller:

```<code>public function edit($id, Request $request) {
    $procedure = $this->getProcedure($id, $request, true);
    if (!$procedure) {
        return redirect('gare/procedure')->with('alert-warning', 'Gara non trovata - Operazione non consentita');
    }
    return view('gare.procedures.edit', [ 'procedure'=>$procedure, 'opChoiceList'=>$this->getOpChoiceList(), 'pubGiurList'=>json_encode(GaraPubblicazioneGiuridica::GetPubByGaraId($procedure->id)) ]);
}
</code>```

Model:

```<code>public static function GetPubByGaraId($id){
    //TODO: visualizzare le selected publications
    $procagg = GaraPubblicazioneGiuridica::where('gara_id','=',$id)->select('id')->get();
    if($procagg){
        $plucked = $procagg->pluck('nome');
        $toReturn = array();
        foreach($plucked as $key=>$value){
            $toReturn[$key]=$value;
        }
        return $toReturn;
    }
    return "";
}
</code>```

Could you shed some light on this?
Thank you in advance.

答:
When you make a dropdown selector you can specify the initially selected options:

```<code>Form::select(
   'pubblicazione_giuridica_id[]',
   [$pubGiurList],
   $opChoiceList,
  ['class' => 'form-control', 'id'=>'select-pgiur', 'multiple'=>'multiple']
)
</code>```

However this means you need to pre-populate your AJAX select2 dropdown with the initially selected options.

Body:
Good morning everybody, I'm stuck while trying to set initial selected options (got through an ajax requests) to a jquery select2 (multi-select). If I use the control, multi selection works just fine. The problem arise when I have to edit a previously saved model, as none of the options I previously selected are shown.

This is my view:

has('pubblicazione_giuridica_id') ? 'has-error' : ''}}">
    {!! Form::label('pubblicazione_giuridica_id', 'Law Pubs', ['class' => 'col-sm-3 control-label']) !!}

        {!! Form::select('pubblicazione_giuridica_id[]', [$pubGiurList], null, ['class' => 'form-control', 'id'=>'select-pgiur', 'multiple'=>'multiple']) !!}
        {!! $errors->first('pubblicazione_giuridica_id', '
:message
') !!}

The javascript:

$('#select-pgiur').select2({
    ajax: {
        url: "{!! URL::to('/gare/proc-getpubgiur') !!}",
        dataType: 'json',
        delay: 150,
        data: function (params) {
            return { q: params.term, };
        },
        processResults: function (data, params) {
            return { results: data.items, };
        },
        cache: true
    },
    language: 'it',
    theme: "bootstrap",
    placeholder: "Choose an option."
});

The Controller:

public function edit($id, Request $request) {
    $procedure = $this->getProcedure($id, $request, true);
    if (!$procedure) {
        return redirect('gare/procedure')->with('alert-warning', 'Gara non trovata - Operazione non consentita');
    }
    return view('gare.procedures.edit', [ 'procedure'=>$procedure, 'opChoiceList'=>$this->getOpChoiceList(), 'pubGiurList'=>json_encode(GaraPubblicazioneGiuridica::GetPubByGaraId($procedure->id)) ]);
}

Model:

public static function GetPubByGaraId($id){
    //TODO: visualizzare le selected publications
    $procagg = GaraPubblicazioneGiuridica::where('gara_id','=',$id)->select('id')->get();
    if($procagg){
        $plucked = $procagg->pluck('nome');
        $toReturn = array();
        foreach($plucked as $key=>$value){
            $toReturn[$key]=$value;
        }
        return $toReturn;
    }
    return "";
}

Could you shed some light on this?
Thank you in advance.

Body:
When you make a dropdown selector you can specify the initially selected options:

Form::select(
   'pubblicazione_giuridica_id[]',
   [$pubGiurList],
   $opChoiceList,
  ['class' => 'form-control', 'id'=>'select-pgiur', 'multiple'=>'multiple']
)

However this means you need to pre-populate your AJAX select2 dropdown with the initially selected options.


来源: stackexchange

问:
Unpacking argument in print statements
I would like to know if there is a way to unpack values in a print statement, the same way it is possible to unpack arguments in a function f

This works:

```<code>import numpy
er = numpy.array([0.36666667, 0.46666667, 0.43333333, numpy.nan])
l = 0.8
print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (er[0], er[1], er[2], er[3], l))
# 0.367 | 0.467 | 0.433 | nan | 0.8
</code>```

However, I would like to avoid multiple er[x] and instead use something like *er as in:

```<code>def f(a,b,c,d):
    return True
print(f(*er))
# True
</code>```

I tried:

```<code>#print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (*(er, numpy.array([l]))))
</code>```

But this last line generates "SyntaxError: invalid syntax" error.

Any ideas?

答:
```<code>print('{:.3f} | {:.3f} | {:.3f} | {:.1f} | {:.3f}'.format(*(list(er) + [l])))
</code>```

Make sure all your args are in one place before you unpack them.

ContentLicense: CC BY-SA 3.0

Title: Unpacking argument in print statements

Body:
I would like to know if there is a way to unpack values in a print statement, the same way it is possible to unpack arguments in a function f

This works:

import numpy
er = numpy.array([0.36666667, 0.46666667, 0.43333333, numpy.nan])
l = 0.8
print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (er[0], er[1], er[2], er[3], l))
# 0.367 | 0.467 | 0.433 | nan | 0.8

However, I would like to avoid multiple er[x] and instead use something like *er as in:

def f(a,b,c,d):
    return True
print(f(*er))
# True

I tried:

#print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (*(er, numpy.array([l]))))

But this last line generates "SyntaxError: invalid syntax" error.

Any ideas?

Body:
print('{:.3f} | {:.3f} | {:.3f} | {:.1f} | {:.3f}'.format(*(list(er) + [l])))

Make sure all your args are in one place before you unpack them.


问:
Unable to restart glassfish 3 server
We have deployed application on glassfish3 server on Windows machine.
The server and application were running fine. In the glassfish console, I restarted the server but it didn't start again.

I also tried from the command prompt(as administrator) but getting below error log:

C:\glassfish3\glassfish\bin> asadmin -p 4841 start-domain domain1
  Waiting for domain1 to start ..Error starting domain domain1. The
  server exited prematurely with exit code 1. Before it died, it
  produced the following output:

Launching GlassFish on Felix platform ERROR: Error parsing system
  bundle export statement: org.osgi.framework; version=1.6.0,
  org.osgi.framework.launch; versi on=1.0.0, org.osgi.framework.wiring;
  version=1.0.0, org.osgi.framework.startlevel; version=1.0.0,
  org.osgi.framework.hoo ks.bundle; version=1.0.0,
  org.osgi.framework.hooks.resolver; version=1.0.0,
  org.osgi.framework.hooks.service; version=1.
  1.0, org.osgi.framework.hooks.weaving; version=1.0.0, org.osgi.service.packageadmin; version=1.2.0, org.osgi.service.sta
  rtlevel; version=1.1.0, org.osgi.service.url; version=1.0.0,
  org.osgi.util.tracker; version=1.5.0, , org.glassfish.embed
  dable;org.glassfish.embeddable.spi;version=3.1.1
  (org.osgi.framework.BundleException: Exported package names cannot be
  z ero length.) ERROR: Unable to re-install
  file:/C:/glassfish3/glassfish/modules/javax.transaction.jar
  (org.osgi.framework.BundleExcept ion: Could not create bundle object.)
  ERROR: Unable to re-install
  file:/C:/glassfish3/glassfish/modules/webservices-extra-jdk-packages.jar
  (org.osgi.framework .BundleException: Could not create bundle object.)
  ERROR: Unable to re-install
  file:/C:/glassfish3/glassfish/modules/flashlight-extra-jdk-packages.jar
  (org.osgi.framework. BundleException: Could not create bundle object.)
  ERROR: Unable to re-install
  file:/C:/glassfish3/glassfish/modules/glassfish-corba-omgapi.jar
  (org.osgi.framework.BundleE xception: Could not create bundle object.)
  ERROR: Unable to re-install
  file:/C:/glassfish3/glassfish/modules/glassfish-extra-jre-packages.jar
  (org.osgi.framework.B undleException: Could not create bundle object.)
  ERROR: Unable to re-install
  file:/C:/glassfish3/glassfish/modules/glassfish-oracle-jdbc-driver-packages.jar
  (org.osgi.fr amework.BundleException: Could not create bundle object.)
  ERROR: Bundle jaxb-api [2] Error starting
  file:/C:/glassfish3/glassfish/modules/endorsed/jaxb-api-osgi.jar
  (org.osgi.fra mework.BundleException: Unresolved constraint in bundle
  jaxb-api [2]: Unable to resolve 2.0: missing requirement [2.0] o
  sgi.wiring.package; (osgi.wiring.package=javax.activation)) ERROR:
  Bundle org.glassfish.metro.webservices-api-osgi [3] Error starting
  file:/C:/glassfish3/glassfish/modules/endorsed
  /webservices-api-osgi.jar (org.osgi.framework.BundleException:
  Unresolved constraint in bundle org.glassfish.metro.webse
  rvices-api-osgi [3]: Unable to resolve 3.0: missing requirement [3.0]
  osgi.wiring.package; (&(osgi.wiring.package=javax.
  xml.bind)(version>=2.2.0)) [caused by: Unable to resolve 2.0: missing
  requirement [2.0] osgi.wiring.package; (osgi.wirin
  g.package=javax.activation)]) ERROR: Bundle
  org.glassfish.main.core.glassfish [101] Error starting
  file:/C:/glassfish3/glassfish/modules/glassfish.jar
  (org.osgi.framework.BundleException: Activator start error in bundle
  org.glassfish.main.core.glassfish [101].) ERROR: Bundle
  org.glassfish.hk2.osgi-adapter [202] Error starting
  file:/C:/glassfish3/glassfish/modules/osgi-adapter.jar
  (org.osgi.framework.BundleException: Unresolved constraint in bundle
  org.glassfish.hk2.osgi-adapter [202]: Unable to re solve 202.0:
  missing requirement [202.0] osgi.wiring.package;
  (&(osgi.wiring.package=com.sun.enterprise.module)(version>
  =1.1.0)) [caused by: Unable to resolve 121.0: missing requirement [121.0] osgi.wiring.package; (&(osgi.wiring.package=or
  g.jvnet.hk2.config)(version>=1.1.0)) [caused by: Unable to resolve
  37.0: missing requirement [37.0] osgi.wiring.package;  (osgi.wiring.package=javax.management)]])  ....  ....

答: I was installing Glassfish 3 (coming with JAVA EE 6) when I have configure JAVA_HOME for Java 8. The solution was to modify ./glassfish/config/asenv.conf and set AS_JAVA to point to Java 7</p>

Title: Unable to restart glassfish 3 server


问:
How to make AAC seekable over http stream using Android MediaPlayer?
I have an app using MediaPlayer that works fine when I stream progressive download MP3s.  I have tried to use that same app to stream progress download AAC files.  And it plays the files fine.  What doesn't work is when I try to skip around in the stream using MediaPlayer.seekTo() with AAC.  This again works fine in mp3.  For the AAC stream it just restarts playing over at zero.

My feeling is that is encoding related.  That AAC file hasn't been configured correctly to stream.

Here is the output from MediaInfo tool:

```<code>Size: 2.3 MB
Format: QuickTime/MPEG-4/Motion JPEG 2000 format
Stream count: 2
Duration: 00:05:02
Bit rate: 64 kb/s
Meta info:
    album_artist: Red Hot Chili Peppers
    album: The Getaway
    minor_version: 512
    encoder: Lavf57.41.100
    title: Dark Necessities
    major_brand: M4V
    track: 2
    disc: 1
    compatible_brands: isomiso2avc1
    artist: Red Hot Chili Peppers
    copyright: 2016 Warner Bros. Records Inc.
    genre: Alternative

Stream 0
Type: video
Codec: h264
Codec profile: High 10
FourCC: avc1
Duration: 00:00:00
Width: 350
Height: 350
Sample aspect ratio: 1:1
Display aspect ratio: 1:1
Pixel format: yuv420p10le
Frame rate: 90000 fps
Meta info:
    handler_name: VideoHandler
    language: und

Stream 1
Type: audio
Codec: aac
FourCC: mp4a
Duration: 00:05:02
Bit rate: 64 kb/s
Sample rate: 44100 Hz
Sample format: s16
Channel: 2
Meta info:
    handler_name: SoundHandler
    language: und
</code>```

You'll notice it's really a video file with AAC audio and no real video included.  If that's the case then I figured it needs more metadata to know where to play when I ask for a portion of the stream that may or may not be loaded. Also videos need keyframes to know where to play from so I believe no keyframes or 'hint' boxes are included in the stream/file.

I haven't had any luck with finding any real details about what is missing or if this is possible or not.  I've tested this on other versions and it seems that prior to 5.0.2 it worked.  After 5.0.2 it does not work.  I haven't found any details about what changed in that version.

So this could either be a stream encoding issue that doesn't allow us to stream this file over a progressive download http(s) stream.  Or, it could be a bug in Android Media Player created sometime around 5.0.2 timeframe.  Or it could be both.

Why isn't this working?

答:
Try with Exoplayer, it is so simple

ExoPlayer has a number of advantages over Android’s built in MediaPlayer:

Support for Dynamic Adaptive Streaming over HTTP (DASH) and SmoothStreaming, neither of which are are supported by MediaPlayer (it also supports HTTP Live Streaming (HLS), MP4, MP3, WebM, M4A, MPEG-TS and AAC).

Support for advanced HLS features, such as correct handling of #EXT-X-DISCONTINUITY tags.

The ability to customize and extend the player to suit your use case. ExoPlayer is designed specifically with this in mind, and allows many components to be replaced with custom implementations.

Easily update the player along with your application. Because ExoPlayer is a library that you include in your application apk, you have control over which version you use and you can easily update to a newer version as part of a regular application update.

Body:
I have an app using MediaPlayer that works fine when I stream progressive download MP3s.  I have tried to use that same app to stream progress download AAC files.  And it plays the files fine.  What doesn't work is when I try to skip around in the stream using MediaPlayer.seekTo() with AAC.  This again works fine in mp3.  For the AAC stream it just restarts playing over at zero.

My feeling is that is encoding related.  That AAC file hasn't been configured correctly to stream.

Here is the output from MediaInfo tool:

Size: 2.3 MB
Format: QuickTime/MPEG-4/Motion JPEG 2000 format
Stream count: 2
Duration: 00:05:02
Bit rate: 64 kb/s
Meta info:
    album_artist: Red Hot Chili Peppers
    album: The Getaway
    minor_version: 512
    encoder: Lavf57.41.100
    title: Dark Necessities
    major_brand: M4V
    track: 2
    disc: 1
    compatible_brands: isomiso2avc1
    artist: Red Hot Chili Peppers
    copyright: 2016 Warner Bros. Records Inc.
    genre: Alternative

Stream 0
Type: video
Codec: h264
Codec profile: High 10
FourCC: avc1
Duration: 00:00:00
Width: 350
Height: 350
Sample aspect ratio: 1:1
Display aspect ratio: 1:1
Pixel format: yuv420p10le
Frame rate: 90000 fps
Meta info:
    handler_name: VideoHandler
    language: und

Stream 1
Type: audio
Codec: aac
FourCC: mp4a
Duration: 00:05:02
Bit rate: 64 kb/s
Sample rate: 44100 Hz
Sample format: s16
Channel: 2
Meta info:
    handler_name: SoundHandler
    language: und

You'll notice it's really a video file with AAC audio and no real video included.  If that's the case then I figured it needs more metadata to know where to play when I ask for a portion of the stream that may or may not be loaded. Also videos need keyframes to know where to play from so I believe no keyframes or 'hint' boxes are included in the stream/file.

I haven't had any luck with finding any real details about what is missing or if this is possible or not.  I've tested this on other versions and it seems that prior to 5.0.2 it worked.  After 5.0.2 it does not work.  I haven't found any details about what changed in that version.

So this could either be a stream encoding issue that doesn't allow us to stream this file over a progressive download http(s) stream.  Or, it could be a bug in Android Media Player created sometime around 5.0.2 timeframe.  Or it could be both.

Why isn't this working?


问:
Multiple captures on same text with regexp_matches() using different regex patterns
Given the following title Olympic National Park, WA. [OC][5239x3492] the goal is to capture tags OC, 5239x3492, and also capture 5239 and 3492 as two separate captures. Thought was to use a series of positive look aheads (?=) to non-consumingly make N matches, like [\[\(\{](?=[a-zA-Z0-9\-_ \/]+)(?=[0-9]+)[\}\)\]], however this just lead to a bunch of empty strings (and confusion). Seem to have a misunderstanding of how regexp_matches or positive look aheads work, assist greatly appreciated.

Statement:

```<code>SELECT (
  regexp_matches(
    'Olympic National Park, WA. [OC][5239x3492]',
    '[\[\(\{]([a-zA-Z0-9\-_ \/]+)[\}\)\]]',
    'gi'
  )
);
</code>```

Current output:

```<code> regexp_matches
----------------
 {OC}
 {5239x3492}
(2 rows)
</code>```

Desired output:

```<code> regexp_matches
----------------
 {OC}
 {5239x3492}
 {5239}
 {3492}
(4 rows)
</code>```

答:
Matches cannot overlap in any regular expression implementation. What you can do however, is to split the matches like 5239x3492 afterwards:

```<code>select     u
from       t
cross join regexp_matches(col, '[\[\(\{]([a-z0-9 \/_-]+)[\}\)\]]', 'gi') m
left join  regexp_matches(m[1], '(\d+)x(\d+)', 'gi') s on true
cross join unnest(m || s) u
</code>```

http://rextester.com/VKDTON30263

Body:
Given the following title Olympic National Park, WA. [OC][5239x3492] the goal is to capture tags OC, 5239x3492, and also capture 5239 and 3492 as two separate captures. Thought was to use a series of positive look aheads (?=) to non-consumingly make N matches, like [\[\(\{](?=[a-zA-Z0-9\-_ \/]+)(?=[0-9]+)[\}\)\]], however this just lead to a bunch of empty strings (and confusion). Seem to have a misunderstanding of how regexp_matches or positive look aheads work, assist greatly appreciated.

Statement:

SELECT (
  regexp_matches(
    'Olympic National Park, WA. [OC][5239x3492]',
    '[\[\(\{]([a-zA-Z0-9\-_ \/]+)[\}\)\]]',
    'gi'
  )
);

Current output:

 regexp_matches
----------------
 {OC}
 {5239x3492}
(2 rows)

Desired output:

 regexp_matches
----------------
 {OC}
 {5239x3492}
 {5239}
 {3492}
(4 rows)

Body:
Matches cannot overlap in any regular expression implementation. What you can do however, is to split the matches like 5239x3492 afterwards:

select     u
from       t
cross join regexp_matches(col, '[\[\(\{]([a-z0-9 \/_-]+)[\}\)\]]', 'gi') m
left join  regexp_matches(m[1], '(\d+)x(\d+)', 'gi') s on true
cross join unnest(m || s) u

http://rextester.com/VKDTON30263


问:
efficiency of a program that checks range of variable vs another that checks values one by one?
Let assume that I have a Boolean function that receives a random number as its argument and then return True if the random number is 200, 201 or 202 and return False for other values.

The question is which one of the following functions are more efficient?

f1:

```<code>bool f1(int number) {
    if (number >= 200 && number <= 202)
        return true;
    return false;
}
</code>```

f2:

```<code>bool f2(int number) {
    if (number == 200 || number == 201 || number == 202)
        return true;
    return false;
}
</code>```

答:
Two more options for you to measure

```<code>#include <stdbool.h>
bool f3(int n) {
    if (n < 200) return 0;
    if (n > 202) return 0;
    return 1;
}
</code>```

or

```<code>#include <stdbool.h>
bool f4(int n) {
    return (n >= 200) * (n <= 202);
}
</code>```

Body:
Let assume that I have a Boolean function that receives a random number as its argument and then return True if the random number is 200, 201 or 202 and return False for other values.

The question is which one of the following functions are more efficient?

f1:

bool f1(int number) {
    if (number >= 200 && number <= 202)
        return true;
    return false;
}

f2:

bool f2(int number) {
    if (number == 200 || number == 201 || number == 202)
        return true;
    return false;
}

Body:
Two more options for you to measure

#include <stdbool.h>
bool f3(int n) {
    if (n < 200) return 0;
    if (n > 202) return 0;
    return 1;
}

or

#include <stdbool.h>
bool f4(int n) {
    return (n >= 200) * (n <= 202);
}


问:
CMake not being able to find Python Library
I am following this tutorial to install OpenCV 3.0 and Python 2.7 but however, I am getting Cmake errors at step 8.

-- Could NOT find PythonLibs: Found unsuitable version "2.7.11", but required is exact version "2.7.13" (found
  /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/bin)
  -- Could NOT find PythonInterp: Found unsuitable version "2.7.13", but required is at least "3.4" (found
  /Users/SabrinaZuraimi/.virtualenvs/cv/bin/python)
  -- Could NOT find PythonInterp: Found unsuitable version "2.7.13", but required is at least "3.2" (found
  /Users/SabrinaZuraimi/.virtualenvs/cv/bin/python)

There is 2 versions of Python(2.7.11 and 2.7.13) in the usr/local/Cellar/Python but I don't understand why there is an error saying that i can't find 2.7.13

The command that I typed into the terminal was

```<code> cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D PYTHON2_PACKAGES_PATH=~/.virtualenvs/cv/lib/python2.7/site-packages \
    -D PYTHON2_LIBRARY=/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/bin \
    -D PYTHON2_INCLUDE_DIR=/usr/local/Frameworks/Python.framework/Headers \
    -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON \
    -D BUILD_EXAMPLES=ON \
        -D INSTALL_C_EXAMPLES=OFF\
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules ..
</code>```

I am not very familiar with cmake, and I appreciate any help that I can get.

答: that tutorial is out-of-date. you can try this new tutorial</p>

Body:
I am following this tutorial to install OpenCV 3.0 and Python 2.7 but however, I am getting Cmake errors at step 8.

-- Could NOT find PythonLibs: Found unsuitable version "2.7.11", but required is exact version "2.7.13" (found
  /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/bin)
  -- Could NOT find PythonInterp: Found unsuitable version "2.7.13", but required is at least "3.4" (found
  /Users/SabrinaZuraimi/.virtualenvs/cv/bin/python)
  -- Could NOT find PythonInterp: Found unsuitable version "2.7.13", but required is at least "3.2" (found
  /Users/SabrinaZuraimi/.virtualenvs/cv/bin/python)

There is 2 versions of Python(2.7.11 and 2.7.13) in the usr/local/Cellar/Python but I don't understand why there is an error saying that i can't find 2.7.13

The command that I typed into the terminal was

 cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D PYTHON2_PACKAGES_PATH=~/.virtualenvs/cv/lib/python2.7/site-packages \
    -D PYTHON2_LIBRARY=/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/bin \
    -D PYTHON2_INCLUDE_DIR=/usr/local/Frameworks/Python.framework/Headers \
    -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON \
    -D BUILD_EXAMPLES=ON \
        -D INSTALL_C_EXAMPLES=OFF\
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules ..

I am not very familiar with cmake, and I appreciate any help that I can get.


问:
Electron <webview> back using backspace
I'm writing an electron app. I used webview to show a website inside my app. I want the website inside the webview to go back when I press the backspace key. The Official documentary on webview was not helpful for me. How do I make the webview content go back when the backspace is pressed,please?</p>

答:
So Finally I figured it out. Here is the final code.

```<code>const webview = document.querySelector('webview')
webview.addEventListener('keydown', (e)=>{
        if(e.keyCode === 8) webview.goBack();

})
</code>```

Thanks for the keypress code. ^_^

Title: Electron <webview> back using backspace

Body:
So Finally I figured it out. Here is the final code.

const webview = document.querySelector('webview')
webview.addEventListener('keydown', (e)=>{
        if(e.keyCode === 8) webview.goBack();

})

Thanks for the keypress code. ^_^


问:
Issue with @import in Chrome but not in live preview
I'm creating a simple HTML/CSS based website for a certain assignment and I've run into a smaller issue.

I had around 500 lines of code in my main.css file and it was getting hard to read and scroll through, so I've decided to split it into several .css files and link all of them into one with the @import function.

Now then, I've still got the main.css file in my main folder, and inside it the following:

@import url('/css/first.css')
@import url('/css/second.css')
.
.
.
@import url('/css/last.css')
```

I'm using Brackets as an editor, and while everything works perfectly with Brackets live preview, apparently, when I run the page manually via Chrome (by double clicking the index.html), the CSS doesn't appear at all.

Yes, /css/ is the folder inside the main folder containing all other .css files. And yes, the live preview from Brackets also uses Chrome.

答:
The @import rule could calls in multiple styles files. These files are called by the browser or User Agent when needed e.g. HTML tags call the CSS.

try this below code

```<code>@import url("../css/first.css");
@import url("../css/second.css");
@import url("../css/last.css");
</code>```

Or you can add your css by using link tag in html between  tag

```<code><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" href="../css/first.css" type="text/css" />
<link rel="stylesheet" href="../css/second.css" type="text/css" />
<link rel="stylesheet" href="../css/last.css" type="text/css" />
</head>

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

Body:
I'm creating a simple HTML/CSS based website for a certain assignment and I've run into a smaller issue.

I had around 500 lines of code in my main.css file and it was getting hard to read and scroll through, so I've decided to split it into several .css files and link all of them into one with the @import function.

Now then, I've still got the main.css file in my main folder, and inside it the following:

@import url('/css/first.css')
@import url('/css/second.css')
.
.
.
@import url('/css/last.css')

I'm using Brackets as an editor, and while everything works perfectly with Brackets live preview, apparently, when I run the page manually via Chrome (by double clicking the index.html), the CSS doesn't appear at all.

Yes, /css/ is the folder inside the main folder containing all other .css files. And yes, the live preview from Brackets also uses Chrome.

Body:
The @import rule could calls in multiple styles files. These files are called by the browser or User Agent when needed e.g. HTML tags call the CSS.

try this below code

@import url("../css/first.css");
@import url("../css/second.css");
@import url("../css/last.css");

Or you can add your css by using link tag in html between  tag

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" href="../css/first.css" type="text/css" />
<link rel="stylesheet" href="../css/second.css" type="text/css" />
<link rel="stylesheet" href="../css/last.css" type="text/css" />
</head>

<body>
</body>
</html>


问:
Variable doesn't save the current List size
So I have this piece of code here:

```<code>List<String> s1 = new ArrayList<String>();
int size = s1.size();

s1.add("A");
s1.add("B");
System.out.println(size);
s1.add("C");
s1.add("D");
System.out.println(size);
</code>```

And that's the output:

```<code>0
0
</code>```

But it should be:

```<code>2
4
</code>```

What it the problem? Why doesn't the variable size get the current List size when I call her?

Thanks for helping me!

答:
size contains the value that was assigned to it when int size = s1.size(); was executed, which is 0, since the list was empty at the time.

It isn't modified automatically when the list is modified. It has no association with the size of the list.

You do have a variable whose value is updated when the list size is changed. That's the size variable of the ArrayList class, whose value you get when you call the size() method:

```<code>/**
 * Returns the number of elements in this list.
 *
 * @return the number of elements in this list
 */
public int size() {
    return size;
}
</code>```

Therefore you don't need your variable. Simply call s1.size() to get the current size of the list.

Body:
So I have this piece of code here:

List<String> s1 = new ArrayList<String>();
int size = s1.size();

s1.add("A");
s1.add("B");
System.out.println(size);
s1.add("C");
s1.add("D");
System.out.println(size);

And that's the output:

0
0

But it should be:

2
4

What it the problem? Why doesn't the variable size get the current List size when I call her?

Thanks for helping me!

Body:
size contains the value that was assigned to it when int size = s1.size(); was executed, which is 0, since the list was empty at the time.

It isn't modified automatically when the list is modified. It has no association with the size of the list.

You do have a variable whose value is updated when the list size is changed. That's the size variable of the ArrayList class, whose value you get when you call the size() method:

/**
 * Returns the number of elements in this list.
 *
 * @return the number of elements in this list
 */
public int size() {
    return size;
}

Therefore you don't need your variable. Simply call s1.size() to get the current size of the list.


问:
How do I read my input from text area in react?
I am trying to read input from text area once I finish typing. I read somewhere that you need onBlur event handler to achieve this functionality instead of onChange. However when I use onBlur, I am not able to enter my input. Where am I going wrong?</p>

```<code>import React from 'react'
import ReactDOM from 'react-dom'
class HelloWorld extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            value: '',
        }
    }
    handleChange(event) {
        this.setState({value: event.target.value})
        console.log(this.state.value)
    }
    render(){
        return(
            <div>
                <h1>Hello World Restaurant</h1>
                <textarea placeholder="Enter name of guest:" onBlur={this.handleChange.bind(this)} value={this.state.value}></textarea>
            </div>
        )
    }
}
ReactDOM.render(<HelloWorld/>,document.getElementById('root'))
</code>```

答:
To add to Mayank's answer,

I will suggest you to make use of controlled input as git gives you more flexibility to use the values later on

You can do that like

class HelloWorld extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            value: '',
        }
    }
    handleBlur() {
        console.log('You finished typing:', this.state.value)
    }
    handleChange(event) {
        this.setState({value: event.target.value})
    }

    render(){
        return(

Hello World Restaurant

                value: {this.state.value}

                <textarea placeholder="Enter name of guest:" onChange={this.handleChange.bind(this)} value={this.state.value} onBlur={this.handleBlur.bind(this)}></textarea>

        )
    }
}

ReactDOM.render(<HelloWorld/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/></code>```

Body:
I am trying to read input from text area once I finish typing. I read somewhere that you need onBlur event handler to achieve this functionality instead of onChange. However when I use onBlur, I am not able to enter my input. Where am I going wrong?

import React from 'react'
import ReactDOM from 'react-dom'
class HelloWorld extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            value: '',
        }
    }
    handleChange(event) {
        this.setState({value: event.target.value})
        console.log(this.state.value)
    }
    render(){
        return(

Hello World Restaurant

                <textarea placeholder="Enter name of guest:" onBlur={this.handleChange.bind(this)} value={this.state.value}></textarea>

        )
    }
}
ReactDOM.render(<HelloWorld/>,document.getElementById('root'))

Body:
To add to Mayank's answer,

I will suggest you to make use of controlled input as git gives you more flexibility to use the values later on

You can do that like

class HelloWorld extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            value: '',
        }
    }
    handleBlur() {
        console.log('You finished typing:', this.state.value)
    }
    handleChange(event) {
        this.setState({value: event.target.value})
    }

    render(){
        return(
            <div>
                <h1>Hello World Restaurant</h1>
                value: {this.state.value}
                <br/>
                <textarea placeholder="Enter name of guest:" onChange={this.handleChange.bind(this)} value={this.state.value} onBlur={this.handleBlur.bind(this)}></textarea>
            </div>
        )
    }
}

ReactDOM.render(<HelloWorld/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>


问:
Can i edit the buttons of a browser dialogs?
I was wondering if it's possible to change the text of the OK/Cancel buttons in dialogs?

答:
there is not a part of html or css so you cannot change it anymore.
here for refrence</p>


问:
Pc going unresponsive when looping over a 10^8 elements in an array
When I execute python code which loops over an array of size 10^8. The pc becomes unresponsive and takes around 10 minutes to execute the code.
After it is done with the script, it stays laggy for a while.

So is that a problem due to a weak processor or is it a Ram problem, and is the only way to fix it, is to upgrade the ram?

The script could be as simple as:

```<code>arr = [x for x in range(pow(10,8))]
for i in range( len(arr) ):
   arr[i]+=1
</code>```

My Specs are:
RAM is 8 GB.
OS is Ubuntu.
Python 3.6.
Processor: Intel Core i7-3632QM 2.20GHZ

More details on what exactly happens: when I run the script I can see the memory usage for the python process keeps getting up. Then the PC becomes unresponsive. It doesn't respond to any action I give. If anything was playing in the background it stops, If i move the mouse, the cursor won't move. Until the script is actually done. Then it becomes responsive but very laggy for a while. if I try to switch the active application to another minimized application it takes quiet some time. As if the PC was just booted up. It takes a bit of time for everything to get back to normal.

答:
What's happening here is very likely paging / swapping1. Due to virtual address space, each process on your system can address a huge amount of memory - way more than you have physically in your computer. If all processes together use more memory than you have physically available, the operating system is in trouble - one approach is paging: Moving data from some processes from memory to disk.

Since your disk, even if it's an SSD, is several orders of magnitude slower than RAM, the systems gets unresponsive. Say for example the OS decides to move the block of memory which contains your mouse cursor position onto the disk. Every time it updates the cursor, this introduces a huge delay. Even after the process which consumed all the memory finishes, it will take some time to load back all data from disk to RAM.

To illustrate, on my system with a comparable processor (i5-3320M), your example code finishes in a mere 20 seconds without impact on overall system responsiveness - that is because I have 16 GiB RAM. So clearly it is not about the  "CPU [being saturated] with billions of operations". Given you have a quad-core processor, and that code uses only one thread, you have lots of spare compute cycles. Even if you were to use up all the CPU cycles, the system is usually quite responsive, because the OS scheduler does a good job balancing CPU cycles between your compute task and the process moving your mouse cursor.

Python is particularly prone to this issue, because it uses way more memory than necessary. Python 3.6.1 on my system uses ~4 GiB for the data in arr - even though 10^8 64 bit integers would only use 800 MB. That's just due to the fact that everything in python is an object. You can be more memory-efficient if you don't permanently store anything in memory in the first place or use numpy. But to discuss that, would require a more problem-oriented code example.

1: There are differences between paging and swapping, but nowadays it is used interchangeably.

Body:
When I execute python code which loops over an array of size 10^8. The pc becomes unresponsive and takes around 10 minutes to execute the code.
After it is done with the script, it stays laggy for a while.

So is that a problem due to a weak processor or is it a Ram problem, and is the only way to fix it, is to upgrade the ram?

The script could be as simple as:

arr = [x for x in range(pow(10,8))]
for i in range( len(arr) ):
   arr[i]+=1

My Specs are:
RAM is 8 GB.
OS is Ubuntu.
Python 3.6.
Processor: Intel Core i7-3632QM 2.20GHZ

More details on what exactly happens: when I run the script I can see the memory usage for the python process keeps getting up. Then the PC becomes unresponsive. It doesn't respond to any action I give. If anything was playing in the background it stops, If i move the mouse, the cursor won't move. Until the script is actually done. Then it becomes responsive but very laggy for a while. if I try to switch the active application to another minimized application it takes quiet some time. As if the PC was just booted up. It takes a bit of time for everything to get back to normal.


问:
why it returns empty value but of boolean type when no match is found
I am using the following code to search an element inside a multi dimensional array.When a match is found it returns the index.But when no match is found it returns a empty value.Not 0 or 1.But if i print out the type , it says boolean.What does that boolean mean if it returns empty.Does it mean that it will be equal to empty string ?</p>

```<code>$arr =Array
(
    0 => Array
        (
            'uid' => '100',
            'name' => 'Sandra Shush'
        ),

    1 => Array
        (
            'uid' => '5465',
            'name' => 'Stefanie Mcmohn'
        ),

    2 => Array
        (
            'uid' => '40489',
            'name' => 'Michael'
        )
);

$match = array_search('546',array_column($arr, 'uid'));

echo gettype($match);
</code>```

答:
array_search() returns FALSE when it cannot find the needle in the haystack.

The comparison is done using ==. This means, the values are converted to the same type, if needed. But their values must be the same after conversion. It doesn't match substrings.

echo(FALSE); doesn't print anything. The type of FALSE is boolean, indeed. And FALSE is == with the empty string (''), zero (0), the string that contain the number zero ('0') and other empty values.

Body:
I am using the following code to search an element inside a multi dimensional array.When a match is found it returns the index.But when no match is found it returns a empty value.Not 0 or 1.But if i print out the type , it says boolean.What does that boolean mean if it returns empty.Does it mean that it will be equal to empty string ?

$arr =Array
(
    0 => Array
        (
            'uid' => '100',
            'name' => 'Sandra Shush'
        ),

    1 => Array
        (
            'uid' => '5465',
            'name' => 'Stefanie Mcmohn'
        ),

    2 => Array
        (
            'uid' => '40489',
            'name' => 'Michael'
        )
);

$match = array_search('546',array_column($arr, 'uid'));

echo gettype($match);


问:
How to run multiple simulators on Xcode 9?
According to What's new on Xcode, Xcode 9 allows us to run multiple instance of simulator.

But what's the way to do this ?

I tried to Build & Run on different models but it Quit the current instance.

答:
I solved my problem, it's "very simple" :]

On the simulator, you must choose a new device from Hardware > Devices. The new instance will starts.

Then, choose your model on Xcode.

Here is the solution.


答:
Use below to get size of the list.</p>

```<code>System.out.println(s1.size());
</code>```

Title: Variable doesn't save the current List size

Body:
Use below to get size of the list.

System.out.println(s1.size());


问:
OnChange of a Component binding in Angular Js
I have created a component in angular js which shows some data
But on change of my customer binding i want to call some service in component controller which is not reflecting,Here is the below code

In my Test1.html

```<code><tab-customer title="Test Comp" customerCode="vm.customerCode"  functioname="fnTest"></tab-customer>
</code>```

vm.CustomerCode is changing on basis of dropdown so its changing

app.comp.TestComp is already defined

```<code>angular
        .module('app.comp.TestComp')
        .component('tabCustomer', {
            templateUrl: 'Component.html',
            controller: tabCompCustomer,
            controllerAs: 'vm',
            bindings: {
                title: '@',
                functioname: '@',
                customerCode: '<'
            }
        });
function tabCompCustomer(tableCustomerService, $rootScope,$scope, $filter) {
        var vm = this;
         $scope.$watch('vm.customerCode', function (newValue, oldValue) {
            console.log('got1')
            console.log(newValue) // This is also not working
        });

        $onChanges = function (changes) {
            console.log('got')
            console.log(changes) // This is also not working
        };
};
</code>```

On Change of a Customer Code i need to fire my component again but i am not getting any fire event can anyone help

If the question is still unclear comment i will detailed it

答:
You should be changing your attribute binding from customerCode to customer-code, So that will pass vm.customerCode to component. And remove $watch function from component controller, as $onChanges function will get fire automatically on each bindings change.

```<code>customerCode="vm.customerCode"
</code>```

should be

```<code>customer-code="vm.customerCode"
</code>```

Note: make $onChanges = to this.$onChanges =

Body:
I have created a component in angular js which shows some data
But on change of my customer binding i want to call some service in component controller which is not reflecting,Here is the below code

In my Test1.html

<tab-customer title="Test Comp" customerCode="vm.customerCode"  functioname="fnTest"></tab-customer>

vm.CustomerCode is changing on basis of dropdown so its changing

app.comp.TestComp is already defined

angular
        .module('app.comp.TestComp')
        .component('tabCustomer', {
            templateUrl: 'Component.html',
            controller: tabCompCustomer,
            controllerAs: 'vm',
            bindings: {
                title: '@',
                functioname: '@',
                customerCode: '<'
            }
        });
function tabCompCustomer(tableCustomerService, $rootScope,$scope, $filter) {
        var vm = this;
         $scope.$watch('vm.customerCode', function (newValue, oldValue) {
            console.log('got1')
            console.log(newValue) // This is also not working
        });

        $onChanges = function (changes) {
            console.log('got')
            console.log(changes) // This is also not working
        };
};

On Change of a Customer Code i need to fire my component again but i am not getting any fire event can anyone help

If the question is still unclear comment i will detailed it

Body:
You should be changing your attribute binding from customerCode to customer-code, So that will pass vm.customerCode to component. And remove $watch function from component controller, as $onChanges function will get fire automatically on each bindings change.

customerCode="vm.customerCode"

should be

customer-code="vm.customerCode"

Note: make $onChanges = to this.$onChanges =


问:
QUICKFIX Logon Request. Session getting disconnected.
I am trying to get messages from a message queue and forward them to some other queue using quickfix. I encounter an IllegalStateException when a message is read. Exception message is Logon did not succeed. I think the issue is with session handshake.</p>

```<code>Jun 6, 2017 11:49:35 AM quickfix.mina.initiator.InitiatorIoHandler sessionCreated
<20170606-06:18:35, FIX.4.2:FROMPAT->TOPAT, outgoing> (8=FIX.4.2☺9=80☺35=A☺34=683☺49=FROMPAT☺52=20170606-06:18:35.614☺56=toPAT☺98=0☺108=1200☺10=180☺)
<20170606-06:18:35, FIX.4.2:FROMPAT->TOPAT, event> (Initiated logon request)
Jun 6, 2017 11:48:37 AM quickfix.Session disconnect
iNFO: [FIX.4.2:FROMPAT->TOPAT] Disconnecting: IO Session closed
</code>```

答: Try checking your CompIds and sequence numbers. These are the top two reasons we see login failures. Especially when setting up a new session, check you have the SenderCompId and TargetCompId the right way around, it's surprisingly easy to mix up! </p>

Body:
I am trying to get messages from a message queue and forward them to some other queue using quickfix. I encounter an IllegalStateException when a message is read. Exception message is Logon did not succeed. I think the issue is with session handshake.

Jun 6, 2017 11:49:35 AM quickfix.mina.initiator.InitiatorIoHandler sessionCreated
<20170606-06:18:35, FIX.4.2:FROMPAT->TOPAT, outgoing> (8=FIX.4.2☺9=80☺35=A☺34=683☺49=FROMPAT☺52=20170606-06:18:35.614☺56=toPAT☺98=0☺108=1200☺10=180☺)
<20170606-06:18:35, FIX.4.2:FROMPAT->TOPAT, event> (Initiated logon request)
Jun 6, 2017 11:48:37 AM quickfix.Session disconnect
iNFO: [FIX.4.2:FROMPAT->TOPAT] Disconnecting: IO Session closed


问:
how to make a cookie last a year PHP
I attempted to make a cookie-based theme switcher using PHP, and to make the cookie I use this:

```<code>$t = $_GET["t"];
if($t == "dark" || "light" || "mixed") {
    setcookie("theme", $t, time() + 31556926, "/");
} elseif(!isset($t) and !isset($_COOKIE["theme"])) {
    setcookie("theme", "dark", time() + 31556926 , "/");
}
if(isset($_COOKIE["theme"])) {
    echo "<body style=\"background:url(/imgs/" . $_COOKIE['theme'] . ".gif) top left repeat\">";
} else {
    echo "<body style=\"background:url(/imgs/dark.gif) top left repeat\">";
}
</code>```

But this doesn't seem to work, it reloads the page and sets the cookie, but has a strange property of needing to reload the page again in order for it to change the background, and only lasting for the session. As well as this, when you return to the index.php without ?t=light it stays, but then when you reload it disappears. I couldn't figure out any reason that it should be acting this way.

答:
The problem is that you, as you said in comments have the setcookie below other code.

You can not have any output before the setcookie.

Move the code you have in the question as far up as you can.

See here: http://php.net/manual/en/function.setcookie.php

If output exists prior to calling this function, setcookie() will fail and return FALSE.

Edit; and with as far up as possible, I mean above  tag

Edit2; about the isset.

```<code>If(isset($_GET["t"])){
      $t = $_GET["t"];
}Else{
      $t = "dark";
}
if($t == "dark" || "light" || "mixed") {
    setcookie("theme", $t, time() + 31556926, "/");
} elseif(!isset($t) and !isset($_COOKIE["theme"])) {
    setcookie("theme", "dark", time() + 31556926 , "/");
 }
if(isset($_COOKIE["theme"])) {
    echo "<body style=\"background:url(/imgs/" . $_COOKIE['theme'] . ".gif) top left repeat\">";
} else {
     echo "<body style=\"background:url(/imgs/dark.gif) top left repeat\">";
}
</code>```

It's hard to get it right on phone but you get the idea.

Title: how to make a cookie last a year PHP

Body:
I attempted to make a cookie-based theme switcher using PHP, and to make the cookie I use this:

$t = $_GET["t"];
if($t == "dark" || "light" || "mixed") {
    setcookie("theme", $t, time() + 31556926, "/");
} elseif(!isset($t) and !isset($_COOKIE["theme"])) {
    setcookie("theme", "dark", time() + 31556926 , "/");
}
if(isset($_COOKIE["theme"])) {
    echo "";
} else {
    echo "";
}

But this doesn't seem to work, it reloads the page and sets the cookie, but has a strange property of needing to reload the page again in order for it to change the background, and only lasting for the session. As well as this, when you return to the index.php without ?t=light it stays, but then when you reload it disappears. I couldn't figure out any reason that it should be acting this way.

Body:
The problem is that you, as you said in comments have the setcookie below other code.

You can not have any output before the setcookie.

Move the code you have in the question as far up as you can.

See here: http://php.net/manual/en/function.setcookie.php

If output exists prior to calling this function, setcookie() will fail and return FALSE.

Edit; and with as far up as possible, I mean above <HTML> tag

Edit2; about the isset.

If(isset($_GET["t"])){
      $t = $_GET["t"];
}Else{
      $t = "dark";
}
if($t == "dark" || "light" || "mixed") {
    setcookie("theme", $t, time() + 31556926, "/");
} elseif(!isset($t) and !isset($_COOKIE["theme"])) {
    setcookie("theme", "dark", time() + 31556926 , "/");
 }
if(isset($_COOKIE["theme"])) {
    echo "<body style=\"background:url(/imgs/" . $_COOKIE['theme'] . ".gif) top left repeat\">";
} else {
     echo "<body style=\"background:url(/imgs/dark.gif) top left repeat\">";
}

It's hard to get it right on phone but you get the idea.


问:
Persisting and accessing values globally in multiple components in Angular 2
I have a settings page where users can save some config variables, such as a Username. The user can also change the username on that page. But when I go to another Component (page) and back, the username isn't saved.

I also want to show the username in the other components. How do I do that? With a global variable?

Structure:
- App
    - app.ts (main)
    - setting.ts
    - someOtherComponent.ts

答:
You would need a service this so you can inject in wherever you need it.:

```<code>@Injectable()
export class GlobalService{
  private value;

  constructor(){

  }

  public setValue(value){
    this.value = value;
  }

  public getValue(){
    return this.value;
  }
}
</code>```

You could provide this service in all your modules but there is a chance you will get multiple instances. Therefore we will make the service a singleton.

```<code>@NgModule({
  providers: [ /* DONT ADD THE SERVICE HERE */ ]
})
class GlobalModule {
  static forRoot() {
    return {
      ngModule: GlobalModule,
      providers: [ GlobalService ]
    }
  }
}
</code>```

You should call the forRoot method only in your AppModule:

```<code>@NgModule({
  imports: [GlobalModule.forRoot()]
})
class AppModule {}
</code>```

Body:
You would need a service this so you can inject in wherever you need it.:

@Injectable()
export class GlobalService{
  private value;

  constructor(){

  }

  public setValue(value){
    this.value = value;
  }

  public getValue(){
    return this.value;
  }
}

You could provide this service in all your modules but there is a chance you will get multiple instances. Therefore we will make the service a singleton.

@NgModule({
  providers: [ /* DONT ADD THE SERVICE HERE */ ]
})
class GlobalModule {
  static forRoot() {
    return {
      ngModule: GlobalModule,
      providers: [ GlobalService ]
    }
  }
}

You should call the forRoot method only in your AppModule:

@NgModule({
  imports: [GlobalModule.forRoot()]
})
class AppModule {}


问:
reference to ID instead of using foreign key in jdo?
I'm using Datanucleus (jdo) with derby and I have a class MyClass. And this class has a variable of the type AnotherClass. I want to persist this variable. When an instance of MyClass is persisted, the variable AnotherClass is persisted too.

Now the problem: When I persist a new MyClass and this instance has the same AnotherClass instance as variable I don't want to save it into the AnotherClass table again but just reference it by the ID in the MyClass table. Else my AnotherClass table will have tons of the same instance persisted.

At the momement my class looks like this:

```<code>  @PersistenceCapable(identityType = IdentityType.APPLICATION)
  public class MyClass implements Serializable {

  private static final long serialVersionUID = -5074030667922748006L;

  @PrimaryKey
  @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
  Long key;

  @Persistent
  AnotherClass anotherClass;
</code>```

Update:

The AnotherClass class looks like the MyClass class.

I guess Tom Anderson's answer was already the correct one. I'm creating NEW AnotherClass instances and put them into the MyClass instance like myClass.setAnotherClass(anotherClass). So I guess anotherClass is an instance with the same values but it's still not the same instance so it gets its own row in the database even thought it looks exactly identical in there (except of the ID).

So I guess the solution would be: Check if the AnotherClass instance is already persisted in the database, if yes: get it from the database and set that instance to my myClass. If not: create a new instance and set it to the myClass so it gets persisted when myClass is persisted. Is that the way I should do it?

EDIT: Ok, now I have a new problem: I can't delete MyClass (= Character) instances anymore. If I try to do that I get this Exception (AnotherClass = Faction):

```<code>java.sql.SQLIntegrityConstraintViolationException: DELETE on table 'FACTION' caused a violation of foreign key constraint 'CHARACTER_FK1' for key (1).  The statement has been rolled back.
</code>```

That just happend when I did this: Create character1, create character2 exactly the same faction (it's only in the database once), try to delete character2. Any idea why?

EDIT2: Forgot something important:

```<code>  @Persistent(dependent = "true")
  Faction faction;
</code>```

That's what my Character class is saying. I have that because I want the Faction to be deleted if no Character is using it. I guess that's the problem? How can I do that now?

答:
This should just work. If the two MyClass instances are pointing to the same AnotherClass instance, then there will be one entry in the AnotherClass table, referenced by both of the MyClass entries.

If you're seeing lots of AnotherClass entries, it can only be because you have many different instances at runtime. How do you define identity of AnotherClass? How are you associating MyClass instances with AnotherClass instances?

ContentLicense: CC BY-SA 2.5

Body:
I'm using Datanucleus (jdo) with derby and I have a class MyClass. And this class has a variable of the type AnotherClass. I want to persist this variable. When an instance of MyClass is persisted, the variable AnotherClass is persisted too.

Now the problem: When I persist a new MyClass and this instance has the same AnotherClass instance as variable I don't want to save it into the AnotherClass table again but just reference it by the ID in the MyClass table. Else my AnotherClass table will have tons of the same instance persisted.

At the momement my class looks like this:

  @PersistenceCapable(identityType = IdentityType.APPLICATION)
  public class MyClass implements Serializable {

  private static final long serialVersionUID = -5074030667922748006L;

  @PrimaryKey
  @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
  Long key;

  @Persistent
  AnotherClass anotherClass;

Update:

The AnotherClass class looks like the MyClass class.

I guess Tom Anderson's answer was already the correct one. I'm creating NEW AnotherClass instances and put them into the MyClass instance like myClass.setAnotherClass(anotherClass). So I guess anotherClass is an instance with the same values but it's still not the same instance so it gets its own row in the database even thought it looks exactly identical in there (except of the ID).

So I guess the solution would be: Check if the AnotherClass instance is already persisted in the database, if yes: get it from the database and set that instance to my myClass. If not: create a new instance and set it to the myClass so it gets persisted when myClass is persisted. Is that the way I should do it?

EDIT: Ok, now I have a new problem: I can't delete MyClass (= Character) instances anymore. If I try to do that I get this Exception (AnotherClass = Faction):

java.sql.SQLIntegrityConstraintViolationException: DELETE on table 'FACTION' caused a violation of foreign key constraint 'CHARACTER_FK1' for key (1).  The statement has been rolled back.

That just happend when I did this: Create character1, create character2 exactly the same faction (it's only in the database once), try to delete character2. Any idea why?

EDIT2: Forgot something important:

  @Persistent(dependent = "true")
  Faction faction;

That's what my Character class is saying. I have that because I want the Faction to be deleted if no Character is using it. I guess that's the problem? How can I do that now?


问:
split configurations in spring - is it possible?
I would like to use different controllers in spring with different application configurations.
For example lets say I have one configuration using jsf/primefaces and another one using thymeleaf (for no special reason). Is it possible to map these configurations independently to different controllers?</p>

答:
Not sure but may be You can do it in two ways buy either returning view in your controller method as

```<code>@RequestMapping("/view1")
public String thymleaf(){
    return "thymleaf.html";
}

@RequestMapping("/view2")
public String jspView(){
    return "jspView.html";
}
</code>```

or by configuring it in xml

```<code><bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
     <property name="prefix" value="/WEB-INF/views/" />
     <property name="suffix" value=".html" />
     <property name="viewNames" value="thymeleaf/*" />
     <property name="templateMode" value="HTML5" />
</bean>

<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
     <property name="prefix" value="/WEB-INF/views/" />
     <property name="viewNames" value="jsp/*" />
     <property name="suffix" value=".jsp" />
</bean>
</code>```

Body:
Not sure but may be You can do it in two ways buy either returning view in your controller method as

@RequestMapping("/view1")
public String thymleaf(){
    return "thymleaf.html";
}

@RequestMapping("/view2")
public String jspView(){
    return "jspView.html";
}

or by configuring it in xml

<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
     <property name="prefix" value="/WEB-INF/views/" />
     <property name="suffix" value=".html" />
     <property name="viewNames" value="thymeleaf/*" />
     <property name="templateMode" value="HTML5" />
</bean>

<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
     <property name="prefix" value="/WEB-INF/views/" />
     <property name="viewNames" value="jsp/*" />
     <property name="suffix" value=".jsp" />
</bean>


问:
How to both show the log on the console and save an external log for a crawl?
Just like the title. I use -s LOG_FILE=mylog.txt for saving an external log. But I would like also see the log as the spider is running. Is there a way to do that? I'm using Windows 10 and prefer an answer that works in Windows 10.

Amateur developer without computing background here so please go easy on me.

答:
Use gnu's tee tool:

```<code>scrapy crawl myspider 2>&1 | tee crawl.log
</code>```

2>&1 redirect stderr to stdout - you want errors and info in the same file most likely.

| tee crawl.log pipes that output to tee which splits it to crawl.log file and stdout.

There's tee implementation for windows too:

There's a Win32 port of the Unix tee command, that does exactly that. See http://unxutils.sourceforge.net/ or http://getgnuwin32.sourceforge.net/

taken from: https://stackoverflow.com/a/796492/3737009

Body:
Use gnu's tee tool:

scrapy crawl myspider 2>&1 | tee crawl.log

2>&1 redirect stderr to stdout - you want errors and info in the same file most likely.

| tee crawl.log pipes that output to tee which splits it to crawl.log file and stdout.

There's tee implementation for windows too:

There's a Win32 port of the Unix tee command, that does exactly that. See http://unxutils.sourceforge.net/ or http://getgnuwin32.sourceforge.net/

taken from: https://stackoverflow.com/a/796492/3737009

ContentLicense: CC BY-SA 4.0


问:
numpy package not defined when importing function from another .py file
In my master file I have:

```<code>import matplotlib.pyplot as plt
import seaborn
import numpy as np
import time

import sys
sys.path.append("C:/.../python check/createsplit")
import createsplit

data='MJexample'
X,Y,N,Ntr=create_training_data(data)
</code>```

where I am calling create_training_data function from createsplit.py file which is:

```<code>import numpy as np
import scipy.io

def create_training_data(data_type):
     """
     creates training data
     """
     if data_type=='MJexample':
         N=300
         Ntr = 150
         X=np.linspace(0,1,N)
         X = np.array([X,X*X,np.linspace(5,10,N),np.sin(X),np.cos(X),np.sin(X)*np.cos(X)]).T

         fac=40
         Y=np.array([np.sin(fac*x)*np.cos(fac*x**2) for x in X[:,0]])[:,None]

         _X=X
         _Y=Y
         return _X,_Y,N,Ntr
</code>```

However running my original file results in error: NameError: global name 'np' is not defined for some reason I do not understand. I assume I am importing the functions in a wrong way but I don't really understand what would be wrong.

答:
I think this issue raises just because of a wrong call of the function. Try

```<code>X, Y, N, Ntr = createsplit.create_training_data(data)
</code>```

instead, and it should work.

Body:
In my master file I have:

import matplotlib.pyplot as plt
import seaborn
import numpy as np
import time

import sys
sys.path.append("C:/.../python check/createsplit")
import createsplit

data='MJexample'
X,Y,N,Ntr=create_training_data(data)

where I am calling create_training_data function from createsplit.py file which is:

import numpy as np
import scipy.io

def create_training_data(data_type):
     """
     creates training data
     """
     if data_type=='MJexample':
         N=300
         Ntr = 150
         X=np.linspace(0,1,N)
         X = np.array([X,X*X,np.linspace(5,10,N),np.sin(X),np.cos(X),np.sin(X)*np.cos(X)]).T

         fac=40
         Y=np.array([np.sin(fac*x)*np.cos(fac*x**2) for x in X[:,0]])[:,None]

         _X=X
         _Y=Y
         return _X,_Y,N,Ntr

However running my original file results in error: NameError: global name 'np' is not defined for some reason I do not understand. I assume I am importing the functions in a wrong way but I don't really understand what would be wrong.

Body:
I think this issue raises just because of a wrong call of the function. Try

X, Y, N, Ntr = createsplit.create_training_data(data)

instead, and it should work.


问:
How to dynamically choose the configurations based on the environment in JAVA?
I have a utility class which has common configurations related to email-sender, the configurations changes based on the environment like Staging and Production. Now how can I dynamically choose the configurations based on the environment?

here is my code,

EmailUtility.java

```<code>package com.housecar.common;

public class EmailUtility {

 //For staging
 public static final String FROM_EMAIL_ID = "xx12@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "xx12@xyz.com";
 static final String SMTP_PASSWORD = "15sss67$";
 public static final String REPLY_EMAIL_ID = "xx12@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "smtp.gmail.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";

 //for production

 /*public static final String FROM_EMAIL_ID = "admin@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "AKYeeeELEQAGAA"; // Replace with
                                                            // your SMTP
                                                            // username.
 static final String SMTP_PASSWORD = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";
 public static final String REPLY_EMAIL_ID = "admin@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "email-smtp.us-east-1.amazonaws.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";*/

}
</code>```

In my code I'm manually commenting out the configuration!

答:
application-{profile}.properties or application-{profile}.yml allows you to customize your application based on spring profile.

It is possible to create beans only in {profile} using:

```<code>@Service
@Profile(profile-name)
public class ServiceImpl implements ServiceInterface {
}
</code>```

Also it is possible to create beans based on properties values and conditions.

```<code>@Bean
@ConditionalOnProperty(prefix = EmailProperties.PREFIX, name = "fromId")
public BeanClass bean() {
    return new BeanClass(okHttpProperties.getFromId());
}
</code>```

Conditional beans can be based on expression

```<code>@Bean
@ConditionalOnExpression("'${spring.datasource.driver-class-name}'=='com.mysql.jdbc.Driver'")
public DbUtil dbMysqlUtil() {
    ...
}

@Bean
@ConditionalOnExpression("'${spring.datasource.driver-class-name}'=='org.hsqldb.jdbc.JDBCDriver'")
public DbUtil dbHsqlUtil() {
    ...
}
</code>```

Body:
I have a utility class which has common configurations related to email-sender, the configurations changes based on the environment like Staging and Production. Now how can I dynamically choose the configurations based on the environment?

here is my code,

EmailUtility.java

package com.housecar.common;

public class EmailUtility {

 //For staging
 public static final String FROM_EMAIL_ID = "xx12@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "xx12@xyz.com";
 static final String SMTP_PASSWORD = "15sss67$";
 public static final String REPLY_EMAIL_ID = "xx12@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "smtp.gmail.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";

 //for production

 /*public static final String FROM_EMAIL_ID = "admin@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "AKYeeeELEQAGAA"; // Replace with
                                                            // your SMTP
                                                            // username.
 static final String SMTP_PASSWORD = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";
 public static final String REPLY_EMAIL_ID = "admin@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "email-smtp.us-east-1.amazonaws.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";*/

}

In my code I'm manually commenting out the configuration!

Body:
application-{profile}.properties or application-{profile}.yml allows you to customize your application based on spring profile.

It is possible to create beans only in {profile} using:

@Service
@Profile(profile-name)
public class ServiceImpl implements ServiceInterface {
}

Also it is possible to create beans based on properties values and conditions.

@Bean
@ConditionalOnProperty(prefix = EmailProperties.PREFIX, name = "fromId")
public BeanClass bean() {
    return new BeanClass(okHttpProperties.getFromId());
}

Conditional beans can be based on expression

@Bean
@ConditionalOnExpression("'${spring.datasource.driver-class-name}'=='com.mysql.jdbc.Driver'")
public DbUtil dbMysqlUtil() {
    ...
}

@Bean
@ConditionalOnExpression("'${spring.datasource.driver-class-name}'=='org.hsqldb.jdbc.JDBCDriver'")
public DbUtil dbHsqlUtil() {
    ...
}


问:
text and xml converting problems
I have some problem with texts and xml. I’m using Python 3.6.0 :: Anaconda 4.3.1 (x86_64).
I have string x and convert it into xml format.

But the input and output are different. I assume python converts  & lt; into < which I do not want.

Here's how the result looks like:

```<code>import xml.etree.cElementTree as ET
x = '<SCRIPT>g(x) <0</SCRIPT>'
root = ET.fromstring(x)
print('result : ',root.text[5])
</code>```

and the result is

```<code>result :  <
</code>```

which is showing that & lt; has been changed. I'd like it to be

```<code>&
</code>```

Thank you!!!!

答:
If XML has the value  it will lead to parsing error. In order to avoid such errors, The < symbol is replaced with an entity reference <

Similar entity references includes:

```<code><    <   less than
>    >   greater than
&   &   ampersand
'  '   apostrophe
"  "   quotation mark
</code>```

To get back the entity reference after XML parsing, we can use string replace.

print('result : ',root.text.replace('<','<')[5])

Hope this helps.

Title: text and xml converting problems

Body:
I have some problem with texts and xml. I’m using Python 3.6.0 :: Anaconda 4.3.1 (x86_64).
I have string x and convert it into xml format.

But the input and output are different. I assume python converts  & lt; into < which I do not want.

Here's how the result looks like:

import xml.etree.cElementTree as ET
x = ''
root = ET.fromstring(x)
print('result : ',root.text[5])

and the result is

result :  <

which is showing that & lt; has been changed. I'd like it to be

&

Thank you!!!!

Body:
If XML has the value <SCRIPT>g(x) <0</SCRIPT> it will lead to parsing error. In order to avoid such errors, The < symbol is replaced with an entity reference &lt;

Similar entity references includes:

&lt;    <   less than
&gt;    >   greater than
&amp;   &   ampersand
&apos;  '   apostrophe
&quot;  "   quotation mark

To get back the entity reference after XML parsing, we can use string replace.

print('result : ',root.text.replace('<','&lt;')[5])

Hope this helps.


问:
when I try to install a eclipse plugin, It ask for a eclipse.tmatesoft.com a login?
when I try to install an Eclipse plugin, It asks for an eclipse.tmatesoft.com a login? I try to install svn plugin for eclipse with the connectors. This Login required window always pop up? how can I reslove this?

screenshot

答: Seems as you are using the wrong update site. You should better install the SVN plugin via the marketplace Help -> Eclipse Marketplace.


问:
What url encode algorithm does google or baidu Ads links use
when i search in google

```<code>http://www.google.com/search?sclient=psy&hl=en&newwindow=1&site=&source=hp&q=shopping&btnG=Search#sclient=psy&hl=en&newwindow=1&source=hp&q=%E8%B4%AD%E7%89%A9&aq=f&aqi=&aql=&oq=&gs_rfai=&pbx=1&fp=d5a61cbe48a951c1
</code>```

then you can see that there are two links in 'Ads' area, but move to your mouse pointer to these links, they are:

```<code>http://www.google.com/aclk?sa=L&ai=**CYB017kwHTa7GIsT0rQeqnujiCbmK0tEB2dyc_RqQtLWLAQgAEAEoAlCl7byW______8BYJ250IGQBcgBAakCwbO8-f4qhD6qBBlP0FHICrzLP3Yh2d7vTjWYUE8AvmD9DoLL...

http://www.google.com/aclk?sa=L&ai=*CNCTz7kwHTa7GIsT0rQeqnujiCaTU7tsBvOyAshaQtLWLAQgAEAIoAlCe7aiK_P____8BYJ250IGQBcgBAakCwbO8-f4qhD6qBBlP0CHcKLzIP3Yh2cPyGSqYUE8AvmD9DoLL...
</code>```

for China search engine baidu it also encodes the ads links, so can anyone know what encode algorithm they use to encode ads link urls? thank you in advance.

答: It's likely that these values act as tokens, linking to the URL in their back-end instead of being an encoded version of the URL itself - as such it would not be possible to convert these values directly to a URL without querying their servers.</p>

Body:
when i search in google

http://www.google.com/search?sclient=psy&hl=en&newwindow=1&site=&source=hp&q=shopping&btnG=Search#sclient=psy&hl=en&newwindow=1&source=hp&q=%E8%B4%AD%E7%89%A9&aq=f&aqi=&aql=&oq=&gs_rfai=&pbx=1&fp=d5a61cbe48a951c1

then you can see that there are two links in 'Ads' area, but move to your mouse pointer to these links, they are:

http://www.google.com/aclk?sa=L&ai=**CYB017kwHTa7GIsT0rQeqnujiCbmK0tEB2dyc_RqQtLWLAQgAEAEoAlCl7byW______8BYJ250IGQBcgBAakCwbO8-f4qhD6qBBlP0FHICrzLP3Yh2d7vTjWYUE8AvmD9DoLL...

http://www.google.com/aclk?sa=L&ai=*CNCTz7kwHTa7GIsT0rQeqnujiCaTU7tsBvOyAshaQtLWLAQgAEAIoAlCe7aiK_P____8BYJ250IGQBcgBAakCwbO8-f4qhD6qBBlP0CHcKLzIP3Yh2cPyGSqYUE8AvmD9DoLL...

for China search engine baidu it also encodes the ads links, so can anyone know what encode algorithm they use to encode ads link urls? thank you in advance.


问:
Is it possible to prevent the browser from parsing certain elements?
Consider the following markup:

```<code><div hidden id="table-template">
<table>
<tbody>
  <slot></slot>
</tbody>
</table>
</div>
<div hidden id="table-row-template">
<tr>
  <td>
    Some Content
  </td>
</tr>
</div>
</code>```

I would like to use 'table-template' and 'table-row-template' as re-usable components in my script.
(clone them and append them on demand)
but as the page loads the browser parses the markup and mutates it (taking 'slot' element and insert it before the 'table' element, and stripping 'td' and 'tr' tags).

This is reasonable (not valid HTML of course), but is there any way I can prevent the browser from parsing those elements?

So far I have tried:
using hidden elements,
wrapping with 'pre'/'code' tags,
but none seem to work.

答:
You can try using

```<code><script id="mytemplate" type="text/template">
  ...your table's html...
</script>
</code>```

Then:

```<code><script>
  alert($('#mytemplate').html());
</script>
</code>```

Many libraries use this method, handlebar.js for example.

The <template> element may gain compatibility with more browser versions: http://caniuse.com/#feat=template

Body:
Consider the following markup:

  <slot></slot>

    Some Content

I would like to use 'table-template' and 'table-row-template' as re-usable components in my script.
(clone them and append them on demand)
but as the page loads the browser parses the markup and mutates it (taking 'slot' element and insert it before the 'table' element, and stripping 'td' and 'tr' tags).

This is reasonable (not valid HTML of course), but is there any way I can prevent the browser from parsing those elements?

So far I have tried:
using hidden elements,
wrapping with 'pre'/'code' tags,
but none seem to work.

Body:
You can try using <script type="text/template"></script>

<script id="mytemplate" type="text/template">
  ...your table's html...
</script>

Then:

<script>
  alert($('#mytemplate').html());
</script>

Many libraries use this method, handlebar.js for example.

The <template> element may gain compatibility with more browser versions: http://caniuse.com/#feat=template


问:
Get environment variable defined in Linux bash to webpack
I have checked out tons of SO questions about "environment variables in webpack" using e.g. the DefinePlugin:

```<code>new webpack.DefinePlugin({'ENV': JSON.stringify('staging')})
</code>```

but I cannot for the life of me find a way to inject an environment variable defined in the linux bash shell, instead of using the hard coded staging string

In my production and staging environements I have variables such as $ENV and $API_KEY defined, and I want to use their values in my webpack / ReactJs code.

Edit

I notice, if I run the a webpack command from cli:

```<code> $ ENVIRONMENT=staging
 $ node_modules/.bin/webpack -p
</code>```

And in my webpack.config.js file defines

```<code> new webpack.DefinePlugin({'ENV': JSON.stringify(process.env.ENVIRONMENT)})
</code>```

This does not work (ENV is undefined in my JS code),

However, if I run it on the same line, it seems to work - ENVIRONMENT seems to be available in the webpack.config.js file:

```<code>$ ENVIRONMENT=staging node_modules/.bin/webpack -p
</code>```

So I would really like to make this work without having to define the ENVIRONMENT variable on the same line as the webpack command.

答:
Stupid me forgot to export the variable in the bash terminal

```<code>$ export ENVIRONMENT=staging
$ node_modules/.bin/webpack -p
</code>```

works fine and, as pointed out, one can then access the ENVIRONMENT variable with process.env.ENVIRONMENT from inside webpack.config.js

Body:
I have checked out tons of SO questions about "environment variables in webpack" using e.g. the DefinePlugin:

new webpack.DefinePlugin({'ENV': JSON.stringify('staging')})

but I cannot for the life of me find a way to inject an environment variable defined in the linux bash shell, instead of using the hard coded staging string

In my production and staging environements I have variables such as $ENV and $API_KEY defined, and I want to use their values in my webpack / ReactJs code.

Edit

I notice, if I run the a webpack command from cli:

 $ ENVIRONMENT=staging
 $ node_modules/.bin/webpack -p

And in my webpack.config.js file defines

 new webpack.DefinePlugin({'ENV': JSON.stringify(process.env.ENVIRONMENT)})

This does not work (ENV is undefined in my JS code),

However, if I run it on the same line, it seems to work - ENVIRONMENT seems to be available in the webpack.config.js file:

$ ENVIRONMENT=staging node_modules/.bin/webpack -p

So I would really like to make this work without having to define the ENVIRONMENT variable on the same line as the webpack command.

Body:
Stupid me forgot to export the variable in the bash terminal

$ export ENVIRONMENT=staging
$ node_modules/.bin/webpack -p

works fine and, as pointed out, one can then access the ENVIRONMENT variable with process.env.ENVIRONMENT from inside webpack.config.js


问:
React native in app developers menu not working on Real device
Shaking device is not opening the developers menu.

I run the following command to open the menu

```<code>adb shell input keyevent KEYCODE_MENU
</code>```

Output is

```<code>Error: TV display id Invalid, will send event to default displayId
</code>```

So how to open/enable in app developer menu on android device ?

React native : 0.44.0
Android device : Lenovo k4 note

答: I have faced the similar issue so what I did is, I uninstalled the app and installed it again. After doing it try to shake the device you will get into the developer menu.</p>

Body:
Shaking device is not opening the developers menu.

I run the following command to open the menu

adb shell input keyevent KEYCODE_MENU

Output is

Error: TV display id Invalid, will send event to default displayId

So how to open/enable in app developer menu on android device ?

React native : 0.44.0
Android device : Lenovo k4 note


问:
Finder Synch Extension Waiting to Attach in XCode 7.0.1 OSX 10.10
I have written a Finder Synch extension with Swift and add to my project target in XCode 7.0.1. At first run, it works as normal but after several runs, it stall on Extension Waiting to Attach. If I open a Finder window, nothing happened and my class init never called.

Do you face any problem like this? Using Mac OSX 10.10.5 Yosemite with XCode 7.0.1.

答:
This happened to me also, make sure your entitlements and certificates / signing are set correctly. Working with a non signed finder sync extension caused exactly the problems you described.

edit: one more thing, the optional relaunch (alt + right click on finder) also helps attach to the extension after it is launched.


问:
Suitability of app with long running tasks for AWS Lambda or AWS Step Functions
I have an application on an AWS EC2 instance that runs once daily. The application fetches some files from a web service, parses the files line by line, updates a database, updates S3 files based on changes in the database, sends notification emails to customers as well as a few other tasks.

This is a series of logical tasks that must take place in sequence, although some of the tasks can be thought of as sub-tasks that can be executed in parallel. All tasks are a combination of Perl scripts and Java programs, with a single Perl script acting as the manager that executes each in turn. Some tasks can take as long as 45 minutes to complete, and the whole process can take up to 3 hours in total.

I'd like to make this whole process serverless. My initial idea was to use AWS Lambda, whereby each task would execute as a Lambda function, until I discovered Lambda functions impose a 5 minute execution timeout. It seems like the AWS Step Functions service is actually a better fit for my use case, but my understanding is that this service is backed by Lambda, so the tasks will still have the 5 min execution limitation.

(I'm also aware that I would have to re-write my Perl scripts to a language supported by Lambda).

I assume that I can work around the execution time limit by refactoring my code into smaller functions that will guarantee to complete in under 5 minutes. In my particular situation though, this seems inefficient.

Currently the database update task processes lines from a file one at a time. For this to work with Lambda, a Lambda function would need to handle only a single line from the file (or a very small number of lines) in order to guarantee not spilling over 5 minutes execution time. This would involve opening and closing a connection with the database on every invocation of the Lambda function. Also, each line processed should result in an entry written to a file, to be stored in S3. Right now, I just keep a file handle in memory and write the file to S3 when all lines are processed, but with Lambda I would need to keep reading the file, updating it and writing it back to S3.

What I'm asking is:

Is my use case a bad fit for AWS Lambda and/or AWS Step Functions?

Have I misunderstood how these services work?

Is there another AWS service that would be a better fit for my use case?

After further research, I think AWS Batch might be a good idea.

答:
What you want are called Activity Workers.  Tl;dr: You register "activities" and each gets an ARN.  Then you can put that ARN in the resource field of Task states and then you run some code (the "worker") somewhere (in a Lambda, on EC2, in your basement, wherever) that polls for tasks identified by that ARN, then calls back to report success or failure.  Activity Workers can run for up to a year.

Step-by-step details at the AWS docs

In response to RTF's comment, here's a deeper dive: Suppose you have code to color turtles in color_turtles.pl. So what you do is call the CreateActivity API - see http://docs.aws.amazon.com/step-functions/latest/apireference/API_CreateActivity.html - giving the name "ColorTurtles" and it'll give you back an ARN, a string beginning arn:aws...  Then in your state machine you make a Task state with that ARN as the value of the resource field.  Then you add code to color_turtles.pl to poll the service with http://docs.aws.amazon.com/step-functions/latest/apireference/API_GetActivityTask.html - whenever a machine you're running gets to that task, it'll go look for activity workers polling.  It'll give your polling worker the input for the task, then you process the input and generate some output, and call SendTaskSuccess or SendTaskFailure. All these are just REST HTTP calls, so you can run them anywhere and I mean anywhere; in a Lambda, on an EC2 instance, or on some computer anywhere on the Internet.


问:
In-core inode list and disk inode list
Kindly tell me the difference between In-core inode list and disk inode list with reference to Unix File System.

Also, kindly direct me to the links where i can get more info on this.

Thanks,LinuxPenseur

答:
From http://www.cs.iastate.edu/~cs554/NOTES/RPC/UNIXfilesystem.pdf (3rd page):

• on-disk inode refers to inode stored in disk within the inode list

• in-core inode refers to inode stored in memory when a file is open

Title: In-core inode list and disk inode list


问:
Can i edit the buttons of a browser dialogs?
I was wondering if it's possible to change the text of the OK/Cancel buttons in dialogs?

答:
possible but you need to create a custom alert dialog

https://tutorialzine.com/2010/12/better-confirm-box-jquery-css3


问:
Angular adds a day when displaying the date (dd/MM/yyyy)
I have a datepicker where the user picks the date without choosing the time, the date is saved correctly in my data base but when I display it, it shows one day ahaid, when I looked up the issue it turns out that it's a timezone issue that lots of people face but i didn't quite understand how to fix it in my code :

```<code><tbody>
   <tr ng-repeat="ft in ftListesorted">
      <td>{{ft.NomProjet}}</td>
      <td>{{ft.NomTache}}</td>
      <td>{{ft.Datefeuillestemps |  date : 'dd/MM/yyyy' }}</td>
   </tr>
</tbody>
</code>```

I get the "ft.Datefeuillestemps" from my database where the default time is always set to T00:00:00.

For example here's how my date is stored in the data base : 2017-05-17 00:00:00.0000000 and this is what I get in my view : 18/05/2017 so a day is added.

How can I solve this issue ?

答: You could subtract (new Date()).getTimezoneOffset() from your object (assuming the date in the database is on GMT), but this is not perfect. You will still have issues when timezones change differently because of daylight saving time.</p>

Body:
I have a datepicker where the user picks the date without choosing the time, the date is saved correctly in my data base but when I display it, it shows one day ahaid, when I looked up the issue it turns out that it's a timezone issue that lots of people face but i didn't quite understand how to fix it in my code :

      {{ft.NomProjet}}
      {{ft.NomTache}}
      {{ft.Datefeuillestemps |  date : 'dd/MM/yyyy' }}

I get the "ft.Datefeuillestemps" from my database where the default time is always set to T00:00:00.

For example here's how my date is stored in the data base : 2017-05-17 00:00:00.0000000 and this is what I get in my view : 18/05/2017 so a day is added.

How can I solve this issue ?


问:
Unpacking argument in print statements
I would like to know if there is a way to unpack values in a print statement, the same way it is possible to unpack arguments in a function f

This works:

```<code>import numpy
er = numpy.array([0.36666667, 0.46666667, 0.43333333, numpy.nan])
l = 0.8
print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (er[0], er[1], er[2], er[3], l))
# 0.367 | 0.467 | 0.433 | nan | 0.8
</code>```

However, I would like to avoid multiple er[x] and instead use something like *er as in:

```<code>def f(a,b,c,d):
    return True
print(f(*er))
# True
</code>```

I tried:

```<code>#print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (*(er, numpy.array([l]))))
</code>```

But this last line generates "SyntaxError: invalid syntax" error.

Any ideas?

答:
Since you need the specific format you can do the following which allows both for the definition of separators (' | ') as well as formatting of the individual values ({:.3f}):

```<code>print(' | '.join(['{:.3f}'.format(x) for x in er]))
</code>```

Adding values to that is trivial:

```<code>print(' | '.join(['{:.3f}'.format(x) for x in er]) + ' | {:.1f}'.format(l))
</code>```

Note that the str.join() performs faster when provided with a list rather than a generator expression.

Title: Unpacking argument in print statements

Body:
I would like to know if there is a way to unpack values in a print statement, the same way it is possible to unpack arguments in a function f

This works:

import numpy
er = numpy.array([0.36666667, 0.46666667, 0.43333333, numpy.nan])
l = 0.8
print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (er[0], er[1], er[2], er[3], l))
# 0.367 | 0.467 | 0.433 | nan | 0.8

However, I would like to avoid multiple er[x] and instead use something like *er as in:

def f(a,b,c,d):
    return True
print(f(*er))
# True

I tried:

#print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (*(er, numpy.array([l]))))

But this last line generates "SyntaxError: invalid syntax" error.

Any ideas?

Body:
Since you need the specific format you can do the following which allows both for the definition of separators (' | ') as well as formatting of the individual values ({:.3f}):

print(' | '.join(['{:.3f}'.format(x) for x in er]))

Adding values to that is trivial:

print(' | '.join(['{:.3f}'.format(x) for x in er]) + ' | {:.1f}'.format(l))

Note that the str.join() performs faster when provided with a list rather than a generator expression.


问:
Simple PHP contact form with Firebase hosting
I'm trying to test out if PHP works from my Firebase hosting using the following:

(index.html)

```<code><form action="welcome.php" method="post">
   <input type="submit">
</form>
</code>```

(welcome.php)

```<code><?php

   $to = "my@email.com";
   $subject = "My subject";
   $txt = "Hello world!";
   $headers = "From: dummy@email.com";

   mail($to,$subject,$txt,$headers);

?>
</code>```

Every time I try this the browser keeps on attempting to open the PHP file rather than processing it. Is simple PHP enabled on the Firebase server hosting to process a simple form like this? If I can get it to work this way, I will be building the form out correctly including validation etc.

Thanks,

答:
There is no PHP but nodeJS available for server-side scripting ...

Google Cloud Functions are written in JavaScript, and execute in
  a Node.js runtime.

Mandrill also supports nodeJS and it features a Webhooks API.
Therefore, one can require that node module within these "cloud functions" and "web hooks" ...and then post with a HTML form onto them.

There would need to be a few HTTP cloud functions defined on the Firebase Console, in order to let them subscribe, unsubscribe and manage their subscriptions. One could even generate the HTML markup for the input form with cloud functions and then attach it. As an example, not tested and no guarantee included:

```<code>const functions = require('firebase-functions');
const mandrill = require('mandrill-api/mandrill');
var client = new mandrill.Mandrill('YOUR_API_KEY');

/* TODO: add the user on Firebase, respond through the API */
exports.user_add = functions.https.onRequest((req, res) => {

});

/* TODO: change subscription settings on Firebase, respond through the API */
exports.user_edit = functions.https.onRequest((req, res) => {

});

/* TODO: remove the user on Firebase, respond through the API */
exports.user_remove = functions.https.onRequest((req, res) => {

});

/* optional: generate the HTML markup of the form, send HTTP response */
exports.markup = functions.https.onRequest((req, res) => {

});
</code>```

One can bind the events of Firebase Auth, to keep two user databases in in-sync (this is not required for Mandrill, but required for MailChimp - no matter whether using the PHP or nodeJS wrapper):

```<code>exports.on_user_create = functions.auth.user().onCreate(event => {
   const user = event.data;
});

exports.on_user_delete = functions.auth.user().onDelete(event => {
   const user = event.data;
});
</code>```

Firebase on Websites explains it, while there is a Local Emulator for Cloud Functions.

Body:
I'm trying to test out if PHP works from my Firebase hosting using the following:

(index.html)

<form action="welcome.php" method="post">
   <input type="submit">
</form>

(welcome.php)

<?php

   $to = "my@email.com";
   $subject = "My subject";
   $txt = "Hello world!";
   $headers = "From: dummy@email.com";

   mail($to,$subject,$txt,$headers);

?>

Every time I try this the browser keeps on attempting to open the PHP file rather than processing it. Is simple PHP enabled on the Firebase server hosting to process a simple form like this? If I can get it to work this way, I will be building the form out correctly including validation etc.

Thanks,

Body:
There is no PHP but nodeJS available for server-side scripting ...

Google Cloud Functions are written in JavaScript, and execute in
  a Node.js runtime.

Mandrill also supports nodeJS and it features a Webhooks API.
Therefore, one can require that node module within these "cloud functions" and "web hooks" ...and then post with a HTML form onto them.

There would need to be a few HTTP cloud functions defined on the Firebase Console, in order to let them subscribe, unsubscribe and manage their subscriptions. One could even generate the HTML markup for the input form with cloud functions and then attach it. As an example, not tested and no guarantee included:

const functions = require('firebase-functions');
const mandrill = require('mandrill-api/mandrill');
var client = new mandrill.Mandrill('YOUR_API_KEY');

/* TODO: add the user on Firebase, respond through the API */
exports.user_add = functions.https.onRequest((req, res) => {

});

/* TODO: change subscription settings on Firebase, respond through the API */
exports.user_edit = functions.https.onRequest((req, res) => {

});

/* TODO: remove the user on Firebase, respond through the API */
exports.user_remove = functions.https.onRequest((req, res) => {

});

/* optional: generate the HTML markup of the form, send HTTP response */
exports.markup = functions.https.onRequest((req, res) => {

});

One can bind the events of Firebase Auth, to keep two user databases in in-sync (this is not required for Mandrill, but required for MailChimp - no matter whether using the PHP or nodeJS wrapper):

exports.on_user_create = functions.auth.user().onCreate(event => {
   const user = event.data;
});

exports.on_user_delete = functions.auth.user().onDelete(event => {
   const user = event.data;
});

Firebase on Websites explains it, while there is a Local Emulator for Cloud Functions.


问:
Backend for multiple instances of app
I'm building an app for a beautysalon, the app has a backend where an administrator can manage the content for the app. In example, news, treatment, pricelists.

Now I had the idea to use the backend for multiple instances of the same app. So beautysalon X uses this app but beautysalon Y also has the same app, with of course their own layout (logo, colours ect).

The backend is running on Azure, made with C#.

Now I can see me splitting the data, so that the beauty salons only see their own data. I think the biggest problem is push notifications, since you can only have one certificate.

I don't want to have a backend for every single app I sell.
How would you design an app and backend for this situation?

Thanks in advance, any help is much appreciated!

答: Try creating sub domain for each salon. Thus you need to use only one certificate. You could also use different database for different salons. </p>

Title: Backend for multiple instances of app