问:
Gradient Button Crashed when Removing Gradient
So I'm new at learning Swift and I'm having trouble with removing the button gradient background, technically I am able to "remove" it but it's not stable and crashes if tapped multiple times. My guess it has something to do with the sublayer not being removed "safely" but I looked around and just can't figure it out.

```<code>@IBAction func button(_ sender: UIButton) {
    sender.setTitleColor(.systemBackground, for: .selected)
    sender.isSelected = !sender.isSelected
    if sender.isSelected {
        sender.layer.borderWidth = 0
        sender.applyGradient(colors: [ #colorLiteral(red: 0.5098039216, green: 0.8431372549, blue: 0.5254901961, alpha: 1) , #colorLiteral(red: 0.3058823529, green: 0.6941176471, blue: 0.3215686275, alpha: 1) ], radius: 10)
    } else {
        sender.layer.borderWidth = 1
        sender.layer.sublayers!.remove(at: 1)   // this not stable, cause crash if trigger repeatedly
    }
}
</code>```

```<code>extension UIButton {
    func applyGradient(colors: [CGColor], radius: CGFloat = 0, startGradient: CGPoint = CGPoint(x: 0.5, y: 0.0), endGradient: CGPoint = CGPoint(x: 0.5, y: 1.0)) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.cornerRadius = radius
        gradientLayer.colors = colors
        gradientLayer.startPoint = startGradient
        gradientLayer.endPoint = endGradient
        gradientLayer.frame = self.bounds
        self.layer.insertSublayer(gradientLayer, at: 0)
    }
}
</code>```

答:
You can give your CALayer a name this way you can find the index of your layer before removing it:

```<code>extension UIButton {
    func applyGradient(colors: [CGColor], radius: CGFloat = 0, startGradient: CGPoint = .init(x: 0.5, y: 0), endGradient: CGPoint = .init(x: 0.5, y: 1)) {
        // check first if there is already a gradient layer to avoid adding more than one
        if let gradientLayer = layer.sublayers?.first(where: {$0.name == "gradient" }) as? CAGradientLayer {
            gradientLayer.cornerRadius = radius
            gradientLayer.colors = colors
            gradientLayer.startPoint = startGradient
            gradientLayer.endPoint = endGradient
            gradientLayer.frame = bounds
        // if not found create a new gradient layer
        } else {
            let gradientLayer = CAGradientLayer()
            gradientLayer.name = "gradient"
            gradientLayer.cornerRadius = radius
            gradientLayer.colors = colors
            gradientLayer.startPoint = startGradient
            gradientLayer.endPoint = endGradient
            gradientLayer.frame = bounds
            layer.insertSublayer(gradientLayer, at: 0)
        }
    }
}
</code>```

```<code>@IBAction func button(_ sender: UIButton) {
    sender.setTitleColor(.systemBackground, for: .selected)
    sender.isSelected.toggle()
    if sender.isSelected {
        sender.layer.borderWidth = 0
        sender.applyGradient(colors: [ #colorLiteral(red: 0.5098039216, green: 0.8431372549, blue: 0.5254901961, alpha: 1) , #colorLiteral(red: 0.3058823529, green: 0.6941176471, blue: 0.3215686275, alpha: 1) ], radius: 10)
    } else {
        sender.layer.borderWidth = 1
        if let firstIndex = sender.layer.sublayers?.firstIndex(where: {$0.name == "gradient" }) {
            sender.layer.sublayers?.remove(at: firstIndex)
        }
    }
}
</code>```

Body:
So I'm new at learning Swift and I'm having trouble with removing the button gradient background, technically I am able to "remove" it but it's not stable and crashes if tapped multiple times. My guess it has something to do with the sublayer not being removed "safely" but I looked around and just can't figure it out.

@IBAction func button(_ sender: UIButton) {
    sender.setTitleColor(.systemBackground, for: .selected)
    sender.isSelected = !sender.isSelected
    if sender.isSelected {
        sender.layer.borderWidth = 0
        sender.applyGradient(colors: [ #colorLiteral(red: 0.5098039216, green: 0.8431372549, blue: 0.5254901961, alpha: 1) , #colorLiteral(red: 0.3058823529, green: 0.6941176471, blue: 0.3215686275, alpha: 1) ], radius: 10)
    } else {
        sender.layer.borderWidth = 1
        sender.layer.sublayers!.remove(at: 1)   // this not stable, cause crash if trigger repeatedly
    }
}

extension UIButton {
    func applyGradient(colors: [CGColor], radius: CGFloat = 0, startGradient: CGPoint = CGPoint(x: 0.5, y: 0.0), endGradient: CGPoint = CGPoint(x: 0.5, y: 1.0)) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.cornerRadius = radius
        gradientLayer.colors = colors
        gradientLayer.startPoint = startGradient
        gradientLayer.endPoint = endGradient
        gradientLayer.frame = self.bounds
        self.layer.insertSublayer(gradientLayer, at: 0)
    }
}

Body:
You can give your CALayer a name this way you can find the index of your layer before removing it:

extension UIButton {
    func applyGradient(colors: [CGColor], radius: CGFloat = 0, startGradient: CGPoint = .init(x: 0.5, y: 0), endGradient: CGPoint = .init(x: 0.5, y: 1)) {
        // check first if there is already a gradient layer to avoid adding more than one
        if let gradientLayer = layer.sublayers?.first(where: {$0.name == "gradient" }) as? CAGradientLayer {
            gradientLayer.cornerRadius = radius
            gradientLayer.colors = colors
            gradientLayer.startPoint = startGradient
            gradientLayer.endPoint = endGradient
            gradientLayer.frame = bounds
        // if not found create a new gradient layer
        } else {
            let gradientLayer = CAGradientLayer()
            gradientLayer.name = "gradient"
            gradientLayer.cornerRadius = radius
            gradientLayer.colors = colors
            gradientLayer.startPoint = startGradient
            gradientLayer.endPoint = endGradient
            gradientLayer.frame = bounds
            layer.insertSublayer(gradientLayer, at: 0)
        }
    }
}

@IBAction func button(_ sender: UIButton) {
    sender.setTitleColor(.systemBackground, for: .selected)
    sender.isSelected.toggle()
    if sender.isSelected {
        sender.layer.borderWidth = 0
        sender.applyGradient(colors: [ #colorLiteral(red: 0.5098039216, green: 0.8431372549, blue: 0.5254901961, alpha: 1) , #colorLiteral(red: 0.3058823529, green: 0.6941176471, blue: 0.3215686275, alpha: 1) ], radius: 10)
    } else {
        sender.layer.borderWidth = 1
        if let firstIndex = sender.layer.sublayers?.firstIndex(where: {$0.name == "gradient" }) {
            sender.layer.sublayers?.remove(at: firstIndex)
        }
    }
}


来源: stackexchange

问:
Create config variables in sails.js?
I'm converting an app of mine from Express to sails.js - is there a way I can do something like this in Sails?

From my app.js file in Express:

```<code>var globals = {
    name: 'projectName',
    author: 'authorName'
};

app.get('/', function (req, res) {
    globals.page_title = 'Home';
    res.render('index', globals);
});
</code>```

This let me access those variables on every view without having to hardcode them into the template. Not sure how/where to do it in Sails though.

答:
I just made a service which delivers a value:</p>

```<code>maxLimbs: function(){
        var maxLimbs = 15;
        return maxLimbs;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Create config variables in sails.js?

Body:
I'm converting an app of mine from Express to sails.js - is there a way I can do something like this in Sails?

From my app.js file in Express:

var globals = {
    name: 'projectName',
    author: 'authorName'
};

app.get('/', function (req, res) {
    globals.page_title = 'Home';
    res.render('index', globals);
});

This let me access those variables on every view without having to hardcode them into the template. Not sure how/where to do it in Sails though.

Body:
I just made a service which delivers a value:

maxLimbs: function(){
        var maxLimbs = 15;
        return maxLimbs;
    }

ContentLicense: CC BY-SA 4.0


问:
Dagger 2 - Inject fields in activity
Before I start, I've read a lot of tutorials but each of them contains info about old dagger - using @builder which is now deprecated. I'm using @Factory

What I have?

```<code>class LoginActivity : AppCompatActivity() {

@Inject
lateinit var authService: AuthService

override fun onCreate(savedInstanceState: Bundle?) {
    AndroidInjection.inject(this)
....
}
}
//----------------
@Singleton
@Component(modules = [TestAppModule::class])
interface TestApplicationComponent : AndroidInjector<TestMyApplication> {
    @Component.Factory
    abstract class Builder : AndroidInjector.Factory<TestMyApplication>
}
//----------------
class TestMyApplication : MyApplication() {
    override fun onCreate() {
        super.onCreate()
        JodaTimeAndroid.init(this)
    }
    override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        return DaggerTestApplicationComponent.factory().create(this)
    }
}
//----------------
@Singleton
open class AuthService @Inject constructor(
    @AppContext val context: Context, private val authRemoteDataSource: AuthRemoteDataSource
) {
...
}
//----------------
class MockRunner : AndroidJUnitRunner() {
    override fun onCreate(arguments: Bundle?) {
        StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder().permitAll().build())
        super.onCreate(arguments)
    }

    override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
        return super.newApplication(cl, TestMyApplication::class.qualifiedName, context)
    }
}
</code>```

Notes:

I show you, constructor in AuthService because it has more than 0 args

Mock runner applies my TestMyApplication class

And TestClass

```<code>@RunWith(AndroidJUnit4::class)
    class LoginActivityTest {

@Mock
lateinit var mockAuthService: AuthService

@Rule
@JvmField
val activityRule = ActivityTestRule<LoginActivity>(LoginActivity::class.java, false, false)

@Before
fun beforeEach() {
    MockitoAnnotations.initMocks(this)
    Mockito.doReturn(NOT_SIGNED).`when`(mockAuthService).getUserSignedStatus(ArgumentMatchers.anyBoolean())
    println(mockAuthService.getUserSignedStatus(true)) //test
}

@Test
fun buttonLogin() {
    activityRule.launchActivity(Intent())
    onView(withText("Google")).check(matches(isDisplayed()));
}
}
</code>```

What do I want?
- In the simplest way attach mocked AuthService to LoginActivity

What I've got? Error:

While calling method:  android.content.Context.getSharedPreferences
In line:

```<code>Mockito.doReturn(NOT_SIGNED).`when`(mockAuthService).getUserSignedStatus(ArgumentMatchers.anyBoolean())
</code>```

Method getSharedPreferences is called in real method getUserSignedStatus. So now, I'm getting an error because Mockito.when calls the real function which is public. I think, the second problem will be that mocked AuthService is not injected to LoginActivity

答:
So you should probably provide the AuthService through a module, one for the normal app and one for the android test, which supplies the mocked version.  That would mean removing the Dagger annotations from the AuthService class.  I don't use Component.Factory but this example should be enough to for you to use as a guide.

In androidTest folder :

Create test module :

```<code>    // normal app should include the module to supply this dependency
    @Module object AndroidTestModule {

        val mock : AuthService = Mockito.mock(AuthService::class.java)

        @Provides
        @Singleton
        @JvmStatic
        fun mockService() : AuthService =  mock

    }
