问:
How do I pass data between Activities in Android application?
I have a scenario where, after logging in through a login page, there will be a sign-out button on each activity.

On clicking sign-out, I will be passing the session id of the signed in user to sign-out. Can anyone guide me on how to keep session id available to all activities?

Any alternative to this case

答:
To access session id in all activities you have to store session id in SharedPreference.

Please see below class that I am using for managing sessions, you can also use same.

```<code>import android.content.Context;
import android.content.SharedPreferences;

public class SessionManager {

    public static String KEY_SESSIONID = "session_id";

    public static String PREF_NAME = "AppPref";

    SharedPreferences sharedPreference;
    SharedPreferences.Editor editor;
    Context mContext;

    public SessionManager(Context context) {
        this.mContext = context;

        sharedPreference = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = sharedPreference.edit();
    }

    public String getSessionId() {
        return sharedPreference.getString(KEY_SESSIONID, "");
    }

    public void setSessionID(String id) {
        editor.putString(KEY_SESSIONID, id);
        editor.commit();
        editor.apply();
    }
}

//Now you can access your session using below methods in every activities.

    SessionManager sm = new SessionManager(MainActivity.this);
sm.getSessionId();

//below line us used to set session id on after success response on login page.

    sm.setSessionID("test");
</code>```

Body:
To access session id in all activities you have to store session id in SharedPreference.

Please see below class that I am using for managing sessions, you can also use same.

import android.content.Context;
import android.content.SharedPreferences;

public class SessionManager {

    public static String KEY_SESSIONID = "session_id";

    public static String PREF_NAME = "AppPref";

    SharedPreferences sharedPreference;
    SharedPreferences.Editor editor;
    Context mContext;

    public SessionManager(Context context) {
        this.mContext = context;

        sharedPreference = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = sharedPreference.edit();
    }

    public String getSessionId() {
        return sharedPreference.getString(KEY_SESSIONID, "");
    }

    public void setSessionID(String id) {
        editor.putString(KEY_SESSIONID, id);
        editor.commit();
        editor.apply();
    }
}

//Now you can access your session using below methods in every activities.

    SessionManager sm = new SessionManager(MainActivity.this);
sm.getSessionId();

//below line us used to set session id on after success response on login page.

    sm.setSessionID("test");


来源: stackexchange

问:
Why doesn't code in (isMovingToParentViewController) run in viewDidLayoutSubviews()
I have a viewController, I'm using anchors and I want to get the frame of a button. I only want the frame when the view is pushed on so I use isMovingToParentViewController. Like this:

```<code>if isMovingToParentViewController {

    let myButtonFrame = myButton.convert(myButton.bounds, to: self.view)
}
</code>```

When I add it in viewWillAppear the code to get the button's frame runs but when I add the same code to viewDidLayoutSubviews it doesn't run.

Why is that?

Just to be clear in viewDidLayoutSubviews when I add a break point it does hit if isMovingToParentViewController but the code inside of it never gets hit.

When the view gets pushed on isMovingToParentViewController does get hit, when it pops isMovingToParentViewController doesn't get hit.

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    // anchors are set here but the frames haven't been set yet
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if isMovingToParentViewController {

        // this code runs
        let myButtonFrame = myButton.convert(myButton.bounds, to: self.view)
    }
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if isMovingToParentViewController {

        // this code NEVER runs
        let myButtonFrame = myButton.convert(myButton.bounds, to: self.view)
    }
}
</code>```

答:
The header documentation states that isMovingToParentViewController and the 3 other methods are only valid in appearance callbacks like viewWillAppear thus not in layout callbacks like viewDidLayoutSubviews.

```<code>/*
  These four methods can be used in a view controller's appearance callbacks to determine if it is being
  presented, dismissed, or added or removed as a child view controller. For example, a view controller can
  check if it is disappearing because it was dismissed or popped by asking itself in its viewWillDisappear:
  method by checking the expression ([self isBeingDismissed] || [self isMovingFromParentViewController]).
*/

#if UIKIT_DEFINE_AS_PROPERTIES
@property(nonatomic, readonly, getter=isBeingPresented) BOOL beingPresented NS_AVAILABLE_IOS(5_0);
@property(nonatomic, readonly, getter=isBeingDismissed) BOOL beingDismissed NS_AVAILABLE_IOS(5_0);

@property(nonatomic, readonly, getter=isMovingToParentViewController) BOOL movingToParentViewController NS_AVAILABLE_IOS(5_0);
@property(nonatomic, readonly, getter=isMovingFromParentViewController) BOOL movingFromParentViewController NS_AVAILABLE_IOS(5_0);
#else
- (BOOL)isBeingPresented NS_AVAILABLE_IOS(5_0);
- (BOOL)isBeingDismissed NS_AVAILABLE_IOS(5_0);

- (BOOL)isMovingToParentViewController NS_AVAILABLE_IOS(5_0);
- (BOOL)isMovingFromParentViewController NS_AVAILABLE_IOS(5_0);
#endif
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a viewController, I'm using anchors and I want to get the frame of a button. I only want the frame when the view is pushed on so I use isMovingToParentViewController. Like this:

if isMovingToParentViewController {

    let myButtonFrame = myButton.convert(myButton.bounds, to: self.view)
}

When I add it in viewWillAppear the code to get the button's frame runs but when I add the same code to viewDidLayoutSubviews it doesn't run.

Why is that?

Just to be clear in viewDidLayoutSubviews when I add a break point it does hit if isMovingToParentViewController but the code inside of it never gets hit.

When the view gets pushed on isMovingToParentViewController does get hit, when it pops isMovingToParentViewController doesn't get hit.

override func viewDidLoad() {
    super.viewDidLoad()

    // anchors are set here but the frames haven't been set yet
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if isMovingToParentViewController {

        // this code runs
        let myButtonFrame = myButton.convert(myButton.bounds, to: self.view)
    }
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if isMovingToParentViewController {

        // this code NEVER runs
        let myButtonFrame = myButton.convert(myButton.bounds, to: self.view)
    }
}

Body:
The header documentation states that isMovingToParentViewController and the 3 other methods are only valid in appearance callbacks like viewWillAppear thus not in layout callbacks like viewDidLayoutSubviews.

/*
  These four methods can be used in a view controller's appearance callbacks to determine if it is being
  presented, dismissed, or added or removed as a child view controller. For example, a view controller can
  check if it is disappearing because it was dismissed or popped by asking itself in its viewWillDisappear:
  method by checking the expression ([self isBeingDismissed] || [self isMovingFromParentViewController]).
*/

#if UIKIT_DEFINE_AS_PROPERTIES
@property(nonatomic, readonly, getter=isBeingPresented) BOOL beingPresented NS_AVAILABLE_IOS(5_0);
@property(nonatomic, readonly, getter=isBeingDismissed) BOOL beingDismissed NS_AVAILABLE_IOS(5_0);

@property(nonatomic, readonly, getter=isMovingToParentViewController) BOOL movingToParentViewController NS_AVAILABLE_IOS(5_0);
@property(nonatomic, readonly, getter=isMovingFromParentViewController) BOOL movingFromParentViewController NS_AVAILABLE_IOS(5_0);
#else
- (BOOL)isBeingPresented NS_AVAILABLE_IOS(5_0);
- (BOOL)isBeingDismissed NS_AVAILABLE_IOS(5_0);

- (BOOL)isMovingToParentViewController NS_AVAILABLE_IOS(5_0);
- (BOOL)isMovingFromParentViewController NS_AVAILABLE_IOS(5_0);
#endif


问:
How can add a Custom filter / Custom search field to Sale Order view based on a field in the partner form
I have a field card_customer in partner form. What i need is i have to add a custom filter for sale orders based on the field card_customer. When choosing this filter i need the sale orders, which have customers with card_customer field equaling True.

答:
You can create a filter in search view, by inheriting the base search view of sale order ,and create a new view.</p>

```<code><data>
    <record id="sale_order_search_inherit_receipt" model="ir.ui.view">
        <field name="name">sale.order.search.receipt</field>
        <field name="model">sale.order</field>
        <field name="inherit_id" ref="sale.sale_order_view_search_inherit_quotation"/>
        <field name="arch" type="xml">
            <xpath expr="//filter[@name='order_confirmed']" position="after"> // Adding the filter after existing filter 'Confirmed Orders'
                <separator/>
                <filter string="Card Customer" name="is_card_customer" domain="[('partner_id.card_customer','=', True)]"/>
                <separator/>
            </xpath>
        </field>
    </record>
</data>
</code>```

Body:
You can create a filter in search view, by inheriting the base search view of sale order ,and create a new view.

<data>
    <record id="sale_order_search_inherit_receipt" model="ir.ui.view">
        <field name="name">sale.order.search.receipt</field>
        <field name="model">sale.order</field>
        <field name="inherit_id" ref="sale.sale_order_view_search_inherit_quotation"/>
        <field name="arch" type="xml">
            <xpath expr="//filter[@name='order_confirmed']" position="after"> // Adding the filter after existing filter 'Confirmed Orders'
                <separator/>
                <filter string="Card Customer" name="is_card_customer" domain="[('partner_id.card_customer','=', True)]"/>
                <separator/>
            </xpath>
        </field>
    </record>
</data>