</code>```

Create test component :

```<code>@Component(modules = [AndroidTestModule::class])
@Singleton
interface AndroidTestComponent : AndroidInjector<AndroidTestApp> {

    @Component.Builder interface Builder {

        @BindsInstance fun app(app : Application) : Builder

        fun build() : AndroidTestComponent
    }
}
</code>```

Create test app :

```<code>class AndroidTestApp : DaggerApplication() {

    override fun onCreate() {
        super.onCreate()

        Timber.plant(Timber.DebugTree())
    }

    override fun applicationInjector(): AndroidInjector<out DaggerApplication> =
            DaggerAndroidTestAppComponent.builder().app(this).build()
}
</code>```

then the runner :

```<code>class AndroidTestAppJunitRunner : AndroidJUnitRunner() {

    override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
        return super.newApplication(cl, AndroidTestApp::class.java.canonicalName, context)
    }
}
</code>```

include in android closure in Gradle :

testInstrumentationRunner "com.package.name.AndroidTestAppJunitRunner"

add these deps :

```<code>kaptAndroidTest "com.google.dagger:dagger-compiler:$daggerVersion"
kaptAndroidTest "com.google.dagger:dagger-android-processor:$daggerVersion"

androidTestImplementation "org.mockito:mockito-android:2.27.0"
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
</code>```

then a test :

```<code>@RunWith(AndroidJUnit4::class) class LoginActivityTest {

    @Rule
    @JvmField
    val activityRule = ActivityTestRule<LoginActivity>(LoginActivity::class.java, false, false)

    @Before
    fun beforeEach() {
Mockito.doReturn(NOT_SIGNED).`when`(AndroidTestModule.mock).getUserSignedStatus(ArgumentMatchers.anyBoolean()
    }

    @Test
    fun buttonLogin() {
        activityRule.launchActivity(Intent())
        onView(withText("Google")).check(matches(isDisplayed()));
    }
}
</code>```

Your dependency will then supplied through the generated test component graph to LoginActivity

Title: Dagger 2 - Inject fields in activity

Body:
Before I start, I've read a lot of tutorials but each of them contains info about old dagger - using @builder which is now deprecated. I'm using @Factory

What I have?

class LoginActivity : AppCompatActivity() {

@Inject
lateinit var authService: AuthService

override fun onCreate(savedInstanceState: Bundle?) {
    AndroidInjection.inject(this)
....
}
}
//----------------
@Singleton
@Component(modules = [TestAppModule::class])
interface TestApplicationComponent : AndroidInjector<TestMyApplication> {
    @Component.Factory
    abstract class Builder : AndroidInjector.Factory<TestMyApplication>
}
//----------------
class TestMyApplication : MyApplication() {
    override fun onCreate() {
        super.onCreate()
        JodaTimeAndroid.init(this)
    }
    override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        return DaggerTestApplicationComponent.factory().create(this)
    }
}
//----------------
@Singleton
open class AuthService @Inject constructor(
    @AppContext val context: Context, private val authRemoteDataSource: AuthRemoteDataSource
) {
...
}
//----------------
class MockRunner : AndroidJUnitRunner() {
    override fun onCreate(arguments: Bundle?) {
        StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder().permitAll().build())
        super.onCreate(arguments)
    }

    override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
        return super.newApplication(cl, TestMyApplication::class.qualifiedName, context)
    }
}

Notes:

I show you, constructor in AuthService because it has more than 0 args

Mock runner applies my TestMyApplication class

And TestClass

@RunWith(AndroidJUnit4::class)
    class LoginActivityTest {

@Mock
lateinit var mockAuthService: AuthService

@Rule
@JvmField
val activityRule = ActivityTestRule<LoginActivity>(LoginActivity::class.java, false, false)

@Before
fun beforeEach() {
    MockitoAnnotations.initMocks(this)
    Mockito.doReturn(NOT_SIGNED).`when`(mockAuthService).getUserSignedStatus(ArgumentMatchers.anyBoolean())
    println(mockAuthService.getUserSignedStatus(true)) //test
}

@Test
fun buttonLogin() {
    activityRule.launchActivity(Intent())
    onView(withText("Google")).check(matches(isDisplayed()));
}
}

What do I want?
- In the simplest way attach mocked AuthService to LoginActivity

What I've got? Error:

While calling method:  android.content.Context.getSharedPreferences
In line:

Mockito.doReturn(NOT_SIGNED).`when`(mockAuthService).getUserSignedStatus(ArgumentMatchers.anyBoolean())

Method getSharedPreferences is called in real method getUserSignedStatus. So now, I'm getting an error because Mockito.when calls the real function which is public. I think, the second problem will be that mocked AuthService is not injected to LoginActivity

Body:
So you should probably provide the AuthService through a module, one for the normal app and one for the android test, which supplies the mocked version.  That would mean removing the Dagger annotations from the AuthService class.  I don't use Component.Factory but this example should be enough to for you to use as a guide.

In androidTest folder :

Create test module :

    // normal app should include the module to supply this dependency
    @Module object AndroidTestModule {

        val mock : AuthService = Mockito.mock(AuthService::class.java)

        @Provides
        @Singleton
        @JvmStatic
        fun mockService() : AuthService =  mock

    }

Create test component :

@Component(modules = [AndroidTestModule::class])
@Singleton
interface AndroidTestComponent : AndroidInjector<AndroidTestApp> {

    @Component.Builder interface Builder {

        @BindsInstance fun app(app : Application) : Builder

        fun build() : AndroidTestComponent
    }
}

Create test app :

class AndroidTestApp : DaggerApplication() {

    override fun onCreate() {
        super.onCreate()

        Timber.plant(Timber.DebugTree())
    }

    override fun applicationInjector(): AndroidInjector<out DaggerApplication> =
            DaggerAndroidTestAppComponent.builder().app(this).build()
}

then the runner :

class AndroidTestAppJunitRunner : AndroidJUnitRunner() {

    override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
        return super.newApplication(cl, AndroidTestApp::class.java.canonicalName, context)
    }
}

include in android closure in Gradle :

testInstrumentationRunner "com.package.name.AndroidTestAppJunitRunner"

add these deps :

kaptAndroidTest "com.google.dagger:dagger-compiler:$daggerVersion"
kaptAndroidTest "com.google.dagger:dagger-android-processor:$daggerVersion"

androidTestImplementation "org.mockito:mockito-android:2.27.0"
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

then a test :

@RunWith(AndroidJUnit4::class) class LoginActivityTest {

    @Rule
    @JvmField
    val activityRule = ActivityTestRule<LoginActivity>(LoginActivity::class.java, false, false)

    @Before
    fun beforeEach() {
Mockito.doReturn(NOT_SIGNED).`when`(AndroidTestModule.mock).getUserSignedStatus(ArgumentMatchers.anyBoolean()
    }

    @Test
    fun buttonLogin() {
        activityRule.launchActivity(Intent())
        onView(withText("Google")).check(matches(isDisplayed()));
    }
}

Your dependency will then supplied through the generated test component graph to LoginActivity


问:
Which C++ standard library headers invoke a requirement for the -pthread option with GCC?
If you use C++ threads with the GCC compiler (or perhaps more accurately, with the libstdc++ C++ standard library which ships with GCC) on Linux, you may need to include the -pthread option in your build process to get things to compile and link properly.

What I'm curious about is which library headers invoke that requirement? #include <thread> is an obvious one, but are there other standard library headers which implicitly have a pthread dependency for libstdc++?

答:
<thread> <mutex> <condition_variable> <future> <shared_mutex> <stop_token> all use Pthreads types and functions.

The Networking TS  headers such as <experimental/net> and <experimental/executor> use <mutex> and <future> so they also depend on Pthreads.

We'll soon be adding more concurrency headers such as <latch> <barrier> <semaphore>.

Basically anything related to concurrency and synchronization, except <atomic> which notably does not depend on anything from Pthreads.


问:
Are there any all-in-one packages that help install wamp on a production server?
I need to install amp on a windows2003 production server. I'd like, if possible, an integrated install/management tool so I don't have to install/integrate the components of amp separately. Those that I've found are 'development' servers. Are there any packages out there that install amp in a production ready (locked down state)?

I'm aware of LAMP... Windows, since we have IIS apps already and we've paid for this box, is a requirement. I'll take care of all the other hangups. I just want a simple way to install, integrate, and manage AMP.

答:
There doesn't appear to be any all-in one packages that are up to date and 'designed' for production. You just can't trust the default installs to be secure on whats out there.

WampDeveloper Pro is a commercial WAMP package that is specifically designed for production use (which I use).

I don't think that when this question was asked there was a viable solution for the above.

OwnerDisplayName: Deeno

ContentLicense: CC BY-SA 2.5


问:
Creating a custom "event listener" with es6 modules
We are working on creating custom event listener on Javascript. Tried out a few examples but couldn't get custom event listener to be called. Code example:

events.js

```<code>function init() {
    return new Promise(() => {
        console.log('successfully initialized!');
    });
}

// this symbolizes some event occurring randomly. in reality, this will eventually be
// something like a webhook getting hit, or a websocket, etc. for now we just use
// setTimeout to simulate this event coming in at some time after init has been called
setTimeout(on, 15000);

// on is called anytime any event occurs. in this example, we hardcode that event1 occurred
function on() {
    console.log('event1 occurred in events.js');
    return 'event1';
}

const events = {
    init,
    on,
};

export default events;
</code>```

index.js

```<code>events.init(() => {
        // here we should see console log about successful initialization
    }).then(() => {
        // here, we want to "listen" for event1 to occur
        events.on('event1', () => {
            console.log('we were notified about event1 happening!');
        });
    });
</code>```

In this example we see following being displayed in browser console

```<code>successfully initialized!
</code>```

And then few seconds later:

```<code>event1 occurred in events.js
</code>```

As shown in example callback code for "event1" from index.js is never called, instead "on" function from events.js is called.
What we need is a custom event listener to work so we can call "event1" from index.js console.log should display

```<code>we were notified about event1 happening!
</code>```

Thank you for reviewing the question and helping with solution.

答:
I'd say that there are few problems here.

1. Unresolved promise

First of all, you're not resolving the promise, this means that the then callback never gets called.

So, at first you should update the init method as the following:

function init() {
  return new Promise((resolve) => {
    console.log('successfully initialized!');

    // when you're done with your stuff, tell outside
    resolve()
  });
}
```

<p><strong>2. Tracking callbacks</strong></p>

<p>Than, you're not keeping track of the different callback for the different type of events. The on method should than save the tuple event-callback in an appropriate map as the following:</p>

<pre class="lang-js prettyprint-override"><code>const handlers = {}
function on(event, callback) {
  handlers[event] = callback;
}
</code>```

3. Event emission

The last thing that I think you are missing is the concept of "emission" of an event. When something in particular happen, you should emit a proper event. Than, if it has been registered a callback, you're going to call it.

So, you need to add a third emit method to your events api as the following:

function emit(event) {
  const callback = handlers[event];

  // if we registered a callback before, and it is a function,
  // let's call it
  if ( callback && typeof callback === 'function' )
    callback()
}
```

<p>Your final export becomes:</p>

<pre class="lang-js prettyprint-override"><code>const events = {
  init,
  on,
  emit
};
</code>```

With this new method, you can simulate your call emitting the event event1 as the one you're registering:

setTimeout(() => emit('event1'), 5000);
```

<p>It seems to work like a charm :)</p>

<h2>EDIT</h2>

<p>I'm not sure if this might be the exact use case asked by @Shehzad Nizamani, but we can do <code>emit</code> triggers all registered callbacks if no particular events are given, something like:</p>

<pre class="lang-js prettyprint-override"><code>setTimeout(emit, 5000)

function emit(event) {
  if ( event ) {
    const callback = handlers[event];

    // if we registered a callback before, and it is a function,
    // let's call it
    if ( callback && typeof callback === 'function' )
      callback()

  // if no event is given, we trigger all the callbacks
  } else {

    const callbacks = Object.values(handlers)
    callbacks.forEach(callback => {
      if ( typeof callback === 'function' )
        callback()
    })
  }
}
</code>```

function init() {
  return new Promise((resolve) => {
    console.log('successfully initialized!');

    // when you're done with your stuff, tell outside
    resolve()
  });
}

// emit a specific event to trigger the relative callback
setTimeout(() => emit('event1'), 10000);
setTimeout(emit, 5000);

// we need to keep track of a map
// between event types and their callback
const handlers = {}
function on(event, callback) {
  handlers[event] = callback;
}

// we need a new api that triggers registered callbacks
function emit(event) {
  if ( event ) {
    const callback = handlers[event];

    // if we registered a callback before, and it is a function,
    // let's call it
    if ( callback && typeof callback === 'function' )
      callback()

  // if no event is given, we trigger all the callbacks
  } else {

    const callbacks = Object.values(handlers)
    callbacks.forEach(callback => {
      if ( typeof callback === 'function' )
        callback()
    })
  }
}

const events = {
  init,
  on,
  emit
};

events.init(
  () => {
    // here we should see console log
    //about successful initialization
  }
).then(
  () => {

    // here, we want to "listen" for event1 to occur
    events.on('event1', () => {
      console.log('we were notified about event1 happening!');
    });
  }
);```

Body:
We are working on creating custom event listener on Javascript. Tried out a few examples but couldn't get custom event listener to be called. Code example:

events.js

function init() {
    return new Promise(() => {
        console.log('successfully initialized!');
    });
}

// this symbolizes some event occurring randomly. in reality, this will eventually be
// something like a webhook getting hit, or a websocket, etc. for now we just use
// setTimeout to simulate this event coming in at some time after init has been called
setTimeout(on, 15000);

// on is called anytime any event occurs. in this example, we hardcode that event1 occurred
function on() {
    console.log('event1 occurred in events.js');
    return 'event1';
}

const events = {
    init,
    on,
};

export default events;

index.js

events.init(() => {
        // here we should see console log about successful initialization
    }).then(() => {
        // here, we want to "listen" for event1 to occur
        events.on('event1', () => {
            console.log('we were notified about event1 happening!');
        });
    });

In this example we see following being displayed in browser console

successfully initialized!

And then few seconds later:

event1 occurred in events.js

As shown in example callback code for "event1" from index.js is never called, instead "on" function from events.js is called.
What we need is a custom event listener to work so we can call "event1" from index.js console.log should display

we were notified about event1 happening!

Thank you for reviewing the question and helping with solution.

Body:
I'd say that there are few problems here.

1. Unresolved promise

First of all, you're not resolving the promise, this means that the then callback never gets called.

So, at first you should update the init method as the following:

function init() {
  return new Promise((resolve) => {
    console.log('successfully initialized!');

    // when you're done with your stuff, tell outside
    resolve()
  });
}

2. Tracking callbacks

Than, you're not keeping track of the different callback for the different type of events. The on method should than save the tuple event-callback in an appropriate map as the following:

const handlers = {}
function on(event, callback) {
  handlers[event] = callback;
}

3. Event emission

The last thing that I think you are missing is the concept of "emission" of an event. When something in particular happen, you should emit a proper event. Than, if it has been registered a callback, you're going to call it.

So, you need to add a third emit method to your events api as the following:

function emit(event) {
  const callback = handlers[event];

  // if we registered a callback before, and it is a function,
  // let's call it
  if ( callback && typeof callback === 'function' )
    callback()
}

Your final export becomes:

const events = {
  init,
  on,
  emit
};

With this new method, you can simulate your call emitting the event event1 as the one you're registering:

setTimeout(() => emit('event1'), 5000);

It seems to work like a charm :)

EDIT

I'm not sure if this might be the exact use case asked by @Shehzad Nizamani, but we can do emit triggers all registered callbacks if no particular events are given, something like:

setTimeout(emit, 5000)

function emit(event) {
  if ( event ) {
    const callback = handlers[event];

    // if we registered a callback before, and it is a function,
    // let's call it
    if ( callback && typeof callback === 'function' )
      callback()

  // if no event is given, we trigger all the callbacks
  } else {

    const callbacks = Object.values(handlers)
    callbacks.forEach(callback => {
      if ( typeof callback === 'function' )
        callback()
    })
  }
}

function init() {
  return new Promise((resolve) => {
    console.log('successfully initialized!');

    // when you're done with your stuff, tell outside
    resolve()
  });
}

// emit a specific event to trigger the relative callback
setTimeout(() => emit('event1'), 10000);
setTimeout(emit, 5000);

// we need to keep track of a map
// between event types and their callback
const handlers = {}
function on(event, callback) {
  handlers[event] = callback;
}

// we need a new api that triggers registered callbacks
function emit(event) {
  if ( event ) {
    const callback = handlers[event];

    // if we registered a callback before, and it is a function,
    // let's call it
    if ( callback && typeof callback === 'function' )
      callback()

  // if no event is given, we trigger all the callbacks
  } else {

    const callbacks = Object.values(handlers)
    callbacks.forEach(callback => {
      if ( typeof callback === 'function' )
        callback()
    })
  }
}

const events = {
  init,
  on,
  emit
};

events.init(
  () => {
    // here we should see console log
    //about successful initialization
  }
).then(
  () => {

    // here, we want to "listen" for event1 to occur
    events.on('event1', () => {
      console.log('we were notified about event1 happening!');
    });
  }
);


问:
How can i obtain/define input output names of my graph or freeze it in proper form
Hi everyone we have been trying to save our model in .bytes format so that we can use it in a c# script.
We are using tensorflow 1.7.0
Here is our model:

```<code>bsize=16

# define cnn model
def define_model():
    # load model
    model = VGG16(include_top=False, input_shape=(224, 224, 3))
    # mark loaded layers as not trainable
    for layer in model.layers:
        layer.trainable = False
    # add new classifier layers
    flat1 = Flatten()(model.layers[-1].output)
    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)
    output = Dense(2, activation='softmax')(class1)
    # define new model
    model = Model(inputs=model.inputs, outputs=output)
    # compile model
    # compile model
    opt = Adam(lr=0.001)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    return model
</code>```

Training:

```<code>sess=tf.Session()
tf.global_variables_initializer().run(session=sess)
model = define_model()
# create data generator
datagen = ImageDataGenerator(rescale=1.0/255.0)
# prepare iterators
train_it = datagen.flow_from_directory(mpath+'/train',
class_mode='categorical', batch_size=bsize, target_size=(224, 224))
test_it = datagen.flow_from_directory(mpath+'/test',
class_mode='categorical', batch_size=bsize, target_size=(224, 224))
# fit model
history = model.fit_generator(train_it, steps_per_epoch=len(train_it),
validation_data=test_it, validation_steps=len(test_it), epochs=1, verbose=0)
# evaluate model
_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)
print('> %.3f' % (acc * 100.0))

model.save_weights("weights.h5")
</code>```

Freeze:

```<code>K.clear_session()
K.set_learning_phase(0)
model = define_model()
model.load_weights("weights.h5")

save_dir = "./out"

tf.saved_model.simple_save(K.get_session(),
                           save_dir,
                           inputs={"input": model.inputs[0]},
                           outputs={"output": model.outputs[0]})

freeze_graph.freeze_graph(None,
                          None,
                          None,
                          None,
                          model.outputs[0].op.name,
                          None,
                          None,
                          os.path.join(save_dir, "frozen_model.bytes"),
                          False,
                          "",
                          input_saved_model_dir=save_dir)
</code>```

Then we try to see input and output names using:

```<code>    model.inputs[0].name
    model.ouputs[0].name
</code>```

Finally we would like to use this graph in c# as:

```<code>.AddInput(graph["input_1_1:0"][0], tensor).Fetch(graph["output"][0]);
</code>```

However, as we understand from the error input and output names are wrong. Moreover  whenever we call

```<code>model.inputs[0].name
model.ouputs[0].name
</code>```

they print different input and output names even if we define output name as name="output"

Do you have any suggestions about how to freeze this model, obtain input and output names etc

regards

答:
How about this:

```<code>my_input = tf.keras.layers.Input(shape=[224,224,3], name="my_input")
vgg = tf.keras.applications.VGG16(input_tensor=my_input)
my_output = tf.identity(vgg.output, name="my_output")
</code>```

Now you know the names of your input and output tensors:

```<code>In [0]: my_input
Out[0]: <tf.Tensor 'my_input:0' shape=(?, 224, 224, 3) dtype=float32>

In [1]: my_output
Out[1]: <tf.Tensor 'my_output:0' shape=(?, 1000) dtype=float32>
</code>```

Body:
Hi everyone we have been trying to save our model in .bytes format so that we can use it in a c# script.
We are using tensorflow 1.7.0
Here is our model:

bsize=16

# define cnn model
def define_model():
    # load model
    model = VGG16(include_top=False, input_shape=(224, 224, 3))
    # mark loaded layers as not trainable
    for layer in model.layers:
        layer.trainable = False
    # add new classifier layers
    flat1 = Flatten()(model.layers[-1].output)
    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)
    output = Dense(2, activation='softmax')(class1)
    # define new model
    model = Model(inputs=model.inputs, outputs=output)
    # compile model
    # compile model
    opt = Adam(lr=0.001)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    return model

Training:

sess=tf.Session()
tf.global_variables_initializer().run(session=sess)
model = define_model()
# create data generator
datagen = ImageDataGenerator(rescale=1.0/255.0)
# prepare iterators
train_it = datagen.flow_from_directory(mpath+'/train',
class_mode='categorical', batch_size=bsize, target_size=(224, 224))
test_it = datagen.flow_from_directory(mpath+'/test',
class_mode='categorical', batch_size=bsize, target_size=(224, 224))
# fit model
history = model.fit_generator(train_it, steps_per_epoch=len(train_it),
validation_data=test_it, validation_steps=len(test_it), epochs=1, verbose=0)
# evaluate model
_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)
print('> %.3f' % (acc * 100.0))

model.save_weights("weights.h5")