问:
Build Windows RCP Application on Unix Machine
We're trying to do an Eclipse PDE build for a RCP Application via Hudson/Jenkins. We were doing this so far successfully on a Windows machine (Hudson running on Windows Server 2003). We have decided to move our CI system to a unix machine.
When executing the same build on the unix machine our build fails with the following error:

```
!SESSION 2011-04-12 01:00:49.497 -----------------------------------------------
eclipse.buildId=unknown
java.version=1.6.0_23
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=win32, ARCH=sparc, WS=win32, NL=en_US
Framework arguments:  -application org.eclipse.ant.core.antRunner -buildfile /appl/midw/jenkins/jobs/AP_NAPF/workspace/TP/plugins/org.eclipse.pde.build_3.4.1.R34x_v20081217/scripts/build.xml main -Ddummy=true
Command-line arguments:  -ws win32 -os win32 -application org.eclipse.ant.core.antRunner -buildfile /appl/midw/jenkins/jobs/AP_NAPF/workspace/TP/plugins/org.eclipse.pde.build_3.4.1.R34x_v20081217/scripts/build.xml main -data /appl/midw/jenkins/jobs/AP_NAPF/workspace/ap_build/workspace -Ddummy=true

!ENTRY org.eclipse.osgi 4 0 2011-04-12 01:00:58.961
!MESSAGE An error occurred while automatically activating bundle org.eclipse.ui.workbench (687).
!STACK 0
org.osgi.framework.BundleException: The activator org.eclipse.ui.internal.WorkbenchPlugin for bundle org.eclipse.ui.workbench is invalid
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:146)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:980)
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:346)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:265)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:400)
    at org.eclipse.core.runtime.internal.adaptor.EclipseLazyStarter.postFindLocalClass(EclipseLazyStarter.java:111)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass(ClasspathManager.java:427)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.findLocalClass(DefaultClassLoader.java:193)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findLocalClass(BundleLoader.java:370)
    at org.eclipse.osgi.framework.internal.core.SingleSourcePackage.loadClass(SingleSourcePackage.java:33)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:443)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:399)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:87)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.defineClass(DefaultClassLoader.java:165)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.defineClass(ClasspathManager.java:554)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findClassImpl(ClasspathManager.java:524)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClassImpl(ClasspathManager.java:455)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass_LockClassLoader(ClasspathManager.java:443)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass(ClasspathManager.java:423)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.findLocalClass(DefaultClassLoader.java:193)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findLocalClass(BundleLoader.java:370)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:446)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:399)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:87)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.loadClass(BundleLoader.java:315)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:227)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:139)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:980)
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:346)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:265)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:400)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:234)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1274)
    at org.eclipse.ant.core.AntCorePreferences$WrappedClassLoader.findClass(AntCorePreferences.java:115)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.ant.internal.core.AntClassLoader.loadClassPlugins(AntClassLoader.java:69)
    at org.eclipse.ant.internal.core.AntClassLoader.findClass(AntClassLoader.java:47)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.ant.core.AntRunner.run(AntRunner.java:510)
    at org.eclipse.ant.core.AntRunner.start(AntRunner.java:600)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:193)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:386)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:549)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:504)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1236)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1212)
Caused by: java.lang.NoClassDefFoundError: org/eclipse/swt/SWTError
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
    at java.lang.Class.getConstructor0(Class.java:2699)
    at java.lang.Class.newInstance0(Class.java:326)
    at java.lang.Class.newInstance(Class.java:308)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:141)
    ... 61 more
Caused by: java.lang.ClassNotFoundException: org.eclipse.swt.SWTError
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:483)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:399)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:87)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    ... 67 more
Root exception:
java.lang.NoClassDefFoundError: org/eclipse/swt/SWTError
```

I've already tried a couple of things after moving to the new infrastructure, with no avail:

 Use a different rt.jar (one coming from a windows JRE) for the PDE build using the bootclasspath property.

Changning the -os command line argument to: solaris

Is it at all possible to do a RCP build for a Windows application on a Unix machine?
If yes, is it necessary to change any parameters when launching the PDE build?

Note: We're using pluginbuilder to setup the PDE build.

答: You need to separate the eclipse that you are using to do the build from the eclipse install that you are putting together with your build. The first one needs to be correct for your build OS. Take a look at your PDE Build invocation. There are separate parameters for Eclipse install and target platform.</p>

ContentLicense: CC BY-SA 3.0

Body:
We're trying to do an Eclipse PDE build for a RCP Application via Hudson/Jenkins. We were doing this so far successfully on a Windows machine (Hudson running on Windows Server 2003). We have decided to move our CI system to a unix machine.
When executing the same build on the unix machine our build fails with the following error:

!SESSION 2011-04-12 01:00:49.497 -----------------------------------------------
eclipse.buildId=unknown
java.version=1.6.0_23
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=win32, ARCH=sparc, WS=win32, NL=en_US
Framework arguments:  -application org.eclipse.ant.core.antRunner -buildfile /appl/midw/jenkins/jobs/AP_NAPF/workspace/TP/plugins/org.eclipse.pde.build_3.4.1.R34x_v20081217/scripts/build.xml main -Ddummy=true
Command-line arguments:  -ws win32 -os win32 -application org.eclipse.ant.core.antRunner -buildfile /appl/midw/jenkins/jobs/AP_NAPF/workspace/TP/plugins/org.eclipse.pde.build_3.4.1.R34x_v20081217/scripts/build.xml main -data /appl/midw/jenkins/jobs/AP_NAPF/workspace/ap_build/workspace -Ddummy=true

!ENTRY org.eclipse.osgi 4 0 2011-04-12 01:00:58.961
!MESSAGE An error occurred while automatically activating bundle org.eclipse.ui.workbench (687).
!STACK 0
org.osgi.framework.BundleException: The activator org.eclipse.ui.internal.WorkbenchPlugin for bundle org.eclipse.ui.workbench is invalid
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:146)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:980)
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:346)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:265)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:400)
    at org.eclipse.core.runtime.internal.adaptor.EclipseLazyStarter.postFindLocalClass(EclipseLazyStarter.java:111)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass(ClasspathManager.java:427)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.findLocalClass(DefaultClassLoader.java:193)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findLocalClass(BundleLoader.java:370)
    at org.eclipse.osgi.framework.internal.core.SingleSourcePackage.loadClass(SingleSourcePackage.java:33)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:443)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:399)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:87)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.defineClass(DefaultClassLoader.java:165)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.defineClass(ClasspathManager.java:554)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findClassImpl(ClasspathManager.java:524)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClassImpl(ClasspathManager.java:455)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass_LockClassLoader(ClasspathManager.java:443)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass(ClasspathManager.java:423)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.findLocalClass(DefaultClassLoader.java:193)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findLocalClass(BundleLoader.java:370)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:446)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:399)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:87)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.loadClass(BundleLoader.java:315)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:227)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:139)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:980)
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:346)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:265)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:400)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:234)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1274)
    at org.eclipse.ant.core.AntCorePreferences$WrappedClassLoader.findClass(AntCorePreferences.java:115)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.ant.internal.core.AntClassLoader.loadClassPlugins(AntClassLoader.java:69)
    at org.eclipse.ant.internal.core.AntClassLoader.findClass(AntClassLoader.java:47)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.ant.core.AntRunner.run(AntRunner.java:510)
    at org.eclipse.ant.core.AntRunner.start(AntRunner.java:600)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:193)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:386)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:549)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:504)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1236)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1212)
Caused by: java.lang.NoClassDefFoundError: org/eclipse/swt/SWTError
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
    at java.lang.Class.getConstructor0(Class.java:2699)
    at java.lang.Class.newInstance0(Class.java:326)
    at java.lang.Class.newInstance(Class.java:308)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:141)
    ... 61 more
Caused by: java.lang.ClassNotFoundException: org.eclipse.swt.SWTError
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:483)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:399)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:87)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    ... 67 more
Root exception:
java.lang.NoClassDefFoundError: org/eclipse/swt/SWTError

I've already tried a couple of things after moving to the new infrastructure, with no avail:

 Use a different rt.jar (one coming from a windows JRE) for the PDE build using the bootclasspath property.

Changning the -os command line argument to: solaris

Is it at all possible to do a RCP build for a Windows application on a Unix machine?
If yes, is it necessary to change any parameters when launching the PDE build?

Note: We're using pluginbuilder to setup the PDE build.


问:
How to disable future dates in bsdatePicker
I am using bsdatepicker in my angular project and i want to disable all future dates in that datePicker for the DOB selection

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'demo-datepicker-datesdisabled',
  templateUrl: './disable-dates.html'
})
export class DemoDatepickerDatesDisabledComponent {
  disabledDates = [
    new Date('2019-02-05'),
    new Date('2019-02-09')
  ];
}

<div class="row">
  <div class="col-xs-12 col-12 col-md-4 form-group">
    <input type="text"
           placeholder="Datepicker"
           class="form-control"
           bsDatepicker
           [datesDisabled]="disabledDates">
  </div>
  <div class="col-xs-12 col-12 col-md-4 form-group">
    <input type="text"
           placeholder="Daterangepicker"
           class="form-control"
           bsDaterangepicker
           [datesDisabled]="disabledDates">
  </div>