Freeze:

K.clear_session()
K.set_learning_phase(0)
model = define_model()
model.load_weights("weights.h5")

save_dir = "./out"

tf.saved_model.simple_save(K.get_session(),
                           save_dir,
                           inputs={"input": model.inputs[0]},
                           outputs={"output": model.outputs[0]})

freeze_graph.freeze_graph(None,
                          None,
                          None,
                          None,
                          model.outputs[0].op.name,
                          None,
                          None,
                          os.path.join(save_dir, "frozen_model.bytes"),
                          False,
                          "",
                          input_saved_model_dir=save_dir)

Then we try to see input and output names using:

    model.inputs[0].name
    model.ouputs[0].name

Finally we would like to use this graph in c# as:

.AddInput(graph["input_1_1:0"][0], tensor).Fetch(graph["output"][0]);

However, as we understand from the error input and output names are wrong. Moreover  whenever we call

model.inputs[0].name
model.ouputs[0].name

they print different input and output names even if we define output name as name="output"

Do you have any suggestions about how to freeze this model, obtain input and output names etc

regards

Body:
How about this:

my_input = tf.keras.layers.Input(shape=[224,224,3], name="my_input")
vgg = tf.keras.applications.VGG16(input_tensor=my_input)
my_output = tf.identity(vgg.output, name="my_output")

Now you know the names of your input and output tensors:

In [0]: my_input
Out[0]: <tf.Tensor 'my_input:0' shape=(?, 224, 224, 3) dtype=float32>

In [1]: my_output
Out[1]: <tf.Tensor 'my_output:0' shape=(?, 1000) dtype=float32>


问:
How do I remove duplicates in mongodb based on multiple fields?
Here's an example of my docs:

```<code>[{name:"duplicate", value:true, id:2910921},{name:"duplicate", value:true, id:32838293},{name:"duplicate", value:false, id:3283232},{name:"notDuplicate", value:true, id:382932}]
</code>```

I want to remove if there are multiple documents that contain the same name and the same value. In the example above it would remove one document, either {name:"duplicate", value:true, id:2910921} or {name:"duplicate", value:true, id:32838293}, it does't matter to me which one.

So far, I've considered just creating a new field for each of these which would be something like newField: "duplicatetrue" and then I could just use distinct on these to remove dupes, but I am having trouble figuring out how to concat two different fields with different types into a new field. I'm definitely open to better suggestions as well. Here's what I have so far:

```<code>db.collection(collectionName).updateMany({}, {$set: {"newField": ["$name","$value"]  }})
</code>```

However, the above line doesn't output the values, rather it outputs exactly newField: ["$name","$value"]

Removing the quotes from $name and $value does not work either.

I'm using the Node mongodb driver: 3.5.8

答:
You can do it in two ways

In one DB call : Using aggregation operator $out, Maybe you can also use $merge but which is not much useful for your case.

In two DB calls : As if you think $out is destructive and with millions of documents in collection can be an issue in production environment, then you can first read all the _id's of documents to be deleted & use .deleteMany() to delete all docs at once. (You can use any unique identifier on a doc instead of _id but I've used _id as it's indexed by default - which can help to run deleteMany() quicker).

Step 1:

Using $out - So as I've said it is destructive cause it will override the entire collection if input name matches or will create a new collection by the result of your aggregation query. So test your aggregation query very well prior to using $out as last stage. Also write data to temporary collection & rename the collections after everything is good enough. Consider a down-time while renaming collections

Query :

```<code>db.collection.aggregate([
  {
    $group: { _id: { name: "$name", value: "$value" },
      doc: { $last: "$$ROOT" } // Retrieve only last doc in a group
    }
  },
  {
    $replaceRoot: { newRoot: "$doc" } // replace doc as object as new root of document
  },
  { $out : 'collection_new' } // Test above aggregation & then use this
])
</code>```

Test : mongoplayground

Step 2:

Using an aggregation query you'll get list of _ids to be deleted from collection.

Query :

```<code>db.collection.aggregate([
    /**
     * Group on matching docs :
     * { name: "duplicate", value: false},
     * { name: "duplicate", value: true},
     * { name: "duplicate-yes", value: true},
     * { name: "notDuplicate", value: true}
     * */
    {
      $group: {
        _id: { name: "$name", value: "$value" },
        _idsNeedsToBeDeleted: { $push: "$$ROOT._id" } // push all `_id`'s to an array
      }
    },
    /** Remove first element - which is removing a doc */
    {
      $project: {
        _id: 0,
        _idsNeedsToBeDeleted: { $slice: [ "$_idsNeedsToBeDeleted", 1, { $size: "$_idsNeedsToBeDeleted" } ] }
      }
    },
    {
      $unwind: "$_idsNeedsToBeDeleted" // Unwind `_idsNeedsToBeDeleted`
    },
    /** Group without a condition & push all `_idsNeedsToBeDeleted` fields to an array */
    {
      $group: { _id: "", _idsNeedsToBeDeleted: { $push: "$_idsNeedsToBeDeleted" } }
    },
    {$project : { _id : 0 }} // Optional stage
     /** At the end you'll have an [{ _idsNeedsToBeDeleted: [_ids] }] or [] */
  ])
</code>```

Test : mongoplayground

Now using .deleteMany() - delete all docs :

Query :

```<code>db.collection.deleteMany( { "_id" : {$in : [_ids]} } );
</code>```

Consideration prior to .deleteMany() you need to check aggregation result is not an empty array [] & has a doc with _idsNeedsToBeDeleted field which is an array. Also since we're matching against _id in DB - aggregations _idsNeedsToBeDeleted array will be an array of strings - So iterate over array, convert string to ObjectId() & use that array of ObjectId()'s in delete query.

Note :

Irrespective of what step you choose - Since we're grouping on name + value you need to make sure all of your docs has those fields.

Body:
Here's an example of my docs:

[{name:"duplicate", value:true, id:2910921},{name:"duplicate", value:true, id:32838293},{name:"duplicate", value:false, id:3283232},{name:"notDuplicate", value:true, id:382932}]

I want to remove if there are multiple documents that contain the same name and the same value. In the example above it would remove one document, either {name:"duplicate", value:true, id:2910921} or {name:"duplicate", value:true, id:32838293}, it does't matter to me which one.

So far, I've considered just creating a new field for each of these which would be something like newField: "duplicatetrue" and then I could just use distinct on these to remove dupes, but I am having trouble figuring out how to concat two different fields with different types into a new field. I'm definitely open to better suggestions as well. Here's what I have so far:

db.collection(collectionName).updateMany({}, {$set: {"newField": ["$name","$value"]  }})

However, the above line doesn't output the values, rather it outputs exactly newField: ["$name","$value"]

Removing the quotes from $name and $value does not work either.

I'm using the Node mongodb driver: 3.5.8

Body:
You can do it in two ways

In one DB call : Using aggregation operator $out, Maybe you can also use $merge but which is not much useful for your case.

In two DB calls : As if you think $out is destructive and with millions of documents in collection can be an issue in production environment, then you can first read all the _id's of documents to be deleted & use .deleteMany() to delete all docs at once. (You can use any unique identifier on a doc instead of _id but I've used _id as it's indexed by default - which can help to run deleteMany() quicker).

Step 1:

Using $out - So as I've said it is destructive cause it will override the entire collection if input name matches or will create a new collection by the result of your aggregation query. So test your aggregation query very well prior to using $out as last stage. Also write data to temporary collection & rename the collections after everything is good enough. Consider a down-time while renaming collections

Query :

db.collection.aggregate([
  {
    $group: { _id: { name: "$name", value: "$value" },
      doc: { $last: "$$ROOT" } // Retrieve only last doc in a group
    }
  },
  {
    $replaceRoot: { newRoot: "$doc" } // replace doc as object as new root of document
  },
  { $out : 'collection_new' } // Test above aggregation & then use this
])

Test : mongoplayground

Step 2:

Using an aggregation query you'll get list of _ids to be deleted from collection.

Query :

db.collection.aggregate([
    /**
     * Group on matching docs :
     * { name: "duplicate", value: false},
     * { name: "duplicate", value: true},
     * { name: "duplicate-yes", value: true},
     * { name: "notDuplicate", value: true}
     * */
    {
      $group: {
        _id: { name: "$name", value: "$value" },
        _idsNeedsToBeDeleted: { $push: "$$ROOT._id" } // push all `_id`'s to an array
      }
    },
    /** Remove first element - which is removing a doc */
    {
      $project: {
        _id: 0,
        _idsNeedsToBeDeleted: { $slice: [ "$_idsNeedsToBeDeleted", 1, { $size: "$_idsNeedsToBeDeleted" } ] }
      }
    },
    {
      $unwind: "$_idsNeedsToBeDeleted" // Unwind `_idsNeedsToBeDeleted`
    },
    /** Group without a condition & push all `_idsNeedsToBeDeleted` fields to an array */
    {
      $group: { _id: "", _idsNeedsToBeDeleted: { $push: "$_idsNeedsToBeDeleted" } }
    },
    {$project : { _id : 0 }} // Optional stage
     /** At the end you'll have an [{ _idsNeedsToBeDeleted: [_ids] }] or [] */
  ])

Test : mongoplayground

Now using .deleteMany() - delete all docs :

Query :

db.collection.deleteMany( { "_id" : {$in : [_ids]} } );

Consideration prior to .deleteMany() you need to check aggregation result is not an empty array [] & has a doc with _idsNeedsToBeDeleted field which is an array. Also since we're matching against _id in DB - aggregations _idsNeedsToBeDeleted array will be an array of strings - So iterate over array, convert string to ObjectId() & use that array of ObjectId()'s in delete query.

Note :

Irrespective of what step you choose - Since we're grouping on name + value you need to make sure all of your docs has those fields.


问:
How to properly filter an object that has an array of objects
I'm trying to filter an array to get only what I want and I have tried with filter and reduce, but I was not able to make it fully work. I'm trying to get only the objects that has "System.State" with an "oldValue" and a "newValue"

```<code>const data = {
  "value": [
    {
      "id": 23,
      "fields": {
        "System.State": {
          "oldValue": "Forecasted",
          "newValue": "Done"
        }
      }
    },
  ]
}
</code>```

The problem is that value array contains several objects that may NOT have "System.State" and some that have "System.State" but only with "newValue", instead of "oldValue" and "newValue", so I'm receiving a lot of undefined errors and I really don't know how to treat these situations.

This is a example that dont have "System.State" and another one that have "System.State" but with "newValue" only:

```<code>const data = {
  "value": [
    {
      "id": 23,
      "fields": {
        "System.State": {
          "oldValue": "Forecasted",
          "newValue": "Done"
        }
      }
    },
    {
      "id": 24,
      "fields": {
        "System.State": {
          "newValue": "New"
        }
      }
    },
    {
      "id": 25,
      "fields": {
        "System.AuthorizedDate": { // This is only an example of an object that does not have System.State
          "newValue": "2020-03-13T14:14:37.1Z"
        }
      }
    },
  ]
}
</code>```

I'm using TFS API if anyone wants to know. This is what I have tried using filter:

```<code>data.value.fields.filter(status => status.fields['System.State'].oldValue === 'Forecasted' && status.fields['System.State'] === 'Done')
</code>```

And this was using reducer:

```<code>  const filter = data.value.reduce((c, n) => {
    const HasNewAndOldValue = c.fields['System.State'].oldValue === 'Forecasted' && c.fields['System.State'].newValue === 'Done';
    if (c.fields['System.State'] && HasNewAndOldValue) {
      return c;
    }
    c.push(n);
  }, [])
  console.log(data.value.fields && filter);
</code>```

What I'm doing wrong? Btw, I'm using ['System.State'] because I can't access an object property that has a dot.

答:
In your filter example, replace data.value.fields.filter() with data.value.filter(), because data.value is an array.

const data = {
  "value": [
    {
      "id": 23,
      "fields": {
        "System.State": {
          "oldValue": "Forecasted",
          "newValue": "Done"
        }
      }
    },
    {
      "id": 24,
      "fields": {
        "System.State": {
          "newValue": "New"
        }
      }
    },
    {
      "id": 25,
      "fields": {
        "System.AuthorizedDate": { // This is only an example of an object that does not have System.State
          "newValue": "2020-03-13T14:14:37.1Z"
        }
      }
    },
  ]
}

console.log(
  data.value.filter((item) => {
    const fields = item.fields || {};
    const state = fields['System.State'];
    if (!state) {
      return false;
    }

    return state.oldValue && state.newValue;
  })

);```

Body:
I'm trying to filter an array to get only what I want and I have tried with filter and reduce, but I was not able to make it fully work. I'm trying to get only the objects that has "System.State" with an "oldValue" and a "newValue"

const data = {
  "value": [
    {
      "id": 23,
      "fields": {
        "System.State": {
          "oldValue": "Forecasted",
          "newValue": "Done"
        }
      }
    },
  ]
}

The problem is that value array contains several objects that may NOT have "System.State" and some that have "System.State" but only with "newValue", instead of "oldValue" and "newValue", so I'm receiving a lot of undefined errors and I really don't know how to treat these situations.

This is a example that dont have "System.State" and another one that have "System.State" but with "newValue" only:

const data = {
  "value": [
    {
      "id": 23,
      "fields": {
        "System.State": {
          "oldValue": "Forecasted",
          "newValue": "Done"
        }
      }
    },
    {
      "id": 24,
      "fields": {
        "System.State": {
          "newValue": "New"
        }
      }
    },
    {
      "id": 25,
      "fields": {
        "System.AuthorizedDate": { // This is only an example of an object that does not have System.State
          "newValue": "2020-03-13T14:14:37.1Z"
        }
      }
    },
  ]
}

I'm using TFS API if anyone wants to know. This is what I have tried using filter:

data.value.fields.filter(status => status.fields['System.State'].oldValue === 'Forecasted' && status.fields['System.State'] === 'Done')

And this was using reducer:

  const filter = data.value.reduce((c, n) => {
    const HasNewAndOldValue = c.fields['System.State'].oldValue === 'Forecasted' && c.fields['System.State'].newValue === 'Done';
    if (c.fields['System.State'] && HasNewAndOldValue) {
      return c;
    }
    c.push(n);
  }, [])
  console.log(data.value.fields && filter);

What I'm doing wrong? Btw, I'm using ['System.State'] because I can't access an object property that has a dot.


问:
How to unfocus text field in flutter?

I don't know if this is normal flutter behavior, but it is annoying that you lose focus only when you tap on the keyboard "ok" button to lose focus. If this is not done, the cursor will remain active within the text field.

What is the best practice to avoid this?
(In the gif it is not well appreciated, but the only way to lose focus is by tapping on the "ok" button on the keyboard, otherwise the cursor will always be active regardless of whether you tap on other areas of the screen)

```<code>    Widget _searchBar() {
     return Container(
      child: TextField(
        textAlignVertical: TextAlignVertical.center,
        style: TextStyle(
          textBaseline: TextBaseline.alphabetic,
          color: _styles["gris_oscuro1"]["color"],
        ),
        onChanged: (value) {},
        decoration: InputDecoration(
          filled: true,
          fillColor: _styles["gris_claro"]["color"],
          alignLabelWithHint: true,
          hintText: "Buscar por código",
          hintStyle: TextStyle(color: _styles["gris_oscuro2"]["color"]),
          prefixIcon:
              Icon(Icons.search, color: _styles["gris_oscuro2"]["color"]),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(40)),
            borderSide:
                BorderSide(color: _styles["gris_claro"]["color"], width: 1.0),
          ),
        ),
      ),
    );
    );

    Scaffold(
        key: _scaffoldKey,
        backgroundColor: _styles["fondo"]["bg"],
        drawer: MenuWidget(),
        body: SafeArea(
        child: _searchBar(),
        )
</code>```

答:
Wrap your full page in GestureDetector and modify it's onTap function as follows:

```<code>@override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () { //here
        FocusScope.of(context).unfocus();
        new TextEditingController().clear();
      },
      child: Container(
      ...
    );
  }
</code>```

Title: How to unfocus text field in flutter?

Body:
I don't know if this is normal flutter behavior, but it is annoying that you lose focus only when you tap on the keyboard "ok" button to lose focus. If this is not done, the cursor will remain active within the text field.

What is the best practice to avoid this?
(In the gif it is not well appreciated, but the only way to lose focus is by tapping on the "ok" button on the keyboard, otherwise the cursor will always be active regardless of whether you tap on other areas of the screen)

    Widget _searchBar() {
     return Container(
      child: TextField(
        textAlignVertical: TextAlignVertical.center,
        style: TextStyle(
          textBaseline: TextBaseline.alphabetic,
          color: _styles["gris_oscuro1"]["color"],
        ),
        onChanged: (value) {},
        decoration: InputDecoration(
          filled: true,
          fillColor: _styles["gris_claro"]["color"],
          alignLabelWithHint: true,
          hintText: "Buscar por código",
          hintStyle: TextStyle(color: _styles["gris_oscuro2"]["color"]),
          prefixIcon:
              Icon(Icons.search, color: _styles["gris_oscuro2"]["color"]),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(40)),
            borderSide:
                BorderSide(color: _styles["gris_claro"]["color"], width: 1.0),
          ),
        ),
      ),
    );
    );

    Scaffold(
        key: _scaffoldKey,
        backgroundColor: _styles["fondo"]["bg"],
        drawer: MenuWidget(),
        body: SafeArea(
        child: _searchBar(),
        )

Body:
Wrap your full page in GestureDetector and modify it's onTap function as follows:

@override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () { //here
        FocusScope.of(context).unfocus();
        new TextEditingController().clear();
      },
      child: Container(
      ...
    );
  }


问:
Pointers and Dynamically Allocating Arrays error in C++
I am getting an introduction to pointers and I don't understand the following code.    </p>

```<code>int main(){
        int *p;
        p=new int[5];
        cout << p <<endl;  // line 4
        *p=3;
        p=p+1;
        cout <<p <<endl;  // line 7
        *p=7;
        cout << p[0] <<endl;
    }
</code>```

<p>line 4 and line 7 prints the memory location as 0xd91730 and 0xd91734 respectively and I understand that. However, why is the last line `( p[0] )  printing 7 on the screen. Isn't p[0] = 3 instead, as assigned in line 5. I am not understanding this concept. Can anyone please help? Thank you.  </p>

答:
When dealing with pointers the square bracket notation is just way of dereferencing a pointer.

```<code>p[x]   is syntactically equivalent to   *(p + x)
</code>```

So you are de-referencing the memory location x points ahead of the pointer.

In your code. After you have allocated memory you move the pointer:

```<code>    p = p+1;   // This moves p to point at the next location in memory.
</code>```

Now your memory looks like this:

```<code>Memory      0xd91730        [0, 0, 0 ,3]   => 4 bytes
p --------->0xd91734        [0, 0, 0, 7]   => 4 bytes (yes I am making an assumption
            0xd91738        [?, ?, ?, ?]               about layout for demonstrating
            0xd9173c        [?, ?, ?, ?]               purposes)
</code>```

De-referencing p will give you the content at 0xs91734.

Try adding the following line:

```<code>            std::cout << p[-1] << "\n"; // Should return the 3 you were looking for
</code>```

Just for fun try:

```<code>            std::cout << 0[p] << "\n";  // Blows your mind but works.

            // Pointer + integer is a pointer.
            // integer + Pointer is also a pointer.
            // So 0[p] => *(0 + p) => *(p + 0) => p[0]
</code>```

Body:
I am getting an introduction to pointers and I don't understand the following code.

int main(){
        int *p;
        p=new int[5];
        cout << p <<endl;  // line 4
        *p=3;
        p=p+1;
        cout <<p <<endl;  // line 7
        *p=7;
        cout << p[0] <<endl;
    }

line 4 and line 7 prints the memory location as 0xd91730 and 0xd91734 respectively and I understand that. However, why is the last line `( p[0] )  printing 7 on the screen. Isn't p[0] = 3 instead, as assigned in line 5. I am not understanding this concept. Can anyone please help? Thank you.

Body:
When dealing with pointers the square bracket notation is just way of dereferencing a pointer.

p[x]   is syntactically equivalent to   *(p + x)

So you are de-referencing the memory location x points ahead of the pointer.

In your code. After you have allocated memory you move the pointer:

    p = p+1;   // This moves p to point at the next location in memory.

Now your memory looks like this:

Memory      0xd91730        [0, 0, 0 ,3]   => 4 bytes
p --------->0xd91734        [0, 0, 0, 7]   => 4 bytes (yes I am making an assumption
            0xd91738        [?, ?, ?, ?]               about layout for demonstrating
            0xd9173c        [?, ?, ?, ?]               purposes)

De-referencing p will give you the content at 0xs91734.

Try adding the following line:

            std::cout << p[-1] << "\n"; // Should return the 3 you were looking for

Just for fun try:

            std::cout << 0[p] << "\n";  // Blows your mind but works.

            // Pointer + integer is a pointer.
            // integer + Pointer is also a pointer.
            // So 0[p] => *(0 + p) => *(p + 0) => p[0]


问:
How do I pass Auth Bearer token to Wapiti web application vulnerability scanner?
I want to security test my web application as well as REST API'S but they require authenticated, How do I pass a Bearer token to it?</p>

答: You can pass this as a header with the -H flag. So -H 'Bearer: [token]'


问:
How to make sure each character of a command argument is a decimal digit?
We have to make a code to encrypt Caesar's cipher. One of the steps is: instead of printing out the command-line argument provided, your program instead checks to make sure that each character of that command line argument is a decimal digit (i.e., 0, 1, 2, etc.) and, if any of them are not, terminates after printing the message Usage: ./caesar key. But if the argument consists solely of digit characters, you should convert that string (recall that argv is an array of strings, even if those strings happen to look like numbers) to an actual integer, and print out the integer, as via %i with printf.
The code below is what I have, but it returns both Success & Error. How can I fix this so that the program checks that each character of the command line argument is a digit?
Code I have

答:
Here is a simple way to check that all characters in a string are in a given set:

```<code>#include <string.h>