</div>
</code>```

the above code is working but i want to disable future N number of date

答:
Set [maxDate] to today.

```<code><input type="text"
           placeholder="Daterangepicker"
           class="form-control"
           bsDaterangepicker
           [datesDisabled]="disabledDates"
           [maxDate]="today"
>
</code>```

```<code>public today = new Date();
</code>```

Body:
I am using bsdatepicker in my angular project and i want to disable all future dates in that datePicker for the DOB selection

import { Component } from '@angular/core';

@Component({
  selector: 'demo-datepicker-datesdisabled',
  templateUrl: './disable-dates.html'
})
export class DemoDatepickerDatesDisabledComponent {
  disabledDates = [
    new Date('2019-02-05'),
    new Date('2019-02-09')
  ];
}

    <input type="text"
           placeholder="Datepicker"
           class="form-control"
           bsDatepicker
           [datesDisabled]="disabledDates">

    <input type="text"
           placeholder="Daterangepicker"
           class="form-control"
           bsDaterangepicker
           [datesDisabled]="disabledDates">

the above code is working but i want to disable future N number of date

Body:
Set [maxDate] to today.

<input type="text"
           placeholder="Daterangepicker"
           class="form-control"
           bsDaterangepicker
           [datesDisabled]="disabledDates"
           [maxDate]="today"
>

public today = new Date();


问:
Merge two array of objects and added a new Key & Value
I have 2 arrays based on the "Form_Name" key value to merge an array with added new key&value "isChecked".

Array One

```<code>arrayOne = [
{id: 11, Form_Name: "form name One", isChecked: true}
{id: 11, Form_Name: "form name Two", isChecked: true}];
</code>```

Array Two

```<code>arrayTwo = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05"}];
</code>```

Expected merged array

```<code>mergedArray = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}]
</code>```

I tried like below

```<code>const mergedArray = [];
for (let i = 0; i < arrayTwo.length; i++) {
  mergedArray.push({
   ...arrayTwo[i],
   ...(arrayOne.find((itmInner) => itmInner.Form_Name === arrayTwo[i].Form_Name))}
  );
}
console.log('merged array result', mergedArray);
</code>```

答:
```<code> const hasChecked = new Set(arrayOne.map(it => it.Form_Name));

 const result = arrayTwo.map(it => ({ ...it, isChecked: hasChecked.has(it.Form_Name) }));
</code>```

By creating a set of checked form names, you can easily map over the second array of objects, and add a isChecked property.

Body:
I have 2 arrays based on the "Form_Name" key value to merge an array with added new key&value "isChecked".

Array One

arrayOne = [
{id: 11, Form_Name: "form name One", isChecked: true}
{id: 11, Form_Name: "form name Two", isChecked: true}];

Array Two

arrayTwo = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05"}];

Expected merged array

mergedArray = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}]

I tried like below

const mergedArray = [];
for (let i = 0; i < arrayTwo.length; i++) {
  mergedArray.push({
   ...arrayTwo[i],
   ...(arrayOne.find((itmInner) => itmInner.Form_Name === arrayTwo[i].Form_Name))}
  );
}
console.log('merged array result', mergedArray);

Body:
 const hasChecked = new Set(arrayOne.map(it => it.Form_Name));

 const result = arrayTwo.map(it => ({ ...it, isChecked: hasChecked.has(it.Form_Name) }));

By creating a set of checked form names, you can easily map over the second array of objects, and add a isChecked property.


问:
Dapper insert DateTime value
I am using dapper CROD operation.

I am trying to enter a new row to a table with DataTime field.

I have created the following class:

```<code> //Properties
    public int Id { get; set; }
    public string Title { get; set; }
    public string Message { get; set; }
    public int UserID { get; set; }
    public DateTime CreationDate { get; set; }
    public DateTime UpdateDate { get; set; }
    public DateTime ActiveStartDate { get; set; }
    public DateTime ExpirationDate { get; set; }
</code>```

Now, the insert statement is as follow:

```<code>public static string InsertNewMessage
        => @"INSERT INTO Messages
(Title,[Message],UserID,CreationDate,UpdateDate,ActiveStartDate,
ExpirationDate)
            VALUES (N'@Title',N'@Message',@UserID,CAST('@CreationDate' as
DATETIME),CAST('@UpdateDate' as DATETIME),
CAST('@ActiveStartDate' as DATETIME)
,CAST('@ExpirationDate' as DATETIME))
SELECT CAST(SCOPE_IDENTITY() as int)";

int returnId = _db.Query<int>(QueriesRepository.InsertNewMessage,
    _message).SingleOrDefault();
</code>```

Now what am i doing wrong - i have dig the web for a solution for the following error - with no luck
I know the problem is the formatting of the DateTime object, but i saw that Dapper should support that.

```<code>Conversion failed when converting date and/or time from character string
</code>```

答: I believe it quite a late response. But anyway I faced the same issue yesterday, so I'll put my solution here. You don't need to CAST datetime directly in sql query. In my case datetime value was out of range, basically, it was 01-01-0001 00:00:00 so that caused the error. Make you sure you pass correct datetime value. Hope this helps!</p>

Title: Dapper insert DateTime value

Body:
I am using dapper CROD operation.

I am trying to enter a new row to a table with DataTime field.

I have created the following class:

 //Properties
    public int Id { get; set; }
    public string Title { get; set; }
    public string Message { get; set; }
    public int UserID { get; set; }
    public DateTime CreationDate { get; set; }
    public DateTime UpdateDate { get; set; }
    public DateTime ActiveStartDate { get; set; }
    public DateTime ExpirationDate { get; set; }

Now, the insert statement is as follow:

public static string InsertNewMessage
        => @"INSERT INTO Messages
(Title,[Message],UserID,CreationDate,UpdateDate,ActiveStartDate,
ExpirationDate)
            VALUES (N'@Title',N'@Message',@UserID,CAST('@CreationDate' as
DATETIME),CAST('@UpdateDate' as DATETIME),
CAST('@ActiveStartDate' as DATETIME)
,CAST('@ExpirationDate' as DATETIME))
SELECT CAST(SCOPE_IDENTITY() as int)";

int returnId = _db.Query<int>(QueriesRepository.InsertNewMessage,
    _message).SingleOrDefault();

Now what am i doing wrong - i have dig the web for a solution for the following error - with no luck
I know the problem is the formatting of the DateTime object, but i saw that Dapper should support that.

Conversion failed when converting date and/or time from character string


问:
Vue JS dynamic components in routes. Handling loading and error
In my vue application, I am importing the components dynamically which are then being used in the routes. So when you go to a specific route, the component chunk will be fetched dynamically.

Sometimes it takes time to fetch the components and sometimes due to network error the component couldn't be fetched. So I want to understand how can I handle the error and loading state gracefully.

答:
If you're using axios to handle your requests there is the possibility to intercept any request and handle them for example according to there status.

Here's an example which redirects to Login if response return error code is 401 (unauthorized).
One thing to mention is that you can have interceptors for responses and requests.

Documentation: https://github.com/axios/axios

```<code>axios.interceptors.response.use(response => {
    return response;
}, error => {
    if (error.response.status === 401) {
        router.push('/logout');
    }

    return error;
});
</code>```

Body:
If you're using axios to handle your requests there is the possibility to intercept any request and handle them for example according to there status.

Here's an example which redirects to Login if response return error code is 401 (unauthorized).
One thing to mention is that you can have interceptors for responses and requests.

Documentation: https://github.com/axios/axios

axios.interceptors.response.use(response => {
    return response;
}, error => {
    if (error.response.status === 401) {
        router.push('/logout');
    }

    return error;
});


问:
How to vertically center a container in Bootstrap?
I'm looking for a way to vertically center the container div inside the jumbotron and to set it in the middle of the page.

The .jumbotron has to be adapted to the full height and width of the screen. The .container div has a width of 1025px and should be in the middle of the page (vertically center).

I want this page to have the jumbotron adapted to the height and width of the screen along with the container vertically center to the jumbotron. How can I achieve it?

.jumbotron {
  height:100%;
  width:100%;
}
.container {
  width:1025px;
}
.jumbotron .container {
  max-width: 100%;
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="jumbotron">
    <div class="container text-center">
        <h1>The easiest and powerful way</h1>
        <div class="row">
            <div class="col-md-7">
                 <div class="top-bg"></div>
            </div>

            <div class="col-md-5 iPhone-features" style="margin-left:-25px;">
                <ul class="top-features">
                    <li>
                        <span><i class="fa fa-random simple_bg top-features-bg"></i></span>
                        <p><strong>Redirect</strong><br>Visitors where they converts more.</p>
                    </li>
                    <li>
                        <span><i class="fa fa-cogs simple_bg top-features-bg"></i></span>
                        <p><strong>Track</strong><br>Views, Clicks and Conversions.</p>
                    </li>
                    <li>
                        <span><i class="fa fa-check simple_bg top-features-bg"></i></span>
                        <p><strong>Check</strong><br>Constantly the status of your links.</p>
                    </li>
                    <li>
                        <span><i class="fa fa-users simple_bg top-features-bg"></i></span>
                        <p><strong>Collaborate</strong><br>With Customers, Partners and Co-Workers.</p>
                    </li>
                        GET STARTED
                        <h6 class="get-Started-sub-btn">FREE VERSION AVAILABLE!</h6>
                </ul>
            </div>
        </div>
    </div>
</div></code>```