int main(int argc, char *argv[]) {
    if (argc > 1) {
        if (strspn(argv[1], "0123456789") == strlen(argv[1]))
            printf("OK\n");
        else
            printf("Invalid characters\n");
    }
    return 0;
}
</code>```

You might want to check that the command line argument has at least 1 character.

Body:
Here is a simple way to check that all characters in a string are in a given set:

#include <string.h>

int main(int argc, char *argv[]) {
    if (argc > 1) {
        if (strspn(argv[1], "0123456789") == strlen(argv[1]))
            printf("OK\n");
        else
            printf("Invalid characters\n");
    }
    return 0;
}

You might want to check that the command line argument has at least 1 character.


问:
Any alternatives to Google Trends?
I'm writing a small helper utility for obscure software that is used at a local shop. Basically, I would like to know if anyone searches for anything associated with that software and if publishing my work on the Internet would make any sense. I entered the name of the software into Google Trends, but my terms "do not have enough search volume to show graphs" despite the fact that Google lists 250,000 results for the software name, or 35,000 if I explicitly remove terms such as serial and warez from the search.

Does anyone know of alternatives to Google Trends? Or of another way to find out if people search for a particular keyword?

答:
Google Trends was also telling me there wasn't enough data for my query. I found Google Insights to do job nicely. And unlike the AdWords tool mentioned in the author's answer, it actually shows a trend.

Here's an example which shows the emergence of 3 terms with too low of volume to show up on Trends: #bigdata, #datascientist & #datajournalism.

Here's a related SO question.

Title: Any alternatives to Google Trends?


问:
Unexpected value 'AngularFirestoreDocument' imported by the module 'AppModule' error
Good day developers , im having an issue i have being struggling with the whole day but can't see the problem, the error thrown is :

Honestly looking the AppComponent at first sight doens't seem to be any remarkable error.Is there by chance any problem with AngularFirestoreDocument and AngularFirestoreCollection im missing?.
Here also leave my app.module.ts scheme.
Thanks in advance

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {
  AngularFirestoreModule,
  AngularFirestoreDocument,
  AngularFirestoreCollection,
} from '@angular/fire/firestore';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { FlashMessagesModule } from 'angular2-flash-messages';
import { AngularFireStorageModule } from '@angular/fire/storage';
import { AngularFireModule } from '@angular/fire';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UserComponent } from './components/user/user.component';
import { UserSheetComponent } from './components/user-sheet/user-sheet.component';
import { UserSheetBalanceComponent } from './components/user-sheet-balance/user-sheet-balance.component';
import { UsersComponent } from './components/users/users.component';
import { LoginComponent } from './components/login/login.component';
import { SignupComponent } from './components/signup/signup.component';
import { HeaderComponent } from './components/header/header.component';
import { FooterComponent } from './components/footer/footer.component';
import { WelcomePageComponent } from './components/welcome-page/welcome-page.component';
import { environment } from 'src/environments/environment';
import { LoginService } from './services/LoginService.service';
import { LogOutService } from './services/LogOutService.service';
import { AuthService } from './services/AuthService.service';
import { ControlMessagesComponent } from './components/control-messages/control-messages.component';
import { ValidationService } from './services/ValidationService.service';
import { SignFormService } from './services/SignInFormService.service';
import { HttpClientModule } from '@angular/common/http';
import { AddingImportService } from './services/addingImportService.service';
import { authguardian } from './guardians/authguardian.guard';

@NgModule({
  declarations: [
    AppComponent,
    UserComponent,
    UserSheetComponent,
    UserSheetBalanceComponent,
    UsersComponent,
    LoginComponent,
    SignupComponent,
    HeaderComponent,
    FooterComponent,
    WelcomePageComponent,
    ControlMessagesComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule,
    FormsModule,
    AngularFireModule.initializeApp(
      environment.firebaseConfig,
      'ngExpenseClassifier'
    ),
    AngularFirestoreModule,
    AngularFireAuthModule,
    AngularFireStorageModule,
    FlashMessagesModule,
    AngularFirestoreDocument,
    AngularFirestoreCollection,
  ],
  providers: [
    LoginService,
    LogOutService,
    AuthService,
    ValidationService,
    SignFormService,
    HttpClientModule,
    AddingImportService,
    authguardian,
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

</code>```

答:
AngularFirestoreDocument and AngularFirestoreCollection are not modules! So it cannot be imported at imports.

Remove AngularFirestoreDocument and AngularFirestoreCollection, and try importing AngularFireDatabaseModule instead!

```<code>imports: [
    ...
    AngularFireDatabaseModule,
  ]
</code>```

Body:
Good day developers , im having an issue i have being struggling with the whole day but can't see the problem, the error thrown is :

Honestly looking the AppComponent at first sight doens't seem to be any remarkable error.Is there by chance any problem with AngularFirestoreDocument and AngularFirestoreCollection im missing?.
Here also leave my app.module.ts scheme.
Thanks in advance

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {
  AngularFirestoreModule,
  AngularFirestoreDocument,
  AngularFirestoreCollection,
} from '@angular/fire/firestore';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { FlashMessagesModule } from 'angular2-flash-messages';
import { AngularFireStorageModule } from '@angular/fire/storage';
import { AngularFireModule } from '@angular/fire';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UserComponent } from './components/user/user.component';
import { UserSheetComponent } from './components/user-sheet/user-sheet.component';
import { UserSheetBalanceComponent } from './components/user-sheet-balance/user-sheet-balance.component';
import { UsersComponent } from './components/users/users.component';
import { LoginComponent } from './components/login/login.component';
import { SignupComponent } from './components/signup/signup.component';
import { HeaderComponent } from './components/header/header.component';
import { FooterComponent } from './components/footer/footer.component';
import { WelcomePageComponent } from './components/welcome-page/welcome-page.component';
import { environment } from 'src/environments/environment';
import { LoginService } from './services/LoginService.service';
import { LogOutService } from './services/LogOutService.service';
import { AuthService } from './services/AuthService.service';
import { ControlMessagesComponent } from './components/control-messages/control-messages.component';
import { ValidationService } from './services/ValidationService.service';
import { SignFormService } from './services/SignInFormService.service';
import { HttpClientModule } from '@angular/common/http';
import { AddingImportService } from './services/addingImportService.service';
import { authguardian } from './guardians/authguardian.guard';

@NgModule({
  declarations: [
    AppComponent,
    UserComponent,
    UserSheetComponent,
    UserSheetBalanceComponent,
    UsersComponent,
    LoginComponent,
    SignupComponent,
    HeaderComponent,
    FooterComponent,
    WelcomePageComponent,
    ControlMessagesComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule,
    FormsModule,
    AngularFireModule.initializeApp(
      environment.firebaseConfig,
      'ngExpenseClassifier'
    ),
    AngularFirestoreModule,
    AngularFireAuthModule,
    AngularFireStorageModule,
    FlashMessagesModule,
    AngularFirestoreDocument,
    AngularFirestoreCollection,
  ],
  providers: [
    LoginService,
    LogOutService,
    AuthService,
    ValidationService,
    SignFormService,
    HttpClientModule,
    AddingImportService,
    authguardian,
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

Body:
AngularFirestoreDocument and AngularFirestoreCollection are not modules! So it cannot be imported at imports.

Remove AngularFirestoreDocument and AngularFirestoreCollection, and try importing AngularFireDatabaseModule instead!

imports: [
    ...
    AngularFireDatabaseModule,
  ]


问:
InvalidArchiveError when installing openssl-1.1.1g through Anaconda 4.7.12 on Windows 10
I am trying to install requests module, and openssl keep causing the InvalidArchiveError.
I am using conda 4.7.12, python 3.8.2, on Windows 10 operating system. I had the same issue when installing other packages requiring openssl-1.1.1g. I have followed the advice from the error message to delete and re-download 'openssl-1.1.1g-he774522_0.tar.bz2', but I keep getting the same error.
Is this version of openssl broken or something? Any help will be greatly appreciated. </p>

```<code>lykim@Louis MINGW64 ~/Desktop/master/Learning
$ conda install -c anaconda requests
Collecting package metadata (current_repodata.json): ...working... done
Solving environment: ...working... done

==> WARNING: A newer version of conda exists. <==
  current version: 4.7.12
  latest version: 4.8.3

Please update conda by running

    $ conda update -n base conda

## Package Plan ##

  environment location: C:\ProgramData\Anaconda3\envs\pytorch

  added / updated specs:
    - requests

The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    openssl-1.1.1g             |       he774522_0         5.8 MB  anaconda
    ------------------------------------------------------------
                                           Total:         5.8 MB

The following NEW packages will be INSTALLED:

  brotlipy           conda-forge/win-64::brotlipy-0.7.0-py38h1e8a9f7_1000
  cffi               anaconda/win-64::cffi-1.14.0-py38h7a1dbc1_0
  chardet            anaconda/win-64::chardet-3.0.4-py38_1003
  cryptography       anaconda/win-64::cryptography-2.9.2-py38h7a1dbc1_0
  idna               anaconda/noarch::idna-2.9-py_1
  pycparser          anaconda/noarch::pycparser-2.20-py_0
  pyopenssl          anaconda/win-64::pyopenssl-19.1.0-py38_0
  pysocks            anaconda/win-64::pysocks-1.7.1-py38_0
  requests           anaconda/win-64::requests-2.23.0-py38_0
  urllib3            conda-forge/noarch::urllib3-1.25.9-py_0
  win_inet_pton      anaconda/win-64::win_inet_pton-1.1.0-py38_0

The following packages will be SUPERSEDED by a higher-priority channel:

  certifi            conda-forge::certifi-2020.4.5.1-py38h~ --> anaconda::certifi-2020.4.5.1-py38_0
  openssl                                       conda-forge --> anaconda

Proceed ([y]/n)? y

Downloading and Extracting Packages
openssl-1.1.1g       | 5.8 MB    | ########## | 100%

InvalidArchiveError('Error with archive C:\\ProgramData\\Anaconda3\\pkgs\\openssl-1.1.1g-he774522_0.tar.bz2.  You probably need to delete and re-download or re-create this file.  Message from libarchive was:\n\nCould not unlink')

(pytorch)
</code>```

答: Encountered the same error, I think it was caused by an earlier failed installation which had left an incomplete openssl-1.1.1g-he774522_0 directory in users\username\Anaconda3\pkgs. Just delete it and then it completes just fine.</p>

Body:
I am trying to install requests module, and openssl keep causing the InvalidArchiveError.
I am using conda 4.7.12, python 3.8.2, on Windows 10 operating system. I had the same issue when installing other packages requiring openssl-1.1.1g. I have followed the advice from the error message to delete and re-download 'openssl-1.1.1g-he774522_0.tar.bz2', but I keep getting the same error.
Is this version of openssl broken or something? Any help will be greatly appreciated.

lykim@Louis MINGW64 ~/Desktop/master/Learning
$ conda install -c anaconda requests
Collecting package metadata (current_repodata.json): ...working... done
Solving environment: ...working... done

==> WARNING: A newer version of conda exists. <==
  current version: 4.7.12
  latest version: 4.8.3

Please update conda by running

    $ conda update -n base conda

## Package Plan ##

  environment location: C:\ProgramData\Anaconda3\envs\pytorch

  added / updated specs:
    - requests

The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    openssl-1.1.1g             |       he774522_0         5.8 MB  anaconda
    ------------------------------------------------------------
                                           Total:         5.8 MB

The following NEW packages will be INSTALLED:

  brotlipy           conda-forge/win-64::brotlipy-0.7.0-py38h1e8a9f7_1000
  cffi               anaconda/win-64::cffi-1.14.0-py38h7a1dbc1_0
  chardet            anaconda/win-64::chardet-3.0.4-py38_1003
  cryptography       anaconda/win-64::cryptography-2.9.2-py38h7a1dbc1_0
  idna               anaconda/noarch::idna-2.9-py_1
  pycparser          anaconda/noarch::pycparser-2.20-py_0
  pyopenssl          anaconda/win-64::pyopenssl-19.1.0-py38_0
  pysocks            anaconda/win-64::pysocks-1.7.1-py38_0
  requests           anaconda/win-64::requests-2.23.0-py38_0
  urllib3            conda-forge/noarch::urllib3-1.25.9-py_0
  win_inet_pton      anaconda/win-64::win_inet_pton-1.1.0-py38_0

The following packages will be SUPERSEDED by a higher-priority channel:

  certifi            conda-forge::certifi-2020.4.5.1-py38h~ --> anaconda::certifi-2020.4.5.1-py38_0
  openssl                                       conda-forge --> anaconda

Proceed ([y]/n)? y

Downloading and Extracting Packages
openssl-1.1.1g       | 5.8 MB    | ########## | 100%

InvalidArchiveError('Error with archive C:\\ProgramData\\Anaconda3\\pkgs\\openssl-1.1.1g-he774522_0.tar.bz2.  You probably need to delete and re-download or re-create this file.  Message from libarchive was:\n\nCould not unlink')

(pytorch)


答:
This data.value.fields is undefined, you should access the property fields through each object within the property value.

const data = {  "value": [    {      "id": 23,      "fields": {        "System.State": {          "oldValue": "Forecasted",          "newValue": "Done"        }      }    },    {      "id": 24,      "fields": {        "System.State": {          "newValue": "New"        }      }    },    {      "id": 25,      "fields": {        "System.AuthorizedDate": {          "newValue": "2020-03-13T14:14:37.1Z"        }      }    }  ]};

console.log(data.value.filter(({fields: {"System.State": state}}) => {
  return state && state.oldValue === "Forecasted" && state.newValue === "Done";
}));```

Title: How to properly filter an object that has an array of objects


问:
Refresh attribute value after html() with ajax
I am making start/pause button that works like this:

```<code>    var btns = document.querySelectorAll(".repairToggle");
    for (i = 0; i < btns.length; i++) {
      btns[i].addEventListener("click", manageOrderStatus);
    }
    function manageOrderStatus() {
      var func = this.getAttribute("func");
      var btn = this;
      var endpoint = "{% url 'mtn:ajax_repair_toggle' %}";
      $.ajax({
        url: endpoint,
        type: "GET",
        data: {
          'func': func,
        },
        success: function (data) {
          $(btn).html(data);
        }
      });
    }
</code>```

I have start and stop buttons stored in separate html files:
work_order_start.html:

```<code><div type="button" class="repairToggle" func="start">
  <svg>...</svg>
</div>
</code>```

work_order_pause.html:

```<code><div type="button" class="repairToggle" func="stop">
  <svg>...</svg>
</div>
</code>```

In view i render one of the buttons based on the value of func attribute:

```<code>def repair_toggle(request):
    ...
    func = request.GET.get('func')
    if func == 'stop':
        return render(request, 'mtn/work_order_start.html')
    else:
        return render(request, 'mtn/work_order_pause.html')
</code>```

The problem is it only works once. After the first click it keeps executing ajax call but it sends the same old func value in request. How do i fix that?

UPDATE:

I figured out the problem. $(btn).html(data); only replaces the svg element. So the func stays the same. If i do this instead:

```<code><div type="button" class="repairToggle">
  <svg id='funcButton' func="stop">
</div>
</code>```

How do i get func out of svg. I tried this.getElementById('funcButton').getAttribute("func"); but it doesn't work.

答:
You are inserting the button inside the original button.

Change work_order_pause.html and work_order_start.html to only contain the svg and add in success function :

```<code> if(func == "start"){
    this.setAttribute("func", "stop")
 }
 else{
    this.setAttribute("func", "start")
 }
</code>```

Body:
I am making start/pause button that works like this:

    var btns = document.querySelectorAll(".repairToggle");
    for (i = 0; i < btns.length; i++) {
      btns[i].addEventListener("click", manageOrderStatus);
    }
    function manageOrderStatus() {
      var func = this.getAttribute("func");
      var btn = this;
      var endpoint = "{% url 'mtn:ajax_repair_toggle' %}";
      $.ajax({
        url: endpoint,
        type: "GET",
        data: {
          'func': func,
        },
        success: function (data) {
          $(btn).html(data);
        }
      });
    }

I have start and stop buttons stored in separate html files:
work_order_start.html:

  <svg>...</svg>

work_order_pause.html:

  <svg>...</svg>

In view i render one of the buttons based on the value of func attribute:

def repair_toggle(request):
    ...
    func = request.GET.get('func')
    if func == 'stop':
        return render(request, 'mtn/work_order_start.html')
    else:
        return render(request, 'mtn/work_order_pause.html')

The problem is it only works once. After the first click it keeps executing ajax call but it sends the same old func value in request. How do i fix that?

UPDATE:

I figured out the problem. $(btn).html(data); only replaces the svg element. So the func stays the same. If i do this instead:

  <svg id='funcButton' func="stop">

How do i get func out of svg. I tried this.getElementById('funcButton').getAttribute("func"); but it doesn't work.

Body:
You are inserting the button inside the original button.

Change work_order_pause.html and work_order_start.html to only contain the svg and add in success function :

 if(func == "start"){
    this.setAttribute("func", "stop")
 }
 else{
    this.setAttribute("func", "start")
 }


问:
CakePHP validates() odd array return (1,2) value behaviour
My validation is working just fine, but seemingly randomly, the retured values are not my model set validation errors, and nothing should be triggering the error, but a "1" or "2" is returned..

Even if all field data is valid, I sometimes get a return value in my array of "1" or "2"...

Here is my validation in my controller:

```<code> if ($this->RequestHandler->isAjax()) {
        if ($this->Plan->validates()) {
            $this->Plan->set($this->data);
            $errors = $this->Plan->invalidFields();
            $this->set('errors', $errors);
        } else {
            $this->Plan->set($this->data);
        }
 }
</code>```

And here is my model validation:

```<code>        'ApplicantAge'   => array(
array('rule'=> array('maxLength', 3),
      'message' => 'Applicant Age cannot be longer than 3 digits.'),
      'last' => true,
array('rule'    => array('range', -1, 120),
      'message' => 'Applicant Age cannot exceed 120.'),
      'last' => true,
array('rule'    => 'numeric',
      'message' => 'Applicant Age must be a valid age.'),
      'last' => true,
),
    'SpouseAge'      => array(
array('allowEmpty' => true),
        'last' => true,
array('rule'    => array('maxLength', 3),
      'message' => 'Spouse Age cannot be longer than 3 digits.'),
      'last' => true,
array('rule'    => array('range', -1, 120),
      'message' => 'Spouse Age cannot exceed 120.'),
      'last' => true,
array('rule' => 'numeric',
      'message' => 'Spouse Age must be numeric.'),
      'last' => true,
),
    'NumberChildren' => array(
array('allowEmpty' => true),
      'last' => true,
array('rule'    => array('range', -1, 20),
      'message' => 'Number of Children cannot exceed 20.'),
      'last' => true,
array('rule'    => 'numeric',
      'message' => 'Number of Children must be numeric.'),
      'last' => true,
),
    'ZipCode' => array(
array('rule'    => array('postal', null, 'us'),
      'message' => 'Zip Code format must be valid. Example: 97756'),
      'last' => true,
array('rule'    => array('minLength', 5),
      'rule'    => array('maxLength', 5),
      'message' => 'Zip Code must be 5 digits.'),
      'last' => true
),
</code>```

答:
Shouldn't you be setting the data in the model before validating it?

```<code>if ($this->RequestHandler->isAjax()) {
    $this->Plan->set($this->data);
    if ($this->Plan->validates()) {
        //do something since data validates
    } else {
        $errors = $this->Plan->invalidFields();
        $this->set('errors', $errors);
    }
}
</code>```

I know that you said it was random, but are you able to find any consistency in the error? You may be able to return the values for $this->data and the Plan model itself to make sure that the information is correct there as well. It may be that the validator is getting bad data to begin with.

Body:
My validation is working just fine, but seemingly randomly, the retured values are not my model set validation errors, and nothing should be triggering the error, but a "1" or "2" is returned..

Even if all field data is valid, I sometimes get a return value in my array of "1" or "2"...

Here is my validation in my controller:

 if ($this->RequestHandler->isAjax()) {
        if ($this->Plan->validates()) {
            $this->Plan->set($this->data);
            $errors = $this->Plan->invalidFields();
            $this->set('errors', $errors);
        } else {
            $this->Plan->set($this->data);
        }
 }

And here is my model validation:

        'ApplicantAge'   => array(
array('rule'=> array('maxLength', 3),
      'message' => 'Applicant Age cannot be longer than 3 digits.'),
      'last' => true,
array('rule'    => array('range', -1, 120),
      'message' => 'Applicant Age cannot exceed 120.'),
      'last' => true,
array('rule'    => 'numeric',
      'message' => 'Applicant Age must be a valid age.'),
      'last' => true,
),
    'SpouseAge'      => array(
array('allowEmpty' => true),
        'last' => true,
array('rule'    => array('maxLength', 3),
      'message' => 'Spouse Age cannot be longer than 3 digits.'),
      'last' => true,
array('rule'    => array('range', -1, 120),
      'message' => 'Spouse Age cannot exceed 120.'),
      'last' => true,
array('rule' => 'numeric',
      'message' => 'Spouse Age must be numeric.'),
      'last' => true,
),
    'NumberChildren' => array(
array('allowEmpty' => true),
      'last' => true,
array('rule'    => array('range', -1, 20),
      'message' => 'Number of Children cannot exceed 20.'),
      'last' => true,
array('rule'    => 'numeric',
      'message' => 'Number of Children must be numeric.'),
      'last' => true,
),
    'ZipCode' => array(
array('rule'    => array('postal', null, 'us'),
      'message' => 'Zip Code format must be valid. Example: 97756'),
      'last' => true,
array('rule'    => array('minLength', 5),
      'rule'    => array('maxLength', 5),
      'message' => 'Zip Code must be 5 digits.'),
      'last' => true
),

Body:
Shouldn't you be setting the data in the model before validating it?

if ($this->RequestHandler->isAjax()) {
    $this->Plan->set($this->data);
    if ($this->Plan->validates()) {
        //do something since data validates
    } else {
        $errors = $this->Plan->invalidFields();
        $this->set('errors', $errors);
    }
}

I know that you said it was random, but are you able to find any consistency in the error? You may be able to return the values for $this->data and the Plan model itself to make sure that the information is correct there as well. It may be that the validator is getting bad data to begin with.


问:
Flutter logical decission between Video and Image in UI
I'm a little bit lost in an App I'm trying to write. I'd like to display either an image, or an Video - depending on an entry in a list.

So, if the entry in the list I'm currently displaying has a video I want to use the Chewie Player in the UI

```<code>child = Chewie(
       controller: _chewieController,
)
</code>```

if the entry in the list I'm currently displaying has an image I want to use CachedNetworkImage:

```<code>CachedNetworkImage(imageUrl: _questions[widget.questionno].getSourceUrl(),)
</code>```

as you probably noticed, I am a programming beginner. How can I solve this problem?

Right now the code I'm trying to use in the UI looks like this:

```<code>Container(
  if (_questions[widget.questionno].getVideo()=="Ja") {
    child = Chewie(
           controller: _chewieController,
    )
  } else {
    child = CachedNetworkImage(imageUrl: _questions[widget.questionno].getSourceUrl(),)
  }

),
</code>```

答:
finally got it working, it's probably not the best way, but whatever, it works and I'm super happy :D

```<code>child: Builder(
    builder: (context) {
      if (_questions[widget.questionno].getVideo()=='Ja') {
        return
        Container(child: Chewie(controller: _chewieController,));
      } else {
        return
        Container(child: CachedNetworkImage(imageUrl: _questions[widget.questionno].getSourceUrl(),));
      }
    }
  )
</code>```

additionally I also had to put the whole definition of the chewie controller (which is in initState) into an if thingie.

Body:
I'm a little bit lost in an App I'm trying to write. I'd like to display either an image, or an Video - depending on an entry in a list.

So, if the entry in the list I'm currently displaying has a video I want to use the Chewie Player in the UI

child = Chewie(
       controller: _chewieController,
)

if the entry in the list I'm currently displaying has an image I want to use CachedNetworkImage:

CachedNetworkImage(imageUrl: _questions[widget.questionno].getSourceUrl(),)

as you probably noticed, I am a programming beginner. How can I solve this problem?

Right now the code I'm trying to use in the UI looks like this:

Container(
  if (_questions[widget.questionno].getVideo()=="Ja") {
    child = Chewie(
           controller: _chewieController,
    )
  } else {
    child = CachedNetworkImage(imageUrl: _questions[widget.questionno].getSourceUrl(),)
  }

),

Body:
finally got it working, it's probably not the best way, but whatever, it works and I'm super happy :D

child: Builder(
    builder: (context) {
      if (_questions[widget.questionno].getVideo()=='Ja') {
        return
        Container(child: Chewie(controller: _chewieController,));
      } else {
        return
        Container(child: CachedNetworkImage(imageUrl: _questions[widget.questionno].getSourceUrl(),));
      }
    }
  )

additionally I also had to put the whole definition of the chewie controller (which is in initState) into an if thingie.


问:
How to speed up Spacy's nlp call?
I have to process hundreds of thousands of texts. I have found that the thing that is taking the longest in the following:

```<code>nlp = English()
ruler = EntityRuler(nlp)
patterns = [...]
ruler.add_patterns(patterns)
nlp.add_pipe(ruler)
...
#This line takes longer than I would like
doc = nlp(whole_chat)
</code>```

Granted, I have many patterns. But is there a way to speed this up? I only have the entity ruler pipe, no others.

答: Use nlp.pipe() to process multiple texts. It is faster and more efficient (documentation)

Title: How to speed up Spacy's nlp call?

Body:
I have to process hundreds of thousands of texts. I have found that the thing that is taking the longest in the following:

nlp = English()
ruler = EntityRuler(nlp)
patterns = [...]
ruler.add_patterns(patterns)
nlp.add_pipe(ruler)
...
#This line takes longer than I would like
doc = nlp(whole_chat)

Granted, I have many patterns. But is there a way to speed this up? I only have the entity ruler pipe, no others.


问:
Traefik 2 http to https redirect with tls not working
I want to set up http to https redirect in one IngressRoute, but with configuration below when I trying to access http endpoint traefik returns 404 not found error. If I remove tls section redirect works but tls not.

Can I have both working?

traefik version 2.1.0-rc2

```<code>apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: console-web
  namespace: dev
  labels:
    app: console-web
spec:
  entryPoints:
    - web
    - websecure
  routes:
    - match: Host(`console.example.com`)
      kind: Rule
      services:
        - name: console-web
          port: 8080
      middlewares:
        - name: https-redirect
  tls:
    secretName: example-com-tls
</code>```

答:
This is an old issue however this might help someone. This might not directly work as i have not tested it. For kubernetes it should work in following way first you define how the middleware works

Untested Code

```<code>apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: test-redirectscheme
spec:
  redirectScheme:
    scheme: https
</code>```

Then define the IngressRoute

```<code>apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: ingress1
  namespace: default
spec:
  entryPoints:
    - websecure
  routes:
    - match: Host(`somehost`)
      kind: Rule
      services:
        - name: console-web
          port: 8080
  tls:
    secretName: example-com-tls
</code>```

```<code>apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: ingress2
  namespace: default
spec:
  entryPoints:
    - web
  routes:
    - match: Host(`somehost`)
      middlewares:
        - name: test-redirectscheme
      kind: Rule
      services:
        - name: console-web
          port: 80
</code>```

two ingress needed as one is redirecting the trafic to other. I also suppose if you dont have two ports you can reuse the previous one as it is going to be redirected to https anyway. Let me know if it does not does not work.

after spending hours on this for docker on this 404 issue for the http endpoint i found this https://stackoverflow.com/a/62093408/2442649

Body:
I want to set up http to https redirect in one IngressRoute, but with configuration below when I trying to access http endpoint traefik returns 404 not found error. If I remove tls section redirect works but tls not.

Can I have both working?

traefik version 2.1.0-rc2

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: console-web
  namespace: dev
  labels:
    app: console-web
spec:
  entryPoints:
    - web
    - websecure
  routes:
    - match: Host(`console.example.com`)
      kind: Rule
      services:
        - name: console-web
          port: 8080
      middlewares:
        - name: https-redirect
  tls:
    secretName: example-com-tls

Body:
This is an old issue however this might help someone. This might not directly work as i have not tested it. For kubernetes it should work in following way first you define how the middleware works

Untested Code

apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: test-redirectscheme
spec:
  redirectScheme:
    scheme: https

Then define the IngressRoute

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: ingress1
  namespace: default
spec:
  entryPoints:
    - websecure
  routes:
    - match: Host(`somehost`)
      kind: Rule
      services:
        - name: console-web
          port: 8080
  tls:
    secretName: example-com-tls

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: ingress2
  namespace: default
spec:
  entryPoints:
    - web
  routes:
    - match: Host(`somehost`)
      middlewares:
        - name: test-redirectscheme
      kind: Rule
      services:
        - name: console-web
          port: 80

two ingress needed as one is redirecting the trafic to other. I also suppose if you dont have two ports you can reuse the previous one as it is going to be redirected to https anyway. Let me know if it does not does not work.

after spending hours on this for docker on this 404 issue for the http endpoint i found this https://stackoverflow.com/a/62093408/2442649


问:
Umbraco 8 - Get Children Of Node Using ContentAtXPath() Method
I've been refactoring an existing Umbraco project to use more performant querying when getting back document data as everything was previously being returned using LINQ. I have been using a combination of Umbraco's querying via XPaths and Examine.

I am currently stumped on trying to get child documents using the Umbraco.ContentAtXPath() method. What I would like to do is get child document based on a path I parse to the method. This is what I have currently:

```<code>IEnumerable<IPublishedContent> umbracoPages = Umbraco.ContentAtXPath("//* [@isDoc]/descendant::/About [@isDoc]");
</code>```

Running this returns a "Object reference not set to an instance of an object." error and unable to see exactly where I'm going wrong (new to this form of querying in Umbraco).

Ideally, I'd like to enhance the querying to also carry out sorting using the non-LINQ approach, as demonstrated here.

答: Up until Umbraco 8, content was cached in an XML file, which made XPath perfect for querying content efficiently. In v8, however, the so called "NuCache" is not file based nor XML based, so the XPath query support is only there for ... well... Old times sake, I guess? Either way it's probably not going to be super efficient and (I'd advise) not something to "aim for". That said I of course don't know what you are changing from (Linq can be a lot of things) :-/</p>

Body:
I've been refactoring an existing Umbraco project to use more performant querying when getting back document data as everything was previously being returned using LINQ. I have been using a combination of Umbraco's querying via XPaths and Examine.

I am currently stumped on trying to get child documents using the Umbraco.ContentAtXPath() method. What I would like to do is get child document based on a path I parse to the method. This is what I have currently:

IEnumerable<IPublishedContent> umbracoPages = Umbraco.ContentAtXPath("//* [@isDoc]/descendant::/About [@isDoc]");

Running this returns a "Object reference not set to an instance of an object." error and unable to see exactly where I'm going wrong (new to this form of querying in Umbraco).

Ideally, I'd like to enhance the querying to also carry out sorting using the non-LINQ approach, as demonstrated here.


问:
looking for Windows RAM-based shared memory solution in C++
I'm facing a situation where I need to pass up to several hundreds of megabytes of memory from one process to another. Right now I'm doing it via files and it's too slow.
I guess that to make it quicker, those files should be written directly to RAM and be accessible from another process. No fancy synchronization required. One process would create  shared memory objects and would fill them with data. The other process would read and remove them. However I've done a quick research and it seems like you can't share memory in RAM in Windows - the shared memory is backed by either a file or paging file. The docs of boost::interprocess confirm this. Where is the speed up then if the shared memory implementation still uses disk? Is there any C++ library that uses RAM-based shared memory?

EDIT: I made some further reading:
1. from boost::interprocess docs:
"as the operating system has to synchronize the file contents with the memory contents, memory-mapped files are not as fast as shared memory. "
2. from http://msdn.microsoft.com/en-us/library/ms810613.aspx:
"A memory-mapped file can also be mapped by more than one application simultaneously. This represents the only mechanism for two or more processes to directly share data in Windows NT."

答:
There's nothing wrong with being backed by a file -- under memory pressure, the data has to go somewhere, and your choices are:

treat the memory as sacred data that cannot be paged or dropped

Likely to only create much worse memory pressure problems, but good choice for some embedded systems where the entire runtime environment of the system can be very well controlled.

drop the memory

Obviously not suitable to all data. Cached contents? Maybe. Original photos? Probably not.

page the memory to disk

Good generic choice!

Are you seeing memory pressure when using a shared-memory tool? Add more RAM or figure out how to shrink your systems. :)