答:
for bootstrap4 vertical center of few items

d-flex for flex rules

flex-column for vertical direction on items

justify-content-center for centering

style='height: 300px;' must have for set points where center be calc or use h-100 class

then for horizontal center div d-flex justify-content-center
and some container

so we have hierarhy of 3 tag: div-column -> div-row -> div-container

```<code>     <div class="d-flex flex-column justify-content-center bg-secondary"
        style="height: 300px;">
        <div class="d-flex justify-content-center">
           <div class=bg-primary>Flex item</div>
        </div>
        <div class="d-flex justify-content-center">
           <div class=bg-primary>Flex item</div>
        </div>
      </div>
</code>```

Body:
I'm looking for a way to vertically center the container div inside the jumbotron and to set it in the middle of the page.

The .jumbotron has to be adapted to the full height and width of the screen. The .container div has a width of 1025px and should be in the middle of the page (vertically center).

I want this page to have the jumbotron adapted to the height and width of the screen along with the container vertically center to the jumbotron. How can I achieve it?

.jumbotron {
  height:100%;
  width:100%;
}
.container {
  width:1025px;
}
.jumbotron .container {
  max-width: 100%;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

The easiest and powerful way

Redirect
Visitors where they converts more.

Track
Views, Clicks and Conversions.

Check
Constantly the status of your links.

Collaborate
With Customers, Partners and Co-Workers.

                        GET STARTED

FREE VERSION AVAILABLE!

Body:
for bootstrap4 vertical center of few items

d-flex for flex rules

flex-column for vertical direction on items

justify-content-center for centering

style='height: 300px;' must have for set points where center be calc or use h-100 class

then for horizontal center div d-flex justify-content-center
and some container

so we have hierarhy of 3 tag: div-column -> div-row -> div-container

     <div class="d-flex flex-column justify-content-center bg-secondary"
        style="height: 300px;">
        <div class="d-flex justify-content-center">
           <div class=bg-primary>Flex item</div>
        </div>
        <div class="d-flex justify-content-center">
           <div class=bg-primary>Flex item</div>
        </div>
      </div>


问:
Python: Reverse Order Of Words
In my program I pull a string from another file and assign it to a variable (see below)

```<code>ex1 = 'John Doe'
</code>```

How would I convert the above string to a different format as seen below? (Note the space after the comma)

```<code>ex2 = 'Doe, John'
</code>```

Sorry if this question seems trivial but I haven't had much experience with lists and most solutions incorporate lists (so I don't fully understand them).

Any help would be greatly appreciated!

答:
Using regex:</p>

```<code>import re
ex2 = re.sub('(\w+)\s(\w+)', r'\2, \1', ex1)

>>> ex2
'Doe, John'
</code>```

Title: Python: Reverse Order Of Words

Body:
In my program I pull a string from another file and assign it to a variable (see below)

ex1 = 'John Doe'

How would I convert the above string to a different format as seen below? (Note the space after the comma)

ex2 = 'Doe, John'

Sorry if this question seems trivial but I haven't had much experience with lists and most solutions incorporate lists (so I don't fully understand them).

Any help would be greatly appreciated!

Body:
Using regex:

import re
ex2 = re.sub('(\w+)\s(\w+)', r'\2, \1', ex1)

>>> ex2
'Doe, John'


问:
Combine 2 collections (keep the similar ones)
I've several collections, I want to keep only the elements that are present in each collection.

I went through the available methods, but I didn't find anything that would match.

```<code>$candidatesByConsultant = Consultant::find(request('consultant_id'))->candidates;
$candidatesByCreation = Candidate::whereBetween('created_at',[Carbon::parse(request('meeting_since')), Carbon::parse(request('meeting_to'))])->get();
</code>```

Do you have any idea? :)

答:
In order to have values that only present in both collection you must use intersect method:

```<code>$result = $candidatesByConsultant->intersect($candidatesByCreation);
</code>```

The intersect method intersects the values of both collections. You can read it in Laravel's official documentation.

And in order to get have results that are not present in both collection you must use diff method:

```<code>$result = $candidatesByConsultant->diff($candidatesByCreation);
</code>```

The diff method finds differences between collections. You can read it in Laravel's official documentation.

Body:
I've several collections, I want to keep only the elements that are present in each collection.

I went through the available methods, but I didn't find anything that would match.

$candidatesByConsultant = Consultant::find(request('consultant_id'))->candidates;
$candidatesByCreation = Candidate::whereBetween('created_at',[Carbon::parse(request('meeting_since')), Carbon::parse(request('meeting_to'))])->get();

Do you have any idea? :)

Body:
In order to have values that only present in both collection you must use intersect method:

$result = $candidatesByConsultant->intersect($candidatesByCreation);

The intersect method intersects the values of both collections. You can read it in Laravel's official documentation.

And in order to get have results that are not present in both collection you must use diff method:

$result = $candidatesByConsultant->diff($candidatesByCreation);

The diff method finds differences between collections. You can read it in Laravel's official documentation.


问:
Why doesn't the emulator behave correctly on orientation change?
As far as I know, by default, when device is rotated, the current activity is destroyed and recreated. I'm rotating the emulator using LeftCTRL+F12 but it's not destroyed. I have logs in OnDestroy, OnCreate and OnStart and OnResume, but none of those fire up when I rotate the device.

Before:

After:

AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.geo_quiz"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.geo_quiz.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答:
I think I know the answer. I have the same problem using the emulator for Pixel 2, API level 28, on Android Studio 3.4.1 (the latest as of writing this).

How I fixed this was by dragging the Quick Settings drop-down menu on the emulator (click and drag from the top right corner of the emulator's screen), and ensuring that auto-rotation was enabled.

When I checked, it wasn't, so I enabled it. After enabling it, the emulator worked normally :).

Hope this helped!

Body:
As far as I know, by default, when device is rotated, the current activity is destroyed and recreated. I'm rotating the emulator using LeftCTRL+F12 but it's not destroyed. I have logs in OnDestroy, OnCreate and OnStart and OnResume, but none of those fire up when I rotate the device.

Before:

After:

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.geo_quiz"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.geo_quiz.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


问:
Regex to extract hashtags with two dot-separated parts
I'm trying to create a regular expression in order to extract some text from strings. I want to extract text from urls or normal text messages e.g.:

```<code>endpoint/?userId=#someuser.id
</code>```

OR

```<code>Hi #someuser.name, how are you?
</code>```

And from both I want to extract exactly #someuser.name from message and #someuser.id from url. There might be be many of those string to extract from the url and messages.

My regular expression currently looks like this:

```<code>(#[^\.]+?\.)([^\W]\w+\b)
</code>```

It works fine, except one for one case and I don't know how to do it - e.g.:

Those strings SHOULD NOT be matched: # .id, #.id. There must be at least one character between # and .. One or more spaces between those characters should not be matched.

How can I do it using my current regex?

答:
You may use

```<code>String regex = "#[^.#]*[^.#\\s][^#.]*\\.\\w+";
</code>```

See the regex demo and its graph:

Details

# - a # symbol

[^.#]* - zero or more chars other than . and #

[^.#\\s] - any char but ., # and whitespace

[^#.]* - - zero or more chars other than . and #

\. - a dot

\w+ - 1+ word chars (letters, digits or _).

Java demo:

```<code>String s = "# #.id\nendpoint/?userId=#someuser.id\nHi #someuser.name, how are you?";
String regex = "#[^.#]*[^.#\\s][^#.]*\\.\\w+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    System.out.println(matcher.group(0));
}
</code>```

Output:

```<code>#someuser.id
#someuser.name
</code>```

Body:
I'm trying to create a regular expression in order to extract some text from strings. I want to extract text from urls or normal text messages e.g.:

endpoint/?userId=#someuser.id

OR

Hi #someuser.name, how are you?

And from both I want to extract exactly #someuser.name from message and #someuser.id from url. There might be be many of those string to extract from the url and messages.

My regular expression currently looks like this:

(#[^\.]+?\.)([^\W]\w+\b)

It works fine, except one for one case and I don't know how to do it - e.g.:

Those strings SHOULD NOT be matched: # .id, #.id. There must be at least one character between # and .. One or more spaces between those characters should not be matched.

How can I do it using my current regex?

Body:
You may use

String regex = "#[^.#]*[^.#\\s][^#.]*\\.\\w+";

See the regex demo and its graph:

Details

# - a # symbol

[^.#]* - zero or more chars other than . and #

[^.#\\s] - any char but ., # and whitespace

[^#.]* - - zero or more chars other than . and #

\. - a dot

\w+ - 1+ word chars (letters, digits or _).

Java demo:

String s = "# #.id\nendpoint/?userId=#someuser.id\nHi #someuser.name, how are you?";
String regex = "#[^.#]*[^.#\\s][^#.]*\\.\\w+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    System.out.println(matcher.group(0));
}

Output:

#someuser.id
#someuser.name


问:
How to submit reactive form from outside the form [submitting on click save or update buttons outside the form]
I am working on reactive forms in angular 7, and I need to call submit from a button outside the form.

```<code><input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit()" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit()" >
</form>
</code>```

This function is working fine.

Now, I need to submit the form from multiple buttons i.e.

if user click Save button, the form should be submitted and save

if user click Update button, the form should be submitted and update

For this purpose, I want to pass a flag 'Save' or 'Update' from

```<code><input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit('Save')" />

<input type="button" form="ngForm"  class='Button' value="Update" (click)="detailForm.ngSubmit.emit('Update')" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit(flag)" >
    </form>
</code>```

But I could not submit the form with the 'Save' / 'Update' flag. How could I pass a parameter from Save and Update buttons outside the form to my submit function.

Any fruitful suggestion would be highly appreciated.

答:
Use type="submit" instead type="button", or if you want to use outside the form.

```<code><input type="submit" form="ngForm" (click)="onSubmit(gDetailForm.value, 'save')"/>
<input type="submit" form="ngForm" (click)="onSubmit(gDetailForm.value, 'update')"/>
<form id="myForm" [formGroup]="gDetailForm">
    <input type="text" name="name"/>
</form>
</code>```

Body:
I am working on reactive forms in angular 7, and I need to call submit from a button outside the form.

<input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit()" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit()" >
</form>

This function is working fine.

Now, I need to submit the form from multiple buttons i.e.

if user click Save button, the form should be submitted and save

if user click Update button, the form should be submitted and update

For this purpose, I want to pass a flag 'Save' or 'Update' from

<input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit('Save')" />

<input type="button" form="ngForm"  class='Button' value="Update" (click)="detailForm.ngSubmit.emit('Update')" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit(flag)" >
    </form>

But I could not submit the form with the 'Save' / 'Update' flag. How could I pass a parameter from Save and Update buttons outside the form to my submit function.

Any fruitful suggestion would be highly appreciated.

Body:
Use type="submit" instead type="button", or if you want to use outside the form.

<input type="submit" form="ngForm" (click)="onSubmit(gDetailForm.value, 'save')"/>
<input type="submit" form="ngForm" (click)="onSubmit(gDetailForm.value, 'update')"/>
<form id="myForm" [formGroup]="gDetailForm">
    <input type="text" name="name"/>
</form>


问:
Scala list with same adjacent values
I have this list:

```<code>List("Black","Black","Green","White")
</code>```

How can I check if a list has two adjacent values which are the same? Like so:

```<code>List("Black","Black","Green","White") true

List("Black","Yellow","Green","White") false

List("Black","Yellow","Black","Yellow") false
</code>```

答:
```<code>val listA = List("Black","Black","Green","White")

listA.sliding(2).map{case a::b::_ if a == b => true else false}.contains(true)
</code>```

Title: Scala list with same adjacent values

Body:
I have this list:

List("Black","Black","Green","White")

How can I check if a list has two adjacent values which are the same? Like so:

List("Black","Black","Green","White") true

List("Black","Yellow","Green","White") false

List("Black","Yellow","Black","Yellow") false


问:
Cannot connect to ExtProc In Oracle 11g
We have two Oracle instances on one server (both 11g) that are using the same listener.  I am having an issue with connecting to the extproc:

TNSNAMES.ORA

```<code>EXTPROC_CONNECTION_DATA.NATIONAL.SERVER.COM =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC11G))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = PLSExtProc11g)
    )
  )
</code>```

LISTENER.ORA

```<code>(DESCRIPTION_LIST=
    (DESCRIPTION =
       (ADDRESS_LIST=
         (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
         (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC11G))
     )
    )
  )

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = PLSExtProc11g)
      (ORACLE_HOME = /home/app/oracle/product/11.2.0/dbhome_1)
      (ENVS = "EXTPROC_DLLS=ANY")
      (PROGRAM = extproc)
    )
</code>```

When I use TNSPING to check the connection, I get the following:

/home/app/oracle/product/11.2.0/dbhome_1/network/admin/sqlnet.ora

$tnsping EXTPROC_CONNECTION_DATA

TNS Ping Utility for Linux: Version 11.2.0.1.0 - Production on 03-NOV-2011 14:03:41

Copyright (c) 1997, 2009, Oracle.  All rights reserved.

Used parameter files:

Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC11G))) (CONNECT_DATA = (SERVICE_NAME = PLSExtProc11g)))
TNS-12541: TNS:no listener

I am able successfully tnsping both of the databases but not the EXTPROC_CONNECTION_DATA.

答:
change the SID_NAME with the correct value, It may solve the issue.

example:
 (SID_NAME = PLSExtProc11g)
   to
 (SID_NAME = ORCL)

Title: Cannot connect to ExtProc In Oracle 11g

Body:
We have two Oracle instances on one server (both 11g) that are using the same listener.  I am having an issue with connecting to the extproc:

TNSNAMES.ORA

EXTPROC_CONNECTION_DATA.NATIONAL.SERVER.COM =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC11G))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = PLSExtProc11g)
    )
  )

LISTENER.ORA

(DESCRIPTION_LIST=
    (DESCRIPTION =
       (ADDRESS_LIST=
         (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
         (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC11G))
     )
    )
  )

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = PLSExtProc11g)
      (ORACLE_HOME = /home/app/oracle/product/11.2.0/dbhome_1)
      (ENVS = "EXTPROC_DLLS=ANY")
      (PROGRAM = extproc)
    )

When I use TNSPING to check the connection, I get the following:

/home/app/oracle/product/11.2.0/dbhome_1/network/admin/sqlnet.ora

$tnsping EXTPROC_CONNECTION_DATA

TNS Ping Utility for Linux: Version 11.2.0.1.0 - Production on 03-NOV-2011 14:03:41

Copyright (c) 1997, 2009, Oracle.  All rights reserved.

Used parameter files:

Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC11G))) (CONNECT_DATA = (SERVICE_NAME = PLSExtProc11g)))
TNS-12541: TNS:no listener

I am able successfully tnsping both of the databases but not the EXTPROC_CONNECTION_DATA.


问:
How to execute bind variable based sql in DB2 DB2 ZOS
I am trying to execute one SQL, which is made up of bind variables. It's working  fine with ORACLE DB but not with DB2

Here is the sample SQL: (UPPER/UCASE it can be anything)

```<code>SELECT Col1 FROM tab1 WHERE Col1 = 'abc' AND (UPPER(Col1) LIKE (UPPER(:1) || '%' ESCAPE '\') ORDER BY 1
</code>```

Error is as follows:

```<code>db2 => SELECT Col1 FROM tab1 WHERE Col1 = 'abc' AND (UPPER(Col1) LIKE (UPPE
R(:1) || '%' ESCAPE '\') ORDER BY 1
SQL0104N  An unexpected token "1" was found following "".  Expected tokens mayinclude:  "<IDENTIFIER>".  SQLSTATE=42601
</code>```

I am not sure, what is the problem here. Its not prompting for input bind value.
In Oracle DB, everything is working fine.

In DB2, I used command line to execute the query. For Oracle, I used ORACLE SQL developer.

答:
You are using the interactive CLP for Db2 on Microsoft Windows, while connected to a remote Db2-for-Z/OS database.

This CLP interface does not have any functionality for prompting for host-variable values in dynamic-SQL. That's why you get the error message.

You can either use an alternative interface (for example IBM Data Studio, or many other java based database front-end tools) , or continue to use Oracle-SQL-Developer to access Db2 for Z/OS.

You can configure 'Oracle SQL Developer' to use the Db2 type-4 jdbc driver (db2jcc4.jar) along with the licence file for Db2 for Z/OS ('db2jcc_license_cisuz.jar').  You will need to get the Db2 licence file from your mainframe DBA or from Passport-Advantage, or alternatively connect via a Db2-connect gateway server (in which case you won't need a separate licence file on the workstation running Oracle-SQL-Developer).

However, the degree to which each such tool understands Db2-for-Z/OS varies, so if you get issues that you cannot easily workaround, then use instead the free IBM Data Studio which works with Db2-for-Z/OS,  and Db2-for-i,  and Db2 for LUW.

Configuring SQL-Developer to access Db2 is documented widely, including on this website, and also by Oracle.  So do your research, this is not programming but configuration. Stackoverflow is for programming questions.

Body:
I am trying to execute one SQL, which is made up of bind variables. It's working  fine with ORACLE DB but not with DB2

Here is the sample SQL: (UPPER/UCASE it can be anything)

SELECT Col1 FROM tab1 WHERE Col1 = 'abc' AND (UPPER(Col1) LIKE (UPPER(:1) || '%' ESCAPE '\') ORDER BY 1

Error is as follows:

db2 => SELECT Col1 FROM tab1 WHERE Col1 = 'abc' AND (UPPER(Col1) LIKE (UPPE
R(:1) || '%' ESCAPE '\') ORDER BY 1
SQL0104N  An unexpected token "1" was found following "".  Expected tokens mayinclude:  "<IDENTIFIER>".  SQLSTATE=42601

I am not sure, what is the problem here. Its not prompting for input bind value.
In Oracle DB, everything is working fine.

In DB2, I used command line to execute the query. For Oracle, I used ORACLE SQL developer.


问:
Difference between ~~ and Math.floor()
As I see in examples, the functionality if ~~ and Math.floor is the same. Both of them round a number downward (Am I think correct?)

Also I should mention that according to this test ~~ is faster than Math.floor: jsperf.com/math-round-vs

So I want to know, is there any difference between ~~ and Math.floor?

答:
In addition to David answer:

One of the things that I have noticed about bitwise operations in JavaScript is that it can be convenient for smaller values, but doesn’t always work for larger values. The reason this is the case is that bitwise operators will only work fully for operands which can be fully expressed in a 32-bit signed format. In other words, using bitwise operations will only produce numbers that are in the range of -2147483648 (-231) to 2147483647 (231 – 1). In addition, if one of the operands used is outside of that range, the last 32 bits of the number will be used instead of the specified number.

http://cwestblog.com/2011/07/27/limits-on-bitwise-operators-in-javascript/

This limitation can easily be found when working with Date, assume you are rounding a milliseconds value:

```<code>Math.floor(1559125440000.6) // 1559125440000
~~1559125440000.6           // 52311552
</code>```

Title: Difference between ~~ and Math.floor()

Body:
In addition to David answer:

One of the things that I have noticed about bitwise operations in JavaScript is that it can be convenient for smaller values, but doesn’t always work for larger values. The reason this is the case is that bitwise operators will only work fully for operands which can be fully expressed in a 32-bit signed format. In other words, using bitwise operations will only produce numbers that are in the range of -2147483648 (-231) to 2147483647 (231 – 1). In addition, if one of the operands used is outside of that range, the last 32 bits of the number will be used instead of the specified number.

http://cwestblog.com/2011/07/27/limits-on-bitwise-operators-in-javascript/

This limitation can easily be found when working with Date, assume you are rounding a milliseconds value:

Math.floor(1559125440000.6) // 1559125440000
~~1559125440000.6           // 52311552


问:
IFormFile property in .NET Core ViewModel causing stalled AJAX Request
I am giving users the ability to add images for a retail product inside of an Add/Edit Product modal.

Modal ViewModel:

```<code>public class ProductModalViewModel
{
    public ProductModalViewModel()
    {
        Product = new ProductDTO();
        Images = new List<ProductImageViewModel>();
    }

    public ProductDTO Product { get; set; }

    public List<ProductImageViewModel> Images { get; set; }
}
</code>```

Each product image is contained in its own ViewModel, as below:

Image ViewModel:

```<code>public class ProductImageViewModel
{
    public ProductImageViewModel()
    {
        ProductImage = new ProductImageDTO();
    }

    public ProductImageDTO ProductImage { get; set; }

    [DataType(DataType.Upload)]
    public IFormFile ImageFile { get; set; }
}
</code>```

Upon submitting the form to save the product (and any added images) my request gets hung up and displays "pending" in Chrome Development Tools. My controller action is never reached.

This only happens when I include the ProductImage Fields/ViewModel/Logic in my project. This was not occurring before adding that functionality to the modal, and works fine if I remove all of the ProductImage Fields/ViewModel/Logic then submit again.

Is there something inherently wrong with including my IFormFile inside of a nested ViewModel? Or could this be something else. The rest of my relevent code is below.

Controller:

```<code>[HttpPost]
public IActionResult SaveProduct([FromForm]ProductModalViewModel model)
{
    //save code
}
</code>```

View (Modal):

```<code><form id="formSaveProduct" onsubmit="SaveProduct(event)" enctype="multipart/form-data">
//Other product fields removed for brevity
    <div class="row">
        <div class="col-md-12">
            <ul class="list-group" id="image-list-group">
                @for (int i = 0; i < Model.Images.Count(); i++)
                {
                    <partial name="_ImageListItem" for="Images[i]" />
                }
            </ul>
        </div>
    </div>
</form>
</code>```

PartialView (ProductImage):

```<code><li class="list-group-item my-1">
    <input type="hidden" asp-for="ProductImage.Id" class="image-id" />
    <input type="hidden" asp-for="ProductImage.ProductId" class="image-productid" />

    <div class="row">
        <div class="col-3">
            <input type="text" readonly asp-for="ProductImage.Order" class="image-order" />
        </div>
        <div class="col-6">
            <img src="..\@Model.ProductImage.Path" class="image-display" />
        </div>
    </div>
</li>
</code>```

Script:

```<code>function SaveProduct(e) {

    e.preventDefault();  // prevent standard form submission

    $.ajax({
        url: "@Url.Action("SaveProduct", "ProductManagement", new { Area = "Admin" })",
        method: "post",
        data: new FormData($('#formSaveProduct')[0]),
        contentType: false,
        processData: false,
        cache: false,
        success: function (result) {
            //removed for brevity
        }
    });
}
</code>```

答:
This question was answered wonderfully in my conceptual question in the following post:

IFormFile as a Nested ViewModel Property

Body:
I am giving users the ability to add images for a retail product inside of an Add/Edit Product modal.

Modal ViewModel:

public class ProductModalViewModel
{
    public ProductModalViewModel()
    {
        Product = new ProductDTO();
        Images = new List<ProductImageViewModel>();
    }

    public ProductDTO Product { get; set; }

    public List<ProductImageViewModel> Images { get; set; }
}

Each product image is contained in its own ViewModel, as below:

Image ViewModel:

public class ProductImageViewModel
{
    public ProductImageViewModel()
    {
        ProductImage = new ProductImageDTO();
    }

    public ProductImageDTO ProductImage { get; set; }

    [DataType(DataType.Upload)]
    public IFormFile ImageFile { get; set; }
}

Upon submitting the form to save the product (and any added images) my request gets hung up and displays "pending" in Chrome Development Tools. My controller action is never reached.

This only happens when I include the ProductImage Fields/ViewModel/Logic in my project. This was not occurring before adding that functionality to the modal, and works fine if I remove all of the ProductImage Fields/ViewModel/Logic then submit again.

Is there something inherently wrong with including my IFormFile inside of a nested ViewModel? Or could this be something else. The rest of my relevent code is below.

Controller:

[HttpPost]
public IActionResult SaveProduct([FromForm]ProductModalViewModel model)
{
    //save code
}

View (Modal):

<form id="formSaveProduct" onsubmit="SaveProduct(event)" enctype="multipart/form-data">
//Other product fields removed for brevity

                @for (int i = 0; i < Model.Images.Count(); i++)
                {
                    <partial name="_ImageListItem" for="Images[i]" />
                }

</form>

PartialView (ProductImage):

    <input type="hidden" asp-for="ProductImage.Id" class="image-id" />
    <input type="hidden" asp-for="ProductImage.ProductId" class="image-productid" />

            <input type="text" readonly asp-for="ProductImage.Order" class="image-order" />

Script:

function SaveProduct(e) {

    e.preventDefault();  // prevent standard form submission

    $.ajax({
        url: "@Url.Action("SaveProduct", "ProductManagement", new { Area = "Admin" })",
        method: "post",
        data: new FormData($('#formSaveProduct')[0]),
        contentType: false,
        processData: false,
        cache: false,
        success: function (result) {
            //removed for brevity
        }
    });
}


答:
The intersect method may be suitable : https://laravel.com/docs/5.8/collections#method-intersect

Example taken from the documentation:

$collection = collect(['Desk', 'Sofa', 'Chair']);

$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);

$intersect->all();

// [0 => 'Desk', 2 => 'Chair']
```

<p>However, especially if you are trying to intersect multiple collections of <strong>Eloquent models</strong>, it may not work since the equality between two models is defined by the Model::is() method. Check
https://laravel.com/docs/5.8/eloquent#comparing-models for more information about comparing two Eloquent models. </p>

<p>To handle this, I would do the following, assuming the primary key of your models is <code>id</code>:</p>

<pre class="lang-php prettyprint-override"><code>$candidatesByConsultant = Consultant::find(request('consultant_id'))->candidates;
$candidatesByCreation = Candidate::whereBetween('created_at',[Carbon::parse(request('meeting_since')), Carbon::parse(request('meeting_to'))])->get();

$candidates = $candidatesByConsultant->merge($candidatesByCreation)->unique("id");
</code>```

You may check the merge() and unique() documentations.

Title: Combine 2 collections (keep the similar ones)

Body:
The intersect method may be suitable : https://laravel.com/docs/5.8/collections#method-intersect

Example taken from the documentation:

$collection = collect(['Desk', 'Sofa', 'Chair']);

$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);

$intersect->all();

// [0 => 'Desk', 2 => 'Chair']

However, especially if you are trying to intersect multiple collections of Eloquent models, it may not work since the equality between two models is defined by the Model::is() method. Check
https://laravel.com/docs/5.8/eloquent#comparing-models for more information about comparing two Eloquent models.

To handle this, I would do the following, assuming the primary key of your models is id:

$candidatesByConsultant = Consultant::find(request('consultant_id'))->candidates;
$candidatesByCreation = Candidate::whereBetween('created_at',[Carbon::parse(request('meeting_since')), Carbon::parse(request('meeting_to'))])->get();

$candidates = $candidatesByConsultant->merge($candidatesByCreation)->unique("id");

You may check the merge() and unique() documentations.


问:
android google maps zoom to a specific area by lat and long
I know how to zoom google maps by level
but what I want is to display a specific area on google maps

I mean I want just to show the area around Lat = 24.453 & Long = 35.547 & Radius = 200km

How to achieve that?

答:
Thanks to @Ken and How does this Google Maps zoom level calculation work? I got a solution.

```<code>private fun getZoomLevel(radius: Double): Float {
    return if (radius > 0) {
        // val scale = radius / 300 // This constant depends on screen size.
        // Calculate scale depending on screen dpi.
        val scale = radius * resources.displayMetrics.densityDpi / 100000
        (16 - Math.log(scale) / Math.log(2.0)).toFloat()
    } else 16f
}
</code>```

I don't know how it depends on screen size (dpi, width, height), so this is another variant:

```<code>private fun getZoomLevel(radius: Double): Float {
    return if (radius > 0) {
        val metrics = resources.displayMetrics
        val size = if (metrics.widthPixels < metrics.heightPixels) metrics.widthPixels
        else metrics.heightPixels
        val scale = radius * size / 300000
        (16 - Math.log(scale) / Math.log(2.0)).toFloat()
    } else 16f
}
</code>```

Usage:

```<code>private fun zoomMapToRadius(latitude: Double, longitude: Double, radius: Double) {
    val position = LatLng(latitude, longitude)
    val center = CameraUpdateFactory.newLatLngZoom(position, getZoomLevel(radius))
    googleMap?.animateCamera(center)
}
</code>```

or

```<code>private fun zoomMapToRadius(/*latitude: Double, longitude: Double,*/ radius: Double) {
    //val position = LatLng(latitude, longitude)
    //val center = CameraUpdateFactory.newLatLng(position)
    //googleMap?.moveCamera(center)
    val zoom = CameraUpdateFactory.zoomTo(getZoomLevel(radius))
    googleMap?.animateCamera(zoom)
}
</code>```

UPDATE

A more accurate solution is here: https://stackoverflow.com/a/56464293/2914140.

Body:
Thanks to @Ken and How does this Google Maps zoom level calculation work? I got a solution.

private fun getZoomLevel(radius: Double): Float {
    return if (radius > 0) {
        // val scale = radius / 300 // This constant depends on screen size.
        // Calculate scale depending on screen dpi.
        val scale = radius * resources.displayMetrics.densityDpi / 100000
        (16 - Math.log(scale) / Math.log(2.0)).toFloat()
    } else 16f
}

I don't know how it depends on screen size (dpi, width, height), so this is another variant:

private fun getZoomLevel(radius: Double): Float {
    return if (radius > 0) {
        val metrics = resources.displayMetrics
        val size = if (metrics.widthPixels < metrics.heightPixels) metrics.widthPixels
        else metrics.heightPixels
        val scale = radius * size / 300000
        (16 - Math.log(scale) / Math.log(2.0)).toFloat()
    } else 16f
}

Usage:

private fun zoomMapToRadius(latitude: Double, longitude: Double, radius: Double) {
    val position = LatLng(latitude, longitude)
    val center = CameraUpdateFactory.newLatLngZoom(position, getZoomLevel(radius))
    googleMap?.animateCamera(center)
}

or

private fun zoomMapToRadius(/*latitude: Double, longitude: Double,*/ radius: Double) {
    //val position = LatLng(latitude, longitude)
    //val center = CameraUpdateFactory.newLatLng(position)
    //googleMap?.moveCamera(center)
    val zoom = CameraUpdateFactory.zoomTo(getZoomLevel(radius))
    googleMap?.animateCamera(zoom)
}

UPDATE

A more accurate solution is here: https://stackoverflow.com/a/56464293/2914140.


问:
How to display a page only, if certain parameters are provided in the URL?
I want to create a page in Spring, which has the url

http://myapp.com/sign-in?email=myemail@provider.com&pw=password

password is a one-time password that the user receives via e-mail every time they want to sign in.

Whenever the user visits this page, I want two things to happen:

Check whether or not the provided credentials are correct.

If they are, display the HTML content of the page.

I've done the first part:

```<code>    @Autowired
    private var userRepository: UserRepository? = null

    @GetMapping
    fun signIn(@RequestParam email:String, @RequestParam(name="pw") password:String): RedirectView {
        // Is the password correct?

        // TODO: Read password hash of the user
        val existingUser: Optional<UserInfo>? = userRepository?.findById(email)
        if (existingUser == null) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        if (!existingUser.isPresent) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        val hashInDb = existingUser.get().passwordHash
        val hashInParam = PasswordHashCalculator.calculateHash(password)
        if (!hashInDb.equals(hashInParam)) {
            return redirectToErrorPage("Invalid user name and/or password")
        }

        // TODO: Display the main page
        return null
    }
</code>```

How do I need to change the code in order to display the main page (HTML file in src/main/resources/static), but only if the authentication checks are passed?

Update 1: Using return ClassPathResource("main.html") as recommended here did not help.

答:
You shouldn't really do your security this way. It's is not good practice to send your password in clear text over http.

There is examples here of basic authentication with spring security.

https://www.baeldung.com/spring-security-basic-authentication

https://www.baeldung.com/securing-a-restful-web-service-with-spring-security

What you can do then is, if you follow this tutorial, is assign an in memory user for starters. Then you can Base64Encode your authentication details to the user. Then for each user you can send the authentication details and no one can snoop the username and password as they pass along the wire and your request is dealt with before ever reaching your controller. This way, you can decouple your business logic from your authentication.

That's a start at least. Hope this helps.

Body:
I want to create a page in Spring, which has the url

http://myapp.com/sign-in?email=myemail@provider.com&pw=password

password is a one-time password that the user receives via e-mail every time they want to sign in.

Whenever the user visits this page, I want two things to happen:

Check whether or not the provided credentials are correct.

If they are, display the HTML content of the page.

I've done the first part:

    @Autowired
    private var userRepository: UserRepository? = null

    @GetMapping
    fun signIn(@RequestParam email:String, @RequestParam(name="pw") password:String): RedirectView {
        // Is the password correct?

        // TODO: Read password hash of the user
        val existingUser: Optional<UserInfo>? = userRepository?.findById(email)
        if (existingUser == null) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        if (!existingUser.isPresent) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        val hashInDb = existingUser.get().passwordHash
        val hashInParam = PasswordHashCalculator.calculateHash(password)
        if (!hashInDb.equals(hashInParam)) {
            return redirectToErrorPage("Invalid user name and/or password")
        }

        // TODO: Display the main page
        return null
    }

How do I need to change the code in order to display the main page (HTML file in src/main/resources/static), but only if the authentication checks are passed?

Update 1: Using return ClassPathResource("main.html") as recommended here did not help.


问:
How to describe a topic using kafka client in Python
I'm beginner to kafka client in python, i need some help to describe the topics using the client.

I was able to list all my kafka topics using the following code:-

```<code>consumer = kafka.KafkaConsumer(group_id='test', bootstrap_servers=['kafka1'])
topicList = consumer.topics()
</code>```

答:
After referring multiple articles and code samples, I was able to do this through describe_configs using confluent_kafka.

Link 1 [Confluent-kafka-python]
Link 2 Git Sample

Below is my sample code!!

```<code>from confluent_kafka.admin import AdminClient, NewTopic, NewPartitions, ConfigResource
import confluent_kafka
import concurrent.futures

#Creation of config
conf = {'bootstrap.servers': 'kafka1','session.timeout.ms': 6000}
adminClient = AdminClient(conf)
topic_configResource = adminClient.describe_configs([ConfigResource(confluent_kafka.admin.RESOURCE_TOPIC, "myTopic")])
    for j in concurrent.futures.as_completed(iter(topic_configResource.values())):
        config_response = j.result(timeout=1)
</code>```

Body:
I'm beginner to kafka client in python, i need some help to describe the topics using the client.

I was able to list all my kafka topics using the following code:-

consumer = kafka.KafkaConsumer(group_id='test', bootstrap_servers=['kafka1'])
topicList = consumer.topics()

Body:
After referring multiple articles and code samples, I was able to do this through describe_configs using confluent_kafka.

Link 1 [Confluent-kafka-python]
Link 2 Git Sample

Below is my sample code!!

from confluent_kafka.admin import AdminClient, NewTopic, NewPartitions, ConfigResource
import confluent_kafka
import concurrent.futures

#Creation of config
conf = {'bootstrap.servers': 'kafka1','session.timeout.ms': 6000}
adminClient = AdminClient(conf)
topic_configResource = adminClient.describe_configs([ConfigResource(confluent_kafka.admin.RESOURCE_TOPIC, "myTopic")])
    for j in concurrent.futures.as_completed(iter(topic_configResource.values())):
        config_response = j.result(timeout=1)


问:
aframe switching between mouse and entity controls
I'm having massive problems getting mouse to work after the player has been in VR.

Updating the cursor attributes didn't do anything, so I've tried removing and replacing them

```<code>  getRayCasterAttributes: function(){

    return this.data.isVR ?
      {
        cursorAttributes:{
          fuse: true,
          fuseTimeout: cursorFuseTimeout,
        },
        raycasterAttributes: {
          objects: '[data-raycastable]',
        },

      } :
      {cursorAttributes:{
        fuse: true,
        fuseTimeout: cursorFuseTimeout,
        rayOrigin:  'mouse',
      },
      raycasterAttributes: {
        objects: '[data-raycastable]',
      },
      }
  }

 if(oldData.isVR !== this.data.isVR){
      this._recticle.object3D.visible = this.data.isVR
      this._recticle.removeAttribute('raycaster')
      this._recticle.removeAttribute('cursor')
      setTimeout(() => {
        console.log(this.getRayCasterAttributes().raycasterAttributes, this.getRayCasterAttributes().cursorAttributes)
        this._recticle.setAttribute('raycaster', this.getRayCasterAttributes().raycasterAttributes)
        this._recticle.setAttribute('cursor', this.getRayCasterAttributes().cursorAttributes)
      },100)
</code>```

This kind of works switching from 2D to VR with the timeout, but switching back is another major pain.

What is the best way to do this in aframe?

I've tried this, isn't helping. Works with mouse, does not switch to cursor controls when entering VR.

```<code>  this._recticle.setAttribute('cursor', {fuse: false, rayOrigin: 'mouse'})
else
  this._recticle.setAttribute('cursor', {fuse: true,rayOrigin: 'entity', fuseTimeout: 2000})
</code>```

答: The opposite would be rayOrigin: entity.

Body:
I'm having massive problems getting mouse to work after the player has been in VR.

Updating the cursor attributes didn't do anything, so I've tried removing and replacing them

  getRayCasterAttributes: function(){

    return this.data.isVR ?
      {
        cursorAttributes:{
          fuse: true,
          fuseTimeout: cursorFuseTimeout,
        },
        raycasterAttributes: {
          objects: '[data-raycastable]',
        },

      } :
      {cursorAttributes:{
        fuse: true,
        fuseTimeout: cursorFuseTimeout,
        rayOrigin:  'mouse',
      },
      raycasterAttributes: {
        objects: '[data-raycastable]',
      },
      }
  }

 if(oldData.isVR !== this.data.isVR){
      this._recticle.object3D.visible = this.data.isVR
      this._recticle.removeAttribute('raycaster')
      this._recticle.removeAttribute('cursor')
      setTimeout(() => {
        console.log(this.getRayCasterAttributes().raycasterAttributes, this.getRayCasterAttributes().cursorAttributes)
        this._recticle.setAttribute('raycaster', this.getRayCasterAttributes().raycasterAttributes)
        this._recticle.setAttribute('cursor', this.getRayCasterAttributes().cursorAttributes)
      },100)

This kind of works switching from 2D to VR with the timeout, but switching back is another major pain.

What is the best way to do this in aframe?

I've tried this, isn't helping. Works with mouse, does not switch to cursor controls when entering VR.

  this._recticle.setAttribute('cursor', {fuse: false, rayOrigin: 'mouse'})
else
  this._recticle.setAttribute('cursor', {fuse: true,rayOrigin: 'entity', fuseTimeout: 2000})


问:
Method List in Visual Studio Code
I've recently started using the Visual Studio Code editor.  I'm really loving it, but there's one critical feature (for me) that I haven't been able to find.  Is there a method list, similar to the Navigator in NetBeans or Member dropdown in Visual Studio?</p>

答:
In VSCode 1.24 you can do that.

Right click on EXPLORER on the side bar and checked Outline.

Title: Method List in Visual Studio Code


问:
Entity Framework Code First Value Object persist to database
I want to create Code First Entity Framework Model with some value objects. I got  exception:

EntityType 'CustomValueObject' has no key defined. Define the key for this EntityType.

I don't want to add a key, because it isn't a full entity.

答:
It was enough to add annotation [ComplexType]to class:

```<code>[ComplexType]
public class CustomValueObject
{ ... }
</code>```

Even better is to add this annotation to base class ValueObject, if there is one.

Body:
It was enough to add annotation [ComplexType]to class:

[ComplexType]
public class CustomValueObject
{ ... }

Even better is to add this annotation to base class ValueObject, if there is one.


问:
How can I add a filter class in Spring Boot?
Is there any annotation for a Filter class (for web applications) in Spring Boot? Perhaps @Filter?

I want to add a custom filter in my project.

The Spring Boot Reference Guide mentioned about
FilterRegistrationBean, but I am not sure how to use it.

答:
Filters, as the name suggest, used to perform filtering on either the request to a resource or on the response from a resource, or both. Spring Boot provides a few options to register custom filters in the Spring Boot application. Let’s look at the different options.

1. Define Spring Boot filter and invocation order

Implement the Filter interface to create a new filter in Spring Boot.

```<code>@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.info("########## Initiating Custom filter ##########");
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
                         throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        LOGGER.info("Logging Request  {} : {}", request.getMethod(), request.getRequestURI());

        // Call next filter in the filter chain
        filterChain.doFilter(request, response);

        LOGGER.info("Logging Response :{}", response.getContentType());
    }

    @Override
    public void destroy() {
        // TODO: 7/4/2018
    }
}
</code>```

Let’s quickly look at some important points in the above code

The filter registered by the @Component annotation.

To fire filters in the right order, we needed to use the @Order annotation.

```<code> @Component
 @Order(1)
 public class CustomFirstFilter implements Filter {

 }

 @Component
 @Order(2)
 public class CustomSecondFilter implements Filter {

 }
</code>```

In the above code, CustomFirstFilter will run before the CustomSecondFilter.

The lower the number, the higher the precedence

2. URL Pattern

If the convention-based mapping is not flexible enough, we can use FilterRegistrationBean for the complete control of the application. Here, don’t use @Component annotation for the filter class but register the filter using a FilterRegistrationBean.

```<code>public class CustomURLFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomURLFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.info("########## Initiating CustomURLFilter filter ##########");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        LOGGER.info("This Filter is only called when request is mapped for /customer resource");

        // Call the next filter in the filter chain
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
</code>```

Register the custom Filter using FilterRegistrationBean.

```<code>@Configuration
public class AppConfig {

    @Bean
    public FilterRegistrationBean < CustomURLFilter > filterRegistrationBean() {
        FilterRegistrationBean < CustomURLFilter > registrationBean = new FilterRegistrationBean();
        CustomURLFilter customURLFilter = new CustomURLFilter();

        registrationBean.setFilter(customURLFilter);
        registrationBean.addUrlPatterns("/greeting/*");
        registrationBean.setOrder(2); // Set precedence
        return registrationBean;
    }
}
</code>```

Body:
Filters, as the name suggest, used to perform filtering on either the request to a resource or on the response from a resource, or both. Spring Boot provides a few options to register custom filters in the Spring Boot application. Let’s look at the different options.

1. Define Spring Boot filter and invocation order

Implement the Filter interface to create a new filter in Spring Boot.

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.info("########## Initiating Custom filter ##########");
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
                         throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        LOGGER.info("Logging Request  {} : {}", request.getMethod(), request.getRequestURI());

        // Call next filter in the filter chain
        filterChain.doFilter(request, response);

        LOGGER.info("Logging Response :{}", response.getContentType());
    }

    @Override
    public void destroy() {
        // TODO: 7/4/2018
    }
}

Let’s quickly look at some important points in the above code

The filter registered by the @Component annotation.

To fire filters in the right order, we needed to use the @Order annotation.

 @Component
 @Order(1)
 public class CustomFirstFilter implements Filter {

 }

 @Component
 @Order(2)
 public class CustomSecondFilter implements Filter {

 }

In the above code, CustomFirstFilter will run before the CustomSecondFilter.

The lower the number, the higher the precedence

2. URL Pattern

If the convention-based mapping is not flexible enough, we can use FilterRegistrationBean for the complete control of the application. Here, don’t use @Component annotation for the filter class but register the filter using a FilterRegistrationBean.

public class CustomURLFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomURLFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.info("########## Initiating CustomURLFilter filter ##########");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        LOGGER.info("This Filter is only called when request is mapped for /customer resource");

        // Call the next filter in the filter chain
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

Register the custom Filter using FilterRegistrationBean.

@Configuration
public class AppConfig {

    @Bean
    public FilterRegistrationBean < CustomURLFilter > filterRegistrationBean() {
        FilterRegistrationBean < CustomURLFilter > registrationBean = new FilterRegistrationBean();
        CustomURLFilter customURLFilter = new CustomURLFilter();

        registrationBean.setFilter(customURLFilter);
        registrationBean.addUrlPatterns("/greeting/*");
        registrationBean.setOrder(2); // Set precedence
        return registrationBean;
    }
}


问:
How to stop bots from posting and causing exceptions
I have a form where anyone can fill in a review about something and this form is not inside a login area.

I started to use captcha after more and more bots was trying to input spam.
The problem now is that some sort of bot just isn't giving up. I receive loads of exception emails everyday since the bot tries to input "dangerous" data and .NET doesn't allow this because the request is validated.
The captcha doesn't help at all since it doesn't even need to be filled in to try to make a post which will cause an exception. The bot doesn't seem to understand that it fails everytime.

Yesterday I tried changing the names of the text boxes and I also added a "honeypot". But it's the same problem as with captcha, the exception occurs before anything is actually posted to the code behind.

Should I really have to set ValidateRequest="false" to enable the bot to make it a step further and maybe stop making requests?

All ideas are very appreciated.

答: Maybe the bot is quite stupid. Instead of having that form box in html encrypt it with javascript. It is possible that this will confuse the bot sufficiently.</p>

ContentLicense: CC BY-SA 2.5