问:
setting rootURL causing 404 error on page refresh
If I set language as rootURL this works I am able to go to any route/subroute and current language will be present in url, but on page refresh browser is trying get app from that language folder any thoughts? :/ I am using Ember 1.11.

```<code>// router.coffee

`import Ember from 'ember';`
`import config from './config/environment';`

Router = Ember.Router.extend
  location: config.locationType
  rootURL: '/' + localStorage.getItem('locale') + '/'

// config/environment.js

module.exports = function(environment) {
  var ENV = {
    locationType: 'history',
    baseURL: '/'
...
</code>```

答:
You shouldn't use rootURL for this purpose. Instead, create a route that will be a parent to all other routes:

```<code>//../app/router.js

import Ember from 'ember';
import config from './config/environment';
var Router = Ember.Router.extend(
    {
        location: config.locationType
    }
);
Router.map(
    function ()
    {
        this.route(
            'lang', { path: '/:lang' }, function ()
            {
                this.route('index', { path: '/' });
                this.route('404', { path: '/*wildcard' });
                this.route('your-route-name');
            }
        );
    }
);
export default Router;
</code>```

Than you can use afterModel method of lang route to determine desired locale:

```<code>//../app/routes/lang.js
import config from '../config/environment';
export default Ember.Route.extend(
    {
        afterModel: function (params)
        {
            var allowedLocales = config.i18n.allowedLocales;
            var defaultLocale = config.i18n.defaultLocale;
            this.set(
                'i18n.locale',
                params && params.lang && allowedLocales.indexOf(params.lang) > -1 ? params.lang : defaultLocale
            );
        }
    }
);
</code>```

And in index route you need to detect user's locale from browser's settings or use default one:

```<code>//../app/routes/index.js
import config from '../config/environment';
export default Ember.Route.extend(
    {
        beforeModel: function ()
        {
            var allowedLanguages = config.i18n.allowedLocales;
            var language = config.i18n.defaultLocale;
            if (navigator.languages) {
                for (let lang of navigator.languages) {
                    if (allowedLanguages.indexOf(lang) > -1) {
                        language = lang;
                        break;
                    }
                }
            } else {
                if (navigator.language) {
                    language = navigator.language;
                } else {
                    if (navigator.userLanguage) {
                        language = navigator.userLanguage;
                    }
                }
            }
            this.transitionTo('lang.index', { lang: language });
        }
    }
);
</code>```

BTW, your Ember version is quite old. You may want to upgrade it to 1.13 (1.13.x shouldn't break your app, 2.x could).

Body:
If I set language as rootURL this works I am able to go to any route/subroute and current language will be present in url, but on page refresh browser is trying get app from that language folder any thoughts? :/ I am using Ember 1.11.

// router.coffee

`import Ember from 'ember';`
`import config from './config/environment';`

Router = Ember.Router.extend
  location: config.locationType
  rootURL: '/' + localStorage.getItem('locale') + '/'

// config/environment.js

module.exports = function(environment) {
  var ENV = {
    locationType: 'history',
    baseURL: '/'
...

Body:
You shouldn't use rootURL for this purpose. Instead, create a route that will be a parent to all other routes:

//../app/router.js

import Ember from 'ember';
import config from './config/environment';
var Router = Ember.Router.extend(
    {
        location: config.locationType
    }
);
Router.map(
    function ()
    {
        this.route(
            'lang', { path: '/:lang' }, function ()
            {
                this.route('index', { path: '/' });
                this.route('404', { path: '/*wildcard' });
                this.route('your-route-name');
            }
        );
    }
);
export default Router;

Than you can use afterModel method of lang route to determine desired locale:

//../app/routes/lang.js
import config from '../config/environment';
export default Ember.Route.extend(
    {
        afterModel: function (params)
        {
            var allowedLocales = config.i18n.allowedLocales;
            var defaultLocale = config.i18n.defaultLocale;
            this.set(
                'i18n.locale',
                params && params.lang && allowedLocales.indexOf(params.lang) > -1 ? params.lang : defaultLocale
            );
        }
    }
);

And in index route you need to detect user's locale from browser's settings or use default one:

//../app/routes/index.js
import config from '../config/environment';
export default Ember.Route.extend(
    {
        beforeModel: function ()
        {
            var allowedLanguages = config.i18n.allowedLocales;
            var language = config.i18n.defaultLocale;
            if (navigator.languages) {
                for (let lang of navigator.languages) {
                    if (allowedLanguages.indexOf(lang) > -1) {
                        language = lang;
                        break;
                    }
                }
            } else {
                if (navigator.language) {
                    language = navigator.language;
                } else {
                    if (navigator.userLanguage) {
                        language = navigator.userLanguage;
                    }
                }
            }
            this.transitionTo('lang.index', { lang: language });
        }
    }
);

BTW, your Ember version is quite old. You may want to upgrade it to 1.13 (1.13.x shouldn't break your app, 2.x could).


来源: stackexchange

问:
Preserve the initial order of array in Symfony2 Doctrine findBy()
I have an array ($newsList) of IDs with the following values: 4,2,1,3.

I'm trying to get some data from the database from entity:

```<code>$news=$this->getDoctrine()->getRepository('Bundle:News')->findBy(array('id' => $newsList));
</code>```

$newsList array represents real IDs from the News entity.

But when I do:

```<code>foreach($news as $n){
    $n->getId();
}
</code>```

IDs are in order: 1,2,3,4.

How can I preserve the order from beginning in foreach?

答:
IMO the best solution is to use field function to get proper news order:

```<code>$ids = [4, 1, 2, 3];
$news  = $this->getDoctrine()->getRepository('Bundle:News')->createQueryBuilder('n')
    ->select('n, field(n.id, :ids) as HIDDEN field')
    ->where("n.id IN (:ids)")
    ->setParameter('ids', $ids )
    ->orderBy(field)
    ->getQuery()
    ->getResult();
</code>```

Note: this solution require custom field function that can be found here.

ContentLicense: CC BY-SA 3.0

Body:
I have an array ($newsList) of IDs with the following values: 4,2,1,3.

I'm trying to get some data from the database from entity:

$news=$this->getDoctrine()->getRepository('Bundle:News')->findBy(array('id' => $newsList));

$newsList array represents real IDs from the News entity.

But when I do:

foreach($news as $n){
    $n->getId();
}

IDs are in order: 1,2,3,4.

How can I preserve the order from beginning in foreach?

Body:
IMO the best solution is to use field function to get proper news order:

$ids = [4, 1, 2, 3];
$news  = $this->getDoctrine()->getRepository('Bundle:News')->createQueryBuilder('n')
    ->select('n, field(n.id, :ids) as HIDDEN field')
    ->where("n.id IN (:ids)")
    ->setParameter('ids', $ids )
    ->orderBy(field)
    ->getQuery()
    ->getResult();

Note: this solution require custom field function that can be found here.


问:
What's the benefit of Scala (singleton) object vs. typical class level artifacts
I understand one of the main benefits from using object is, they are real objects instead of system wide functionality.  But finally those objects are also system wide accessible.

Beside of being more "pure"  what additional benefit does scala "objects" offer.

I bet there are a number but I can't really figure out which.

答:
The real question should be: why using singletons instead of static classes (static method and fields).

For sure one benefit is that removing static simplify compiler and runtime method resolution.

Another benefit is that having singletons supported by the language is very useful when you write you're own code, you don't have to use dirty trick like private constructors and the orrible getInstance() static method. So much cleaner syntax.

Finally static methods and fields are a nightmare for concurrency unwanted sideeffects.

ContentLicense: CC BY-SA 2.5


问:
Delete duplicate rows based on a condition
I have a table that has ID and EventDate. It has duplicate rows as I used Union of two tables. Now I got to have the rows with the minimum Eventdate and remove the other duplicates.

the table for eg

ID  | Date

--- | ---

1     | 10/27/1993

1      | 10/27/1994

2      | 10/17/1993

2      | 08/15/1993

Delete duplicate rows based on condition

答:
As documentation (if we about MySQL) you cannot "delete from a table and select from the same table in a subquery".

So

```<code>CREATE table1 LIKE table2;
INSERT table2 SELECT * FROM table1;
DELETE FROM table1
WHERE EXISTS(
  SELECT t2.id FROM table2 t2 WHERE table1.EventDate>t2.EventDate
);
DROP TABLE table2;
</code>```

Where table1 you original table.

Body:
As documentation (if we about MySQL) you cannot "delete from a table and select from the same table in a subquery".

So

CREATE table1 LIKE table2;
INSERT table2 SELECT * FROM table1;
DELETE FROM table1
WHERE EXISTS(
  SELECT t2.id FROM table2 t2 WHERE table1.EventDate>t2.EventDate
);
DROP TABLE table2;

Where table1 you original table.


问:
Where in Rails App should I be creating a JSON object
I have a rails app with two steps:

1) form where user selects options

2) result table where user sees output based on options in 1

Right now, the result table is built with datatables.  The table is populated in the view by iterating through the options passed in from step 1 with the model being called for each row in tr's and td's.  I suspect there is a better way to do this.

I want to format the table to output to PDF with nice formatting, and most of the examples I see online involve JSON data being passed in.  Should I have my model or controller create this JSON object?

Thanks

答:
if you want to output the result to a PDF, you don't need JSON data being passed, you can use prawn pdf prawnpdf gem, and you can use same method from your statement "The table is populated in the view by iterating through the options passed", you just need to split the output with  respond_to format

```<code>@your_data_tables = YourOptionModel....
respond_to do |format|
  format.html
  format.pdf do
    pdf = ReportPdf.new(@your_data_tables)
    send_data pdf.render, filename: "your_data_table.pdf",type: "application/pdf", disposition: "inline"
  end
end
</code>```

here is sample to split output between html and pdf using respond_to

Body:
if you want to output the result to a PDF, you don't need JSON data being passed, you can use prawn pdf prawnpdf gem, and you can use same method from your statement "The table is populated in the view by iterating through the options passed", you just need to split the output with  respond_to format

@your_data_tables = YourOptionModel....
respond_to do |format|
  format.html
  format.pdf do
    pdf = ReportPdf.new(@your_data_tables)
    send_data pdf.render, filename: "your_data_table.pdf",type: "application/pdf", disposition: "inline"
  end
end

here is sample to split output between html and pdf using respond_to


问:
Write a program that prints the longest substring of s in which the letters occur in alphabetical order
The code runs fine and the output seems ok. But my print is inside the for loop, this makes me doubt that the coding is correct:

```<code>s = 'azcbobobegghakl'
i = 0
increase = 0
longest = 1
for i in range(len(s) - 1):
        if s[i+1] >= s[i]:
           increase +=1
        else:
            if increase > longest:
               longest = increase
               print ("
Longest substring in alphabetical order is:"+""+s[i-longest:i+1])

            increase =0
</code>```

答:
```<code>#With the help of MIT pythontutor(www.pythontutor.com) and
their exercise code test machine,I reworte my code and achieve its function in any string.

i = 0
increase = 0
longest = 0
tem_longest= 0
max_i = 0
start = 0
end = 0
for i in range(len(s)-1 ):
        if s[i+1] >= s[i]:
           increase +=1
           tem_longest = increase
           max_i=i+1
           if increase==(len(s)-1):
              longest = increase
              max_i=i+1
              start = max_i-longest
              end = max_i+1
              break
        else:
            max_i=i
            tem_longest = increase
            increase =0

        if tem_longest > longest:
           longest = tem_longest
           start = max_i-longest
           end = max_i+1

        if i+1 == (len(s)-1) and tem_longest == 0 and longest == 0:
           start = 0
           end = 1

print ("Longest substring in alphabetical order is:"+""+s[start:end])
</code>```

Body:
The code runs fine and the output seems ok. But my print is inside the for loop, this makes me doubt that the coding is correct:

s = 'azcbobobegghakl'
i = 0
increase = 0
longest = 1
for i in range(len(s) - 1):
        if s[i+1] >= s[i]:
           increase +=1
        else:
            if increase > longest:
               longest = increase
               print ("
Longest substring in alphabetical order is:"+""+s[i-longest:i+1])

            increase =0


问:
ImportError: cannot import name taskqueue
I am trying to use AppEngine TaskQueue API, so I import it like this:

```<code>from google.appengine.api import taskqueue
</code>```

The code works perfectly online. But when I try to run it locally, I get this error:

```<code>ImportError: cannot import name taskqueue
</code>```

I checked the directory of AppEngine and I didn't find the file taskqueue.py which explains the error. Is there any reason why this file isn't included in the AppEngine SDK? And is there anyway to install it locally? I wouldn't trust just copying the file to the folder, because I am sure it depends on tens of other files.

答: OK, I found the solution for this myself. I just downloaded the latest AppEngine SDK (version 1.4) and it has the taskqueue.</p>

Body:
I am trying to use AppEngine TaskQueue API, so I import it like this:

from google.appengine.api import taskqueue

The code works perfectly online. But when I try to run it locally, I get this error:

ImportError: cannot import name taskqueue

I checked the directory of AppEngine and I didn't find the file taskqueue.py which explains the error. Is there any reason why this file isn't included in the AppEngine SDK? And is there anyway to install it locally? I wouldn't trust just copying the file to the folder, because I am sure it depends on tens of other files.


问:
How to get array allocation with JProfiler
My spark java application is running on remote machine in our internal lab. To analyse the memory consumption of remote application, attached the remote application pid to JProfiler by using the 'attach mode' (with help of jpenable) from my local machine.

After attaching the remote application to JProfiler in local machine, 'Allocation tree' is showing only non-array object allocations. I want to know array allocations also from my local machine.

Please help me to know about the array allocation with JProfiler.

Thanks,
Nagendra R

答:
When you attach to a running JVM with the JProfiler GUI, the session startup dialog has an option "Record array allocations". It is not selected by default, because it requires a large amount of reinstrumentations which can be very slow.

If array allocation spots are important for your analysis, it's better not to use attach mode but to pass the VM parameter for profiling as given by

Session->Integration wizards->New remote integration

Then the instrumentation is done while the classes are loaded.


问:
How to parse Multi level nested json result
Snapshot from firebug chrome

To be honest I have been running into parsing Json Multi level nested object,
I have been working into real estate website where data from third party has been return into Json format; however data been sent into multi-level which I would like to display into div tag
It would be great help if I could iterate through each return result and could display images

答:
Parsing json strings can be done to nested objects the same way as normal object strings:

```<code>var yourobject = JSON.parse("Your object string");
</code>```

Also see this from w3 https://www.w3schools.com/js/js_json_parse.asp

now loop through

```<code>$.each(yourobject , function (index, value) {
       console.log(this);
});
</code>```

Also see this from jquery docs https://api.jquery.com/each/

Hope this helped :D

Body:
Parsing json strings can be done to nested objects the same way as normal object strings:

var yourobject = JSON.parse("Your object string");

Also see this from w3 https://www.w3schools.com/js/js_json_parse.asp

now loop through

$.each(yourobject , function (index, value) {
       console.log(this);
});

Also see this from jquery docs https://api.jquery.com/each/

Hope this helped :D


问:
FreeRTOS compiler
I just started learning FreeRtos. I have started with "Using the FreeRtos Real Time Kernel" pdf book of Richard Barry.
The book has comprehensive examples and I understood the principles very well but I want to be able to compile this examples somewhere.

Now this may sound like a dumb question but I'm totally new to RTOS :D.
What compiler can I use to compile freeRtos code? I have googled a lot and I found some compiler named Watcom and tried to run some code in it but couldn't and could not find any examples on how to use this compiler.

So basically what I would like is some examples of actually someone showing how to run simple freeRtos code in a compiler then run it and see the actual results in a console.

Any links would be appreciated. Thank you for reading!

答:
Normally you run a FreeRTOS application in a stand-alone environment - ie, the system boots directly into your application rather then being loaded by an OS (there may be an intermediate bootloader in some cases).

There is no concept of a "console" in FreeRTOS itself; your application must implement support for stdio or low-level I/O, typically via a UART and a terminal emulator running on the development host or by using semi-hosting via your debugger.  This is a mater of porting your standard library rather than an issue for FreeRTOS.  The standard library should have some sort fo pirting layer (known as "syscalls" in Newlib, or "Retargetting" in ARM/Keil toolchains for example).

FreeRTOS applications are built using cross-development tools rather than hosted development environments.  That is the code is build on a development host using a cross-compiler then loaded to the target hardware and executed.  There is a Win32 port of FreeRTOS that allows FreeRTOS applications to be built and executed on a Windows host, but the port is only a simulation, and does not provide hard-real-time scheduling.  It is useful for development before hardware is available and testing and debugging using the more sophisticated debugging environment provided by Visual Studio that that typically available to embedded targets.

What you would normally do is select a hardware platform that FreeRTOS supports and meets your application needs, then select a toolchain that supports your hardware platform and is in turn supported by FreeRTOS. For most 32 bit platforms and the 8-bit AtmelAVR platform GNU gcc is near ubiquitous, and many proprietary compilers support GNU extensions for compatability.  Unless you choose a particularly obscure toolchain/target combination, you are unlikely to not be able to either port to use an existing port of FreeRTOS.

Title: FreeRTOS compiler


答: Download and install the current SDK.  You're using an older version.</p>

Title: ImportError: cannot import name taskqueue


问:
Trying to implement in Android Studio 2.3.3 a splash screen image while loading WebView URL
There are similar questions to this "splash screen thing" but no one is working for me or I am doing something wrong. I inserted the code from this answer Splash Screen Code.
The app starts with the splash screen after a second it disappears and then it shows a white background. It doesn't show me the WebView in the next step when the website is loaded. Can anybody help me out?

Here is my code for MainActivity.java:

```<code>import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import static jombi.mooni.R.id.swiperefresh;

public class MainActivity extends AppCompatActivity {
// declare private WebView Variable
private WebView wb;
// method to check for active network connection (caching website)
private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // link the wb Variable to the WebView Component using the webView Id which we gave in the beginning in activity_main.xml-Designansicht
    wb = (WebView) findViewById(R.id.WebView);
    assert wb != null;
    WebSettings webSettings = wb.getSettings();

    WebViewClientImpl webViewClient = new WebViewClientImpl(this);
    wb.setWebViewClient(webViewClient);

    // caching whole website when online from website when offline from cache
    wb.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
    wb.getSettings().setAllowFileAccess( true );
    wb.getSettings().setAppCacheEnabled( true );
    wb.getSettings().setLoadsImagesAutomatically(true);
    //activate JavaScript
    webSettings.setJavaScriptEnabled(true);
    wb.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT ); // load online by default
    if ( !isNetworkAvailable() ) { // loading offline
        wb.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

    }

    // load custom errorpage
    wb.setWebViewClient(new WebViewClient(){
        @SuppressWarnings("deprecation")
        @Override
        public void onReceivedError(android.webkit.WebView view, int errorCode, String description, String failingUrl) {
            wb.loadUrl("file:///android_asset/errorpage/index.html");
        }

    @Override

          public void onPageFinished(WebView view, String url) {

//hide loading image

findViewById(R.id.imgLogo).setVisibility(View.GONE);

//show webview

findViewById(R.id.WebView).setVisibility(View.VISIBLE);

 }

});

// call with wb variable the method loadurl
wb.loadUrl("http://xxx.yyy.zz");

    // swipe to refresh screen
    final SwipeRefreshLayout SwipeRefreshLayout = (SwipeRefreshLayout) findViewById(swiperefresh);
    SwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_orange_dark, android.R.color.holo_orange_light, android.R.color.holo_red_dark, android.R.color.holo_red_light);
    SwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            wb.loadUrl("javascript:window.location.reload(true)");

            refreshItems();
        }
        void refreshItems() {
            // Load items
            SwipeRefreshLayout.setRefreshing(true);
            // Load complete
            onItemsLoadComplete();
        }

        void onItemsLoadComplete() {
            // Update the adapter and notify data set changed
            // ...

            // Stop refresh animation
            SwipeRefreshLayout.setRefreshing(false);
        }
    });

}

private Boolean exit = false;
@Override
// when Back Button pressed load previous page and at last page display end message
public void onBackPressed() {
    if (wb.canGoBack()) {
        wb.goBack();
    } else {
        if (exit)
            this.finish();
        else {
            Toast.makeText(this, "Push to close app",
                    Toast.LENGTH_SHORT).show();
            exit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 3 * 1000);
        }

    }
}

// own URL in WebView, external URL in AndroidBrowser
private class WebViewClientImpl extends WebViewClient {

    private Activity activity = null;

    private WebViewClientImpl(Activity activity) {
        this.activity = activity;
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(url.contains("xxx.yyy.zz") ) return false;

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        activity.startActivity(intent);
        return true;
    }
    //End own URL in WebView, external URL in AndroidBrowser
}

}
</code>```

and activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="jombi.mooni.MainActivity"
android:id="@+id/swiperefresh">

<ImageView
    android:id="@+id/imgLogo"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:visibility="visible"
    android:background="@color/colorPrimaryDark"
    android:src="@drawable/boat" />

<WebView
    android:id="@+id/WebView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone"
    tools:ignore="MissingConstraints"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp">
</WebView>
</code>```

答:
Source: https://stackoverflow.com/a/9589451/8252521

Answered by: https://stackoverflow.com/users/374866/davehale23

I do it by initially showing an ImageView and then once the WebView
  has loaded, swapping their visibility like this

```<code>        WebView wv = (WebView) findViewById(R.id.webView1);
        wv.getSettings().setJavaScriptEnabled(true);
      wv.setWebViewClient(new WebViewClient() {

          ...

          @Override
          public void onPageFinished(WebView view, String url) {
              //hide loading image
              findViewById(R.id.imageLoading1).setVisibility(View.GONE);
              //show webview
              findViewById(R.id.webView1).setVisibility(View.VISIBLE);
          }

      });
      wv.loadUrl("http://yoururlhere.com");
</code>```

And my xml layout looks like this

```<code>    <ImageView android:id="@+id/imageLoading1"
      android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:visibility="visible"
        android:src="@drawable/vert_loading"
        />
    <WebView android:id="@+id/webView1"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:visibility="gone"
        />
</code>```

Body:
There are similar questions to this "splash screen thing" but no one is working for me or I am doing something wrong. I inserted the code from this answer Splash Screen Code.
The app starts with the splash screen after a second it disappears and then it shows a white background. It doesn't show me the WebView in the next step when the website is loaded. Can anybody help me out?

Here is my code for MainActivity.java:

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import static jombi.mooni.R.id.swiperefresh;

public class MainActivity extends AppCompatActivity {
// declare private WebView Variable
private WebView wb;
// method to check for active network connection (caching website)
private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // link the wb Variable to the WebView Component using the webView Id which we gave in the beginning in activity_main.xml-Designansicht
    wb = (WebView) findViewById(R.id.WebView);
    assert wb != null;
    WebSettings webSettings = wb.getSettings();

    WebViewClientImpl webViewClient = new WebViewClientImpl(this);
    wb.setWebViewClient(webViewClient);

    // caching whole website when online from website when offline from cache
    wb.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
    wb.getSettings().setAllowFileAccess( true );
    wb.getSettings().setAppCacheEnabled( true );
    wb.getSettings().setLoadsImagesAutomatically(true);
    //activate JavaScript
    webSettings.setJavaScriptEnabled(true);
    wb.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT ); // load online by default
    if ( !isNetworkAvailable() ) { // loading offline
        wb.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

    }

    // load custom errorpage
    wb.setWebViewClient(new WebViewClient(){
        @SuppressWarnings("deprecation")
        @Override
        public void onReceivedError(android.webkit.WebView view, int errorCode, String description, String failingUrl) {
            wb.loadUrl("file:///android_asset/errorpage/index.html");
        }

    @Override

          public void onPageFinished(WebView view, String url) {

//hide loading image

findViewById(R.id.imgLogo).setVisibility(View.GONE);

//show webview

findViewById(R.id.WebView).setVisibility(View.VISIBLE);

 }

});

// call with wb variable the method loadurl
wb.loadUrl("http://xxx.yyy.zz");

    // swipe to refresh screen
    final SwipeRefreshLayout SwipeRefreshLayout = (SwipeRefreshLayout) findViewById(swiperefresh);
    SwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_orange_dark, android.R.color.holo_orange_light, android.R.color.holo_red_dark, android.R.color.holo_red_light);
    SwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            wb.loadUrl("javascript:window.location.reload(true)");

            refreshItems();
        }
        void refreshItems() {
            // Load items
            SwipeRefreshLayout.setRefreshing(true);
            // Load complete
            onItemsLoadComplete();
        }

        void onItemsLoadComplete() {
            // Update the adapter and notify data set changed
            // ...

            // Stop refresh animation
            SwipeRefreshLayout.setRefreshing(false);
        }
    });

}

private Boolean exit = false;
@Override
// when Back Button pressed load previous page and at last page display end message
public void onBackPressed() {
    if (wb.canGoBack()) {
        wb.goBack();
    } else {
        if (exit)
            this.finish();
        else {
            Toast.makeText(this, "Push to close app",
                    Toast.LENGTH_SHORT).show();
            exit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 3 * 1000);
        }

    }
}

// own URL in WebView, external URL in AndroidBrowser
private class WebViewClientImpl extends WebViewClient {

    private Activity activity = null;

    private WebViewClientImpl(Activity activity) {
        this.activity = activity;
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(url.contains("xxx.yyy.zz") ) return false;

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        activity.startActivity(intent);
        return true;
    }
    //End own URL in WebView, external URL in AndroidBrowser
}

}

and activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="jombi.mooni.MainActivity"
android:id="@+id/swiperefresh">

<ImageView
    android:id="@+id/imgLogo"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:visibility="visible"
    android:background="@color/colorPrimaryDark"
    android:src="@drawable/boat" />

<WebView
    android:id="@+id/WebView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone"
    tools:ignore="MissingConstraints"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp">
</WebView>

Body:
Source: https://stackoverflow.com/a/9589451/8252521

Answered by: https://stackoverflow.com/users/374866/davehale23

I do it by initially showing an ImageView and then once the WebView
  has loaded, swapping their visibility like this

        WebView wv = (WebView) findViewById(R.id.webView1);
        wv.getSettings().setJavaScriptEnabled(true);
      wv.setWebViewClient(new WebViewClient() {

          ...

          @Override
          public void onPageFinished(WebView view, String url) {
              //hide loading image
              findViewById(R.id.imageLoading1).setVisibility(View.GONE);
              //show webview
              findViewById(R.id.webView1).setVisibility(View.VISIBLE);
          }

      });
      wv.loadUrl("http://yoururlhere.com");

And my xml layout looks like this

    <ImageView android:id="@+id/imageLoading1"
      android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:visibility="visible"
        android:src="@drawable/vert_loading"
        />
    <WebView android:id="@+id/webView1"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:visibility="gone"
        />


问:
TypeError: google.map is undefined (even when MapsAPILoader loaded)
I want to use google.map.XXX (e.g. google.map.LatLng) in my code.

First, to be able to build a project I added declare let google : any; before my class definition.

When I tried to run a project, TypeError: google.map is undefined error has occured.
I used google.map.XXX in ngOnInit() method, therefore i thought "Perhaps GoogleMaps still isn't loaded?"...  So, it was kind of right assumption.

Then I tried to use google.map.XXX inside of code like below

```<code>ngAfterViewInit() {
  this.mapsAPILoader.load().then(() => {
    // code that uses namespace of google.map
  });
}
</code>```

and error below has occured:

EXCEPTION: Uncaught (in promise): TypeError: google.map is undefined

Why even after MapsAPILoader fired the callback, google.map is undefined?

答:
The problem is stupid misspell!

❌　google.map.XXX

⭕　google.maps.XXX

Body:
I want to use google.map.XXX (e.g. google.map.LatLng) in my code.

First, to be able to build a project I added declare let google : any; before my class definition.

When I tried to run a project, TypeError: google.map is undefined error has occured.
I used google.map.XXX in ngOnInit() method, therefore i thought "Perhaps GoogleMaps still isn't loaded?"...  So, it was kind of right assumption.

Then I tried to use google.map.XXX inside of code like below

ngAfterViewInit() {
  this.mapsAPILoader.load().then(() => {
    // code that uses namespace of google.map
  });
}

and error below has occured:

EXCEPTION: Uncaught (in promise): TypeError: google.map is undefined

Why even after MapsAPILoader fired the callback, google.map is undefined?


问:
How to find distinct count of data frame particular column value
df:

```<code>Field1 Field2
1      2
3      4
5      6
1      7
3      8
</code>```

Please let me know how to find distinct count of df['Field1'], Results should be 3
In SQL we use query like this.

```<code>select count(distinct Field1) as Field1DistCount from df
</code>```

答:
Let's use nunique:

```<code>df['Field1'].nunique()
</code>```

Output:

```<code>3
</code>```

Body:
df:

Field1 Field2
1      2
3      4
5      6
1      7
3      8

Please let me know how to find distinct count of df['Field1'], Results should be 3
In SQL we use query like this.

select count(distinct Field1) as Field1DistCount from df

Body:
Let's use nunique:

df['Field1'].nunique()

Output:

3


问:
PHP MySQL insert multiple rows with different IDs
I have the following table:

```<code>id | message_id | recevier_id
 1 |      8     |    2
 2 |      9     |    5
 3 |     14     |    4
</code>```

I am sending data to a PHP file to add to the above table. My data is as follows:

messageid = "2"
receiver id = "5,6,34"

I am trying to add multiple rows with different "receiver id", so the outcome of the above query should result in :

```<code>id | message_id | recevier_id
 1 |      8     |    2
 2 |      9     |    5
 3 |     14     |    4
 4 |      2     |    5
 5 |      2     |    6
 6 |      2     |   34
</code>```

My current MySQL query looks like this:

```<code><?php
$inputvalues = $_POST;
$errors = false;
$result = false;
session_start();
include_once '../../../includes/database.php';
$uid = $_SESSION['usr_id'];
$sendername = $_SESSION['firstnames'].' '.$_SESSION['surname'];

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    foreach ($inputvalues as $key => $value) {
        if(isset($value) && !empty($value)) {
            $inputvalues[$key] = $mysqli->real_escape_string( $value );
        } else {
            $errors[$key] = 'The field '.$key.' is empty';
        }
    }

    if( !$errors ) {
        $mysqli->query("
            INSERT INTO `message_receiver_map` (`message_id`, `receiver_id`) VALUES ('".$messageid."', '".$inputvalues['receiverid']."');
        ");
        $returnResult = "Success";
    }
    mysqli_close($mysqli);
    echo json_encode(['result' => $returnResult, 'errors' => $errors]);
    exit;
?>
</code>```

How can I achieve this?

答:
You can do something like this:</p>

```<code>$messageid = "2";         // received value
$receiverids = "5,6,34";  // received value
$receiverid = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("INSERT INTO `table` (`message_id`, `receiver_id`) VALUES (?, ?)");
$stmt->bind_param("ss", $messageid, $receiverid);

foreach($rid in explode($receiverids)) {
   // set parameters and execute
   $receiverid = $rid;
   $stmt->execute();
}

$stmt->close();
</code>```

Body:
I have the following table:

id | message_id | recevier_id
 1 |      8     |    2
 2 |      9     |    5
 3 |     14     |    4

I am sending data to a PHP file to add to the above table. My data is as follows:

messageid = "2"
receiver id = "5,6,34"

I am trying to add multiple rows with different "receiver id", so the outcome of the above query should result in :

id | message_id | recevier_id
 1 |      8     |    2
 2 |      9     |    5
 3 |     14     |    4
 4 |      2     |    5
 5 |      2     |    6
 6 |      2     |   34

My current MySQL query looks like this:

<?php
$inputvalues = $_POST;
$errors = false;
$result = false;
session_start();
include_once '../../../includes/database.php';
$uid = $_SESSION['usr_id'];
$sendername = $_SESSION['firstnames'].' '.$_SESSION['surname'];

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    foreach ($inputvalues as $key => $value) {
        if(isset($value) && !empty($value)) {
            $inputvalues[$key] = $mysqli->real_escape_string( $value );
        } else {
            $errors[$key] = 'The field '.$key.' is empty';
        }
    }

    if( !$errors ) {
        $mysqli->query("
            INSERT INTO `message_receiver_map` (`message_id`, `receiver_id`) VALUES ('".$messageid."', '".$inputvalues['receiverid']."');
        ");
        $returnResult = "Success";
    }
    mysqli_close($mysqli);
    echo json_encode(['result' => $returnResult, 'errors' => $errors]);
    exit;
?>

How can I achieve this?

Body:
You can do something like this:

$messageid = "2";         // received value
$receiverids = "5,6,34";  // received value
$receiverid = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("INSERT INTO `table` (`message_id`, `receiver_id`) VALUES (?, ?)");
$stmt->bind_param("ss", $messageid, $receiverid);

foreach($rid in explode($receiverids)) {
   // set parameters and execute
   $receiverid = $rid;
   $stmt->execute();
}

$stmt->close();


问:
In Delphi: How to skip sections of code while debugging?
I often accidently step into code that I'm not interested in while debugging in Delphi.

Let's start by saying that I know that you can step over with F8, and that you can run to a certain line with f4.

Example:

```<code>function TMyClass.DoStuff():Integer;
begin
  // do some stuff
  bla();
end;

procedure TMyClass.Foo()
begin
  if DoStuff()=0 then // press F7 when entering this line
    beep;
end;
</code>```

Example: I want to step into method DoStuff() by pressing F7, but instead of going there, I first end up in FastMM4.FastGetMem(), which is a massive blob of assembly code that obviously I'm not interested in at the moment.

There are several ways to go about this, and I don't like any of them:

Add a breakpoint on "bla" (almost useless if you only want to step into DoStuff on special occasions, like iteration 23498938);

Instead of pressing F7, manually move the cursor to "bla", and press F4 (Works for this simple example. In practice, it doesn't);

In case of FastMM: temporarily disable fastmm;

Is there any way to hint the IDE that I'm never interested into stepping into a certain block of code, or do I always have to set extra breakpoints or use F4 to try to avoid this?

I'm hoping for some magic compiler directive like {$NODEBUG BEGIN/END} or something like that.

In most cases being able to exclude entire units would be fine-grained enough for me, but being able to avoid certain methods or even lines of code would be even better.

Update: Maybe codegear should introduce something like skip-points (as opposed to break-points) :-)

答: Use a precompiled non-debug DCU of FasmMM</p>

OwnerDisplayName: Wouter van Nifterick

Body:
I often accidently step into code that I'm not interested in while debugging in Delphi.

Let's start by saying that I know that you can step over with F8, and that you can run to a certain line with f4.

Example:

function TMyClass.DoStuff():Integer;
begin
  // do some stuff
  bla();
end;

procedure TMyClass.Foo()
begin
  if DoStuff()=0 then // press F7 when entering this line
    beep;
end;

Example: I want to step into method DoStuff() by pressing F7, but instead of going there, I first end up in FastMM4.FastGetMem(), which is a massive blob of assembly code that obviously I'm not interested in at the moment.

There are several ways to go about this, and I don't like any of them:

Add a breakpoint on "bla" (almost useless if you only want to step into DoStuff on special occasions, like iteration 23498938);

Instead of pressing F7, manually move the cursor to "bla", and press F4 (Works for this simple example. In practice, it doesn't);

In case of FastMM: temporarily disable fastmm;

Is there any way to hint the IDE that I'm never interested into stepping into a certain block of code, or do I always have to set extra breakpoints or use F4 to try to avoid this?

I'm hoping for some magic compiler directive like {$NODEBUG BEGIN/END} or something like that.

In most cases being able to exclude entire units would be fine-grained enough for me, but being able to avoid certain methods or even lines of code would be even better.

Update: Maybe codegear should introduce something like skip-points (as opposed to break-points) :-)

LastEditorDisplayName: Wouter van Nifterick

OwnerDisplayName: Jim McKeeth


问:
Uses of static variables inside functions
I have been writing C code for many years, but I recently came accross a feature that I have never used: a static variable inside a function. Therefore, I was wondering what are some ways that you have used this feature and it was the right design decision.

E.g.

```<code>int count(){
    static int n;
    n = n + 1;
    return n;
}
</code>```

is a BAD design decision. why? because later you might want to decrement the count which would involve changing the function parameters, changing all calling code, ...

Hopefully this is clear enough,
thanks!

答:
I have used static variables as a way to control the execution of another thread.

For instance, thread #1 (the main thread) first declares and initializes a control variable such as:

```<code>/* on thread #1 */
static bool run_thread = true;
// then initialize the worker thread
</code>```

and then it starts the execution of thread #2, which is going to do some work until thread #1 decides to stop it:

```<code>/* thread #2 */
while (run_thread)
{
  // work until thread #1 stops me
}
</code>```

Body:
I have been writing C code for many years, but I recently came accross a feature that I have never used: a static variable inside a function. Therefore, I was wondering what are some ways that you have used this feature and it was the right design decision.

E.g.

int count(){
    static int n;
    n = n + 1;
    return n;
}

is a BAD design decision. why? because later you might want to decrement the count which would involve changing the function parameters, changing all calling code, ...

Hopefully this is clear enough,
thanks!

Body:
I have used static variables as a way to control the execution of another thread.

For instance, thread #1 (the main thread) first declares and initializes a control variable such as:

/* on thread #1 */
static bool run_thread = true;
// then initialize the worker thread

and then it starts the execution of thread #2, which is going to do some work until thread #1 decides to stop it:

/* thread #2 */
while (run_thread)
{
  // work until thread #1 stops me
}


问:
Play Framework - Passing Application Arguments via Docker Container
Before dockerizing my play web application, I was able to do the following when running:

```<code>Joes-Macbook:project-1 joe$ sbt -Dconfig.env=dev run
</code>```

Where I can use one of the following of either dev, qa, prod to the config.env argument and my application will run using the corresponding application.dev.conf or application.qa.conf accordingly.

Now I have my application as a docker container which means that I need a way to inject my configuration file. How could I do it?

One way what I'm thinking is to have a shell script and use that as the Entrypoint. But not sure how this might work? Any suggestions?

So when I do

sbt docker:publishLocal

I get the following Dockerfile produced

```<code>FROM anapsix/alpine-java:8_server-jre_unlimited
MAINTAINER Joesan <myemail@email.com>
WORKDIR /opt/docker
ADD opt /opt
RUN ["chown", "-R", "daemon:daemon", "."]
USER daemon
ENTRYPOINT ["sh", "-c", "bin/project-1", "-Denv=$configEnv"]
CMD []
ENV configEnv default
</code>```

I could not get the $configEnv resolved in my Scala application. This is how I run the produced docker image:

```<code>docker run -e "configEnv=crap" --rm --name play-8080 -p 8080:9000 joesan/project-1:1.0-SNAPSHOT
</code>```

答:
So with the help from VonC, and few changes to my build.sbt, I made it to work:

This is what I have in my build.sbt:

```<code>dockerCommands ++= Seq(
  Cmd("ENV", "configEnv", "default"), // This will be overridden when running!
  // This is the entrypoint where we can run the application against different environments
  ExecCmd("ENTRYPOINT", "sh", "-c", "bin/" + s"${executableScriptName.value}" + " -Denv=$configEnv")
)
</code>```

So when I run my docker command:

```<code>docker run -e "configEnv=test" --rm --name play-8080 -p 8080:9000 joesan/project-1:1.0-SNAPSHOT
</code>```

The appropriate application.test.conf gets picked up, loaded and my play application runs against it!

Body:
Before dockerizing my play web application, I was able to do the following when running:

Joes-Macbook:project-1 joe$ sbt -Dconfig.env=dev run

Where I can use one of the following of either dev, qa, prod to the config.env argument and my application will run using the corresponding application.dev.conf or application.qa.conf accordingly.

Now I have my application as a docker container which means that I need a way to inject my configuration file. How could I do it?

One way what I'm thinking is to have a shell script and use that as the Entrypoint. But not sure how this might work? Any suggestions?

So when I do

sbt docker:publishLocal

I get the following Dockerfile produced

FROM anapsix/alpine-java:8_server-jre_unlimited
MAINTAINER Joesan <myemail@email.com>
WORKDIR /opt/docker
ADD opt /opt
RUN ["chown", "-R", "daemon:daemon", "."]
USER daemon
ENTRYPOINT ["sh", "-c", "bin/project-1", "-Denv=$configEnv"]
CMD []
ENV configEnv default

I could not get the $configEnv resolved in my Scala application. This is how I run the produced docker image:

docker run -e "configEnv=crap" --rm --name play-8080 -p 8080:9000 joesan/project-1:1.0-SNAPSHOT

Body:
So with the help from VonC, and few changes to my build.sbt, I made it to work:

This is what I have in my build.sbt:

dockerCommands ++= Seq(
  Cmd("ENV", "configEnv", "default"), // This will be overridden when running!
  // This is the entrypoint where we can run the application against different environments
  ExecCmd("ENTRYPOINT", "sh", "-c", "bin/" + s"${executableScriptName.value}" + " -Denv=$configEnv")
)

So when I run my docker command:

docker run -e "configEnv=test" --rm --name play-8080 -p 8080:9000 joesan/project-1:1.0-SNAPSHOT

The appropriate application.test.conf gets picked up, loaded and my play application runs against it!


问:
What is the equivalent query for 'NOT IN' in Volt DB?
What is the equivalent query for 'NOT IN' in Volt DB?</p>

答:
VoltDB supports NOT IN syntax:</p>

```<code>1> create table foo (a integer);
Command succeeded.
2> insert into foo values (1);
(Returned 1 rows in 0.00s)
3> insert into foo values (2);
(Returned 1 rows in 0.00s)
4> insert into foo values (3);
(Returned 1 rows in 0.00s)
5> select * from foo where a not in (1,2);
A
--
 3

(Returned 1 rows in 0.00s)
</code>```

Body:
VoltDB supports NOT IN syntax:

1> create table foo (a integer);
Command succeeded.
2> insert into foo values (1);
(Returned 1 rows in 0.00s)
3> insert into foo values (2);
(Returned 1 rows in 0.00s)
4> insert into foo values (3);
(Returned 1 rows in 0.00s)
5> select * from foo where a not in (1,2);
A
--
 3

(Returned 1 rows in 0.00s)


问:
Controller Function Not called inside Directive
I have a controller function and I cannot call it inside the directive. I am trying hard. is there any thing Else i am failing to do? please tell me. I have included my code here. I have searched many places followed many answers and now I am stuck at this

(function () {
  var app = angular.module("featureModule", ['ngRoute']);
//

app.directive('myGoogleAutocomplete', function () {
 return {
  replace: true,
  require: 'ngModel',
  scope: {
   ngModel: '=',
   googleModel: '=',
   onSelect: '&?', // optional callback on selected successfully: 'onPostedBid(googleModel)'
  },
  template: '<input class="form-control" type="text" style="z-index: 100000;" autocomplete="on">',
  link: function ($scope, element, attrs, model)
  {

   var autocomplete = new google.maps.places.Autocomplete(element[0], googleOptions);

   google.maps.event.addListener(autocomplete, 'place_changed', function () {

    $scope.$apply(function () {
     var place = autocomplete.getPlace();
     if (!place.geometry)
      {
      // User entered the name of a Place that was not suggested and pressed the Enter key, or the Place Details request failed.
      model.$setValidity('place', false);
      //console.log("No details available for input: '" + place.name + "'");
      return;
     }

     $scope.googleModel = {};
     $scope.googleModel.placeId = place.place_id;
     $scope.googleModel.latitude = place.geometry.location.lat();
     $scope.googleModel.longitude = place.geometry.location.lng();
     $scope.googleModel.formattedAddress = place.formatted_address;
     if (place.address_components) {
      $scope.googleModel.address = [
       $scope.extract(place.address_components, 'route'),
       $scope.extract(place.address_components, 'street_number')
      ].join(' ');

     }

     model.$setViewValue(element.val());
     model.$setValidity('place', true);
     if (attrs.onSelect)
     {
     //how to call controller function here?
      $scope.onSelect({ $item: $scope.googleModel });
    }
    });
   });
  }
 }

});

app.controller("featureController", function($scope,$http,$rootScope,close,ModalService,NgMap) {
console.log($rootScope.permService);

$scope.onSelect=function(val)
{

 console.log(val);
}

});

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <my-google-autocomplete id="address"  name="address" ng-model="task.house_no" google-model="model.googleAddress"
                on-select="vm.onSelectGoogleAddress($item)" autocomplete="off" required>
              </my-google-autocomplete></code>```

答:
You can bind callback event by using elemet inside link function.

Here is the example . Hope it helps.

Let the controller having callback function from directive as below

```<code>  app.controller('MainCtrl', function($scope) {
   $scope.SayHello=function(id){
        alert(id);
   }
 });
</code>```

Let the directive

```<code>app.directive('dirDemo', function () {
    return {
    scope: {
        okCallback: '&'
    },
    template: '<input type="button" value="Click me" >',
        link: function (scope, element, attrs) {

    var param='from directive';

         element.bind('click', function () {
            scope.$apply(function () {
                scope.okCallback({id:param});
            });
        });
       }
      }
    });
</code>```

HTML is

```<code> <body ng-controller="MainCtrl">
   <div dir-demo
        ok-callback="SayHello(id)"
   </div>
 </body>
</code>```

Working plunker https://plnkr.co/edit/RbFjFfqR1MDDa3Jwe8Gq?p=preview

Body:
I have a controller function and I cannot call it inside the directive. I am trying hard. is there any thing Else i am failing to do? please tell me. I have included my code here. I have searched many places followed many answers and now I am stuck at this

(function () {
  var app = angular.module("featureModule", ['ngRoute']);
//

app.directive('myGoogleAutocomplete', function () {
 return {
  replace: true,
  require: 'ngModel',
  scope: {
   ngModel: '=',
   googleModel: '=',
   onSelect: '&?', // optional callback on selected successfully: 'onPostedBid(googleModel)'
  },
  template: '<input class="form-control" type="text" style="z-index: 100000;" autocomplete="on">',
  link: function ($scope, element, attrs, model)
  {

   var autocomplete = new google.maps.places.Autocomplete(element[0], googleOptions);

   google.maps.event.addListener(autocomplete, 'place_changed', function () {

    $scope.$apply(function () {
     var place = autocomplete.getPlace();
     if (!place.geometry)
      {
      // User entered the name of a Place that was not suggested and pressed the Enter key, or the Place Details request failed.
      model.$setValidity('place', false);
      //console.log("No details available for input: '" + place.name + "'");
      return;
     }

     $scope.googleModel = {};
     $scope.googleModel.placeId = place.place_id;
     $scope.googleModel.latitude = place.geometry.location.lat();
     $scope.googleModel.longitude = place.geometry.location.lng();
     $scope.googleModel.formattedAddress = place.formatted_address;
     if (place.address_components) {
      $scope.googleModel.address = [
       $scope.extract(place.address_components, 'route'),
       $scope.extract(place.address_components, 'street_number')
      ].join(' ');

     }

     model.$setViewValue(element.val());
     model.$setValidity('place', true);
     if (attrs.onSelect)
     {
     //how to call controller function here?
      $scope.onSelect({ $item: $scope.googleModel });
    }
    });
   });
  }
 }

});

app.controller("featureController", function($scope,$http,$rootScope,close,ModalService,NgMap) {
console.log($rootScope.permService);

$scope.onSelect=function(val)
{

 console.log(val);
}

});

 <my-google-autocomplete id="address"  name="address" ng-model="task.house_no" google-model="model.googleAddress"
                on-select="vm.onSelectGoogleAddress($item)" autocomplete="off" required>
              </my-google-autocomplete>

Body:
You can bind callback event by using elemet inside link function.

Here is the example . Hope it helps.

Let the controller having callback function from directive as below

  app.controller('MainCtrl', function($scope) {
   $scope.SayHello=function(id){
        alert(id);
   }
 });

Let the directive

app.directive('dirDemo', function () {
    return {
    scope: {
        okCallback: '&'
    },
    template: '<input type="button" value="Click me" >',
        link: function (scope, element, attrs) {

    var param='from directive';

         element.bind('click', function () {
            scope.$apply(function () {
                scope.okCallback({id:param});
            });
        });
       }
      }
    });

HTML is

 <body ng-controller="MainCtrl">
   <div dir-demo
        ok-callback="SayHello(id)"
   </div>
 </body>

Working plunker https://plnkr.co/edit/RbFjFfqR1MDDa3Jwe8Gq?p=preview


问:
How to convert an XML file to rows and columns using MariaDB on Xampp?
I have an XML file that looks like this:

```<code><users>

<row Id="4" Reputation="27228" CreationDate="2008-07-31T14:22:31.317"
DisplayName="abc"
LastAccessDate="2017-8:19:58.113"

WebsiteUrl="http://www.joeware.com/" Location="Nerk, NY"

AboutMe="<p>I am:</p>\n\n<ul>\n<li>the co-
founof <a href="http://om">Stack
Ext;/a></li>\n<li>the  of <a
href="http://wwwkot; rel="nofollow">Fog
Slt;/a></li>\n<li>the creatorrman
of the board of <a href="http://trello.com"
rel="nofollow">Trello</a></li>\n<li>owner
of Taco, the most f Husky on the UWest
Side.</li>\n</ul>\n\n<p>You can find me on
Twitter (as <a href="http://twitlsky"
rel="nofollow">@sky</a>) or on my rarely-updated
blog, <a href="http://joecom"
rel="nofollow">Software</a>.</p>\n"

Views="69136" UpVotes="785" DownVotes="96"

ProfileImageUrl="https://i.stam/C5gBG.jpg?s=128&g=1"
AccountId="4" />

</users>
</code>```

I wish to convert it into rows and columns so that it can be stored in a database. I tried the following on MariaDB:

```<code> LOAD XML LOCAL INFILE '<path>.xml'
-> INTO TABLE mytbl(id, rep, c_date, D_name,...);
</code>```

But it resulted in error ERROR 1148 (42000): The used command is not allowed with this MariaDB version . How do I go out to convert the xml file to a rows and tables?

I am using MariaDB on Xampp.

EDIT: version 10.1.19-MariaDB

答:
I can't reproduce the problem.

See test:

File: /path/to/file.xml

<users>
    <row Id="4"
         Reputation="27228"
         CreationDate="2008-07-31T14:22:31.317"
         DisplayName="abc"
         LastAccessDate="2017-8:19:58.113"
         WebsiteUrl="http://www.joeware.com/"
         Location="Nerk, NY"
         AboutMe="
I am:
\n\n
\n
the co-
founof Stack
Ext;/a>
\n
the  of Fog
Slt;/a>
\n
the creatorrman
of the board of Trello
\n
owner of Taco, the most f Husky on the UWest Side.
\n
\n\n
You can find me on Twitter (as @sky) or on my rarely-updated blog, Software.
\n"
         Views="69136"
         UpVotes="785"
         DownVotes="96"
         ProfileImageUrl="https://i.stam/C5gBG.jpg?s=128&g=1"
         AccountId="4" />
</users>
```

<p>MariaDB Command-Line:</p>

<pre class="lang-sql prettyprint-override"><code>MariaDB [_]> SELECT VERSION();
+-----------------+
| VERSION()       |
+-----------------+
| 10.1.19-MariaDB |
+-----------------+
1 row in set (0.00 sec)

MariaDB [_]> DROP TABLE IF EXISTS `mytbl`;
Query OK, 0 rows affected (0.00 sec)

MariaDB [_]> CREATE TABLE IF NOT EXISTS `mytbl` (
    -> `id` TEXT,
    -> `rep` TEXT,
    -> `c_date` TEXT,
    -> `D_name` TEXT,
    -> `LastAccessDate` TEXT,
    -> `WebsiteUrl` TEXT,
    -> `Location` TEXT,
    -> `AboutMe` TEXT,
    -> `Views` TEXT,
    -> `UpVotes` TEXT,
    -> `DownVotes` TEXT,
    -> `ProfileImageUrl` TEXT,
    -> `AccountId` TEXT
    -> );
Query OK, 0 rows affected (0.00 sec)

MariaDB [_]> LOAD XML LOCAL INFILE '/path/to/file.xml'
    -> INTO TABLE `mytbl` (
    -> @`Id`,
    -> @`Reputation`,
    -> @`CreationDate`,
    -> @`DisplayName`,
    -> @`LastAccessDate`,
    -> @`WebsiteUrl`,
    -> @`Location`,
    -> @`AboutMe`,
    -> @`Views`,
    -> @`UpVotes`,
    -> @`DownVotes`,
    -> @`ProfileImageUrl`,
    -> @`AccountId`
    -> )
    -> SET
    -> `id` = @`Id`,
    -> `rep` = @`Reputation`,
    -> `c_date` = @`CreationDate`,
    -> `D_name` = @`DisplayName`,
    -> `LastAccessDate` = @`LastAccessDate`,
    -> `WebsiteUrl` = @`WebsiteUrl`,
    -> `Location` = @`Location`,
    -> `AboutMe` = @`AboutMe`,
    -> `Views` = @`Views`,
    -> `UpVotes` = @`UpVotes`,
    -> `DownVotes` = @`DownVotes`,
    -> `ProfileImageUrl` = @`ProfileImageUrl`,
    -> `AccountId` = @`AccountId`;
Query OK, 1 row affected (0.00 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

MariaDB [_]> SELECT
    -> `id`,
    -> `rep`,
    -> `c_date`,
    -> `D_name`,
    -> `LastAccessDate`,
    -> `WebsiteUrl`,
    -> `Location`,
    -> `AboutMe`,
    -> `Views`,
    -> `UpVotes`,
    -> `DownVotes`,
    -> `ProfileImageUrl`,
    -> `AccountId`
    -> FROM
    -> `mytbl`\G
*************************** 1. row ***************************
             id: 4
            rep: 27228
         c_date: 2008-07-31T14:22:31.317
         D_name: abc
 LastAccessDate: 2017-8:19:58.113
     WebsiteUrl: http://www.joeware.com/
       Location: Nerk, NY
        AboutMe: <p>I am:</  p>\n\n<ul>\n<li>the co-
founof Stack
Ext;/a></li>\n<li>the  of Fog
Slt;/a></li>\n<li>the creatorrman
of the board of Trello</li>\n<li>owner of Taco, the most f Husky on the UWest Side.</li>\n</ul>\n\n<p>You can find me on Twitter (as href="http://twitlsky"
rel="nofollow">@sky) or on my rarely-updated blog, href="http://joecom"
rel="nofollow">Software.</p>\n
          Views: 69136
        UpVotes: 785
      DownVotes: 96
ProfileImageUrl: https://i.stam/C5gBG.jpg?s=128&g=1
      AccountId: 4
1 row in set (0.00 sec)
</code>```

See href="https://mariadb.com/kb/en/mariadb/load-xml/" rel="nofollow noreferrer">LOAD XML.

UPDATE

Check the value of the server system variable href="https://mariadb.com/kb/en/mariadb/server-system-variables/#local_infile" rel="nofollow noreferrer">local_infile:

```<code>MariaDB [_]> SHOW VARIABLES WHERE `Variable_name` = 'local_infile';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  | ON    |
+---------------+-------+
1 row in set (0.01 sec)
</code>```

Body:
I have an XML file that looks like this:

<users>

<row Id="4" Reputation="27228" CreationDate="2008-07-31T14:22:31.317"
DisplayName="abc"
LastAccessDate="2017-8:19:58.113"

WebsiteUrl="http://www.joeware.com/" Location="Nerk, NY"

AboutMe="
I am:

the co-
founof Stack
Ext;/a>

the  of Fog
Slt;/a>

the creatorrman
of the board of Trello

owner
of Taco, the most f Husky on the UWest
Side.

You can find me on
Twitter (as @sky) or on my rarely-updated
blog, Software.

"

Views="69136" UpVotes="785" DownVotes="96"

ProfileImageUrl="https://i.stam/C5gBG.jpg?s=128&g=1"
AccountId="4" />

</users>

I wish to convert it into rows and columns so that it can be stored in a database. I tried the following on MariaDB:

 LOAD XML LOCAL INFILE '<path>.xml'
-> INTO TABLE mytbl(id, rep, c_date, D_name,...);

But it resulted in error ERROR 1148 (42000): The used command is not allowed with this MariaDB version . How do I go out to convert the xml file to a rows and tables?

I am using MariaDB on Xampp.

EDIT: version 10.1.19-MariaDB

Body:
I can't reproduce the problem.

See test:

File: /path/to/file.xml

<users>
    <row Id="4"
         Reputation="27228"
         CreationDate="2008-07-31T14:22:31.317"
         DisplayName="abc"
         LastAccessDate="2017-8:19:58.113"
         WebsiteUrl="http://www.joeware.com/"
         Location="Nerk, NY"
         AboutMe="&lt;p&gt;I am:&lt;/  p&gt;&#xA;&#xA;&lt;ul&gt;&#xA;&lt;li&gt;the co-
founof &lt;a href=&quot;http://om&quot;&gt;Stack
Ext;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;the  of &lt;a
href=&quot;http://wwwkot; rel=&quot;nofollow&quot;&gt;Fog
Slt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;the creatorrman
of the board of &lt;a href=&quot;http://trello.com&quot;
rel=&quot;nofollow&quot;&gt;Trello&lt;/a&gt;&lt;/li&gt;&#xA;&lt;li&gt;owner of Taco, the most f Husky on the UWest Side.&lt;/li&gt;&#xA;&lt;/ul&gt;&#xA;&#xA;&lt;p&gt;You can find me on Twitter (as &lt;a href=&quot;http://twitlsky&quot;
rel=&quot;nofollow&quot;&gt;@sky&lt;/a&gt;) or on my rarely-updated blog, &lt;a href=&quot;http://joecom&quot;
rel=&quot;nofollow&quot;&gt;Software&lt;/a&gt;.&lt;/p&gt;&#xA;"
         Views="69136"
         UpVotes="785"
         DownVotes="96"
         ProfileImageUrl="https://i.stam/C5gBG.jpg?s=128&amp;g=1"
         AccountId="4" />
</users>

MariaDB Command-Line:

MariaDB [_]> SELECT VERSION();
+-----------------+
| VERSION()       |
+-----------------+
| 10.1.19-MariaDB |
+-----------------+
1 row in set (0.00 sec)

MariaDB [_]> DROP TABLE IF EXISTS `mytbl`;
Query OK, 0 rows affected (0.00 sec)

MariaDB [_]> CREATE TABLE IF NOT EXISTS `mytbl` (
    -> `id` TEXT,
    -> `rep` TEXT,
    -> `c_date` TEXT,
    -> `D_name` TEXT,
    -> `LastAccessDate` TEXT,
    -> `WebsiteUrl` TEXT,
    -> `Location` TEXT,
    -> `AboutMe` TEXT,
    -> `Views` TEXT,
    -> `UpVotes` TEXT,
    -> `DownVotes` TEXT,
    -> `ProfileImageUrl` TEXT,
    -> `AccountId` TEXT
    -> );
Query OK, 0 rows affected (0.00 sec)

MariaDB [_]> LOAD XML LOCAL INFILE '/path/to/file.xml'
    -> INTO TABLE `mytbl` (
    -> @`Id`,
    -> @`Reputation`,
    -> @`CreationDate`,
    -> @`DisplayName`,
    -> @`LastAccessDate`,
    -> @`WebsiteUrl`,
    -> @`Location`,
    -> @`AboutMe`,
    -> @`Views`,
    -> @`UpVotes`,
    -> @`DownVotes`,
    -> @`ProfileImageUrl`,
    -> @`AccountId`
    -> )
    -> SET
    -> `id` = @`Id`,
    -> `rep` = @`Reputation`,
    -> `c_date` = @`CreationDate`,
    -> `D_name` = @`DisplayName`,
    -> `LastAccessDate` = @`LastAccessDate`,
    -> `WebsiteUrl` = @`WebsiteUrl`,
    -> `Location` = @`Location`,
    -> `AboutMe` = @`AboutMe`,
    -> `Views` = @`Views`,
    -> `UpVotes` = @`UpVotes`,
    -> `DownVotes` = @`DownVotes`,
    -> `ProfileImageUrl` = @`ProfileImageUrl`,
    -> `AccountId` = @`AccountId`;
Query OK, 1 row affected (0.00 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

MariaDB [_]> SELECT
    -> `id`,
    -> `rep`,
    -> `c_date`,
    -> `D_name`,
    -> `LastAccessDate`,
    -> `WebsiteUrl`,
    -> `Location`,
    -> `AboutMe`,
    -> `Views`,
    -> `UpVotes`,
    -> `DownVotes`,
    -> `ProfileImageUrl`,
    -> `AccountId`
    -> FROM
    -> `mytbl`\G
*************************** 1. row ***************************
             id: 4
            rep: 27228
         c_date: 2008-07-31T14:22:31.317
         D_name: abc
 LastAccessDate: 2017-8:19:58.113
     WebsiteUrl: http://www.joeware.com/
       Location: Nerk, NY
        AboutMe: <p>I am:</  p>&#xA;&#xA;<ul>&#xA;<li>the co-
founof <a href="http://om">Stack
Ext;/a></li>&#xA;<li>the  of <a
href="http://wwwkot; rel="nofollow">Fog
Slt;/a></li>&#xA;<li>the creatorrman
of the board of <a href="http://trello.com"
rel="nofollow">Trello</a></li>&#xA;<li>owner of Taco, the most f Husky on the UWest Side.</li>&#xA;</ul>&#xA;&#xA;<p>You can find me on Twitter (as <a href="http://twitlsky"
rel="nofollow">@sky</a>) or on my rarely-updated blog, <a href="http://joecom"
rel="nofollow">Software</a>.</p>&#xA;
          Views: 69136
        UpVotes: 785
      DownVotes: 96
ProfileImageUrl: https://i.stam/C5gBG.jpg?s=128&g=1
      AccountId: 4
1 row in set (0.00 sec)

See LOAD XML.

UPDATE

Check the value of the server system variable local_infile:

MariaDB [_]> SHOW VARIABLES WHERE `Variable_name` = 'local_infile';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  | ON    |
+---------------+-------+
1 row in set (0.01 sec)


问:
Will performFetchWithCompletionHandler be called if the app has been terminated
It's surprisingly difficult to find a definitive answer to this; couldn't find it mentioned in the Apple documentation and couldn't find a definite yes/no after searching past questions.

The question is simple - if the app requests a background fetch to be performed after N time, then the user terminates the app. Will the OS still launch the app into the background to perform the background fetch?

答:
Reading the Apple documentation here I found this text snippet which should explain your question:

The techniques offered by iOS fall into three categories:

```<code>    Apps that start a short task in the foreground can ask for time to finish that task when the app moves to the background.

    **Apps that initiate downloads in the foreground can hand off management of those downloads to the system, thereby allowing the app to be suspended or terminated while the download continues.**

    Apps that need to run in the background to support specific types of tasks can declare their support for one or more background execution modes.
</code>```

The second option is exactly about downloading the data, which can be delegated to the system even if the can be terminated.

Body:
Reading the Apple documentation here I found this text snippet which should explain your question:

The techniques offered by iOS fall into three categories:

    Apps that start a short task in the foreground can ask for time to finish that task when the app moves to the background.

    **Apps that initiate downloads in the foreground can hand off management of those downloads to the system, thereby allowing the app to be suspended or terminated while the download continues.**

    Apps that need to run in the background to support specific types of tasks can declare their support for one or more background execution modes.

The second option is exactly about downloading the data, which can be delegated to the system even if the can be terminated.


问:
Looking for a simple "WCF+ACS+Windows Azure" walkthrough
I just spent the last two hours trying to walk through Microsoft's "Web Services and Identity in Windows Azure Exercise 1: Using Windows Identity Foundation with a WCF Service in Windows Azure" which purports to show how to host a secured WCF service in Azure.

Unfortunately, the walkthrough is ridiculously complicated with a whopping 151 steps.  I've tried to complete the first part of the walkthrough 3 separate times but without any luck.  I'm pretty sure I'm following the instructions exactly as written but there's so much subtlety in there (certificate setup, configuration chaanges, etc.) that it's likely that I'm missing a critical detail.  In either case 151 steps is clearly an order of magnitude too difficult for mere mortals to follow.

Anyway, any help in this rgard would be greatly appreciated....

答:
Check out the BidNow sample. That is a lot less complicated. http://code.msdn.microsoft.com/BidNowSample

Also, check out the samples on http://acs.codeplex.com/


问:
How can I instantiate Services in MVC
I have an ASP.Net MVC 5 project using an Onion Architecture where I have repositories and services and I use Services from my controller. In my controller, I need to use the IGenericService variables I created, but how can I instantiate these variables? The problem being that my Service needs a IRepository for its constructor, and in turn IRepositoryneeds to be initialized too.

What I tried was AddSingleton(IGenericService<MyClass>, GenericService<MyClass>) in the method ConfigureServices(IServiceCollection services) in the Startup.cs file but it doesn't seem to help.

Edit As suggested my @Nkosi I am trying to resolve dependencies and followed this tutorial to do so : http://scottdorman.github.io/2016/03/17/integrating-asp.net-core-dependency-injection-in-mvc-4/ . My problem now is that I get an invalid operation exception  :

Unable to resolve service for type 'Repository.PrincipalServerContext' while attempting to activate 'WebExploitv2.Controllers.NavigationController'

My startup.cs looks like this now:

```<code>public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var services = new ServiceCollection();
        ConfigureAuth(app);
        ConfigureServices(services);
        var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());
        DependencyResolver.SetResolver(resolver);
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllerAsServices(typeof(Startup).Assembly.GetExportedTypes()
            .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
            .Where(t => typeof(IController).IsAssignableFrom(t)
                || t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));

        services.AddSingleton<IGenericRepository<Web_Documents>, GenericRepository<Web_Documents>>();
        services.AddSingleton<IGenericService<Web_Documents>, GenericService<Web_Documents>>();

        services.AddSingleton<IGenericRepository<Web_Categories>, GenericRepository<Web_Categories>>();
        services.AddSingleton<IGenericService<Web_Categories>, GenericService<Web_Categories>>();

        services.AddSingleton<IGenericService<Web_User_joint_Profils>, GenericService<Web_User_joint_Profils>>();
        services.AddSingleton<IGenericRepository<Web_User_joint_Profils>, GenericRepository<Web_User_joint_Profils>>();

        services.AddSingleton<IGenericRepository<Web_Group_joint_Profils>, GenericRepository<Web_Group_joint_Profils>>();
        services.AddSingleton<IGenericService<Web_Group_joint_Profils>, GenericService<Web_Group_joint_Profils>>();

        services.AddSingleton<IMenuService, MenuService>();
        services.AddSingleton<IMenuRepository, MenuRepository>();
    }
}
</code>```

I also added a DefaultDependencyResolver class :

```<code>public class DefaultDependencyResolver : IDependencyResolver
{
    protected IServiceProvider serviceProvider;

    public DefaultDependencyResolver(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    public object GetService(Type serviceType)
    {
        return this.serviceProvider.GetService(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return this.serviceProvider.GetServices(serviceType);
    }
}
</code>```

Next I have the ServiceProviderExtension class:

```<code>public static class ServiceProviderExtensions
{
    public static IServiceCollection AddControllerAsServices(this IServiceCollection services, IEnumerable<Type> controllerTypes)
    {
        foreach(var type in controllerTypes)
        {
            services.AddTransient(type);
        }
        return services;
    }
}
</code>```

Finally in my controller, I have Interfaces of GenericService which allows me to access Repository and in turn access my DB. I use the followed interfaces for instantiation

```<code>    private IGenericService<Web_User_joint_Profils> _userProfileService;
    private IGenericService<Web_Group_joint_Profils> _groupProfileService;
    private IGenericService<Web_Categories> _categoryService;
    PrincipalServerContext context;
    private NavigationController(PrincipalServerContext context, IGenericService<Web_User_joint_Profils> userProfileService, IGenericService<Web_Group_joint_Profils> groupProfileService, IGenericService<Web_Categories> categoryService)
    {
        _context = context;
        _userProfileService = userProfileService;
        _groupProfileService = groupProfileService;
        _categoryService = categoryService;
    }
</code>```

Note that My GenericService takes POCOs as generics in order to know where to look in Database. So for each of these in Startup.ConfigureServices(IServiceCollection services) I added an AddSingleton method to register these services and repositories with the DI container.
Any ideas why I get this exception?

答:
It is rather simple, using IServiceCollection instance that is being passed to ConfigureServices method by the run time you do:

```<code>services.AddSingleton<IAbstraction, ConcreteImplementation>();
</code>```

or, for a transient lifetime scope:

```<code>services.AddTransient<IAbstraction, ConcreteImplementation>();
</code>```

or, in your case:

```<code>services.AddSingleton<IGenericService<MyClass>, GenericService<MyClass>>();
</code>```

Title: How can I instantiate Services in MVC

Body:
I have an ASP.Net MVC 5 project using an Onion Architecture where I have repositories and services and I use Services from my controller. In my controller, I need to use the IGenericService variables I created, but how can I instantiate these variables? The problem being that my Service needs a IRepository for its constructor, and in turn IRepositoryneeds to be initialized too.

What I tried was AddSingleton(IGenericService<MyClass>, GenericService<MyClass>) in the method ConfigureServices(IServiceCollection services) in the Startup.cs file but it doesn't seem to help.

Edit As suggested my @Nkosi I am trying to resolve dependencies and followed this tutorial to do so : http://scottdorman.github.io/2016/03/17/integrating-asp.net-core-dependency-injection-in-mvc-4/ . My problem now is that I get an invalid operation exception  :

Unable to resolve service for type 'Repository.PrincipalServerContext' while attempting to activate 'WebExploitv2.Controllers.NavigationController'

My startup.cs looks like this now:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var services = new ServiceCollection();
        ConfigureAuth(app);
        ConfigureServices(services);
        var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());
        DependencyResolver.SetResolver(resolver);
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllerAsServices(typeof(Startup).Assembly.GetExportedTypes()
            .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
            .Where(t => typeof(IController).IsAssignableFrom(t)
                || t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));

        services.AddSingleton<IGenericRepository<Web_Documents>, GenericRepository<Web_Documents>>();
        services.AddSingleton<IGenericService<Web_Documents>, GenericService<Web_Documents>>();

        services.AddSingleton<IGenericRepository<Web_Categories>, GenericRepository<Web_Categories>>();
        services.AddSingleton<IGenericService<Web_Categories>, GenericService<Web_Categories>>();

        services.AddSingleton<IGenericService<Web_User_joint_Profils>, GenericService<Web_User_joint_Profils>>();
        services.AddSingleton<IGenericRepository<Web_User_joint_Profils>, GenericRepository<Web_User_joint_Profils>>();

        services.AddSingleton<IGenericRepository<Web_Group_joint_Profils>, GenericRepository<Web_Group_joint_Profils>>();
        services.AddSingleton<IGenericService<Web_Group_joint_Profils>, GenericService<Web_Group_joint_Profils>>();

        services.AddSingleton<IMenuService, MenuService>();
        services.AddSingleton<IMenuRepository, MenuRepository>();
    }
}

I also added a DefaultDependencyResolver class :

public class DefaultDependencyResolver : IDependencyResolver
{
    protected IServiceProvider serviceProvider;

    public DefaultDependencyResolver(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    public object GetService(Type serviceType)
    {
        return this.serviceProvider.GetService(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return this.serviceProvider.GetServices(serviceType);
    }
}

Next I have the ServiceProviderExtension class:

public static class ServiceProviderExtensions
{
    public static IServiceCollection AddControllerAsServices(this IServiceCollection services, IEnumerable<Type> controllerTypes)
    {
        foreach(var type in controllerTypes)
        {
            services.AddTransient(type);
        }
        return services;
    }
}

Finally in my controller, I have Interfaces of GenericService which allows me to access Repository and in turn access my DB. I use the followed interfaces for instantiation

    private IGenericService<Web_User_joint_Profils> _userProfileService;
    private IGenericService<Web_Group_joint_Profils> _groupProfileService;
    private IGenericService<Web_Categories> _categoryService;
    PrincipalServerContext context;
    private NavigationController(PrincipalServerContext context, IGenericService<Web_User_joint_Profils> userProfileService, IGenericService<Web_Group_joint_Profils> groupProfileService, IGenericService<Web_Categories> categoryService)
    {
        _context = context;
        _userProfileService = userProfileService;
        _groupProfileService = groupProfileService;
        _categoryService = categoryService;
    }

Note that My GenericService takes POCOs as generics in order to know where to look in Database. So for each of these in Startup.ConfigureServices(IServiceCollection services) I added an AddSingleton method to register these services and repositories with the DI container.
Any ideas why I get this exception?

Body:
It is rather simple, using IServiceCollection instance that is being passed to ConfigureServices method by the run time you do:

services.AddSingleton<IAbstraction, ConcreteImplementation>();

or, for a transient lifetime scope:

services.AddTransient<IAbstraction, ConcreteImplementation>();

or, in your case:

services.AddSingleton<IGenericService<MyClass>, GenericService<MyClass>>();


问:
Error in x %||% list() : argument "p" is missing, with no default
I'm trying to get the status of over 100 sites using the httr library but i keep getting this error:

```<code>Error in x %||% list() : argument "p" is missing, with no default.
</code>```

I have a dataframe with all the site names. this is the line that's giving me the error

```<code>for(i in names)
{

  if(i != "")
  {
    URL <- GET(paste("http://",i,"", sep = "" ),set_config(config(ssl_verifypeer = 0L)),timeout(500))

    if(status_code(URL) == "200")
    {
      r <- "Active"
    }
    else
    {
      r <- "Not active"
    }
    r
    print(paste(i,r))
    all_stat <- rbind(all_stat,r)
  }

}
</code>```

答: I had the same error; I fixed by removing set_config(config(ssl_verifypeer = 0L)), but that may not work for your request.

Body:
I'm trying to get the status of over 100 sites using the httr library but i keep getting this error:

Error in x %||% list() : argument "p" is missing, with no default.

I have a dataframe with all the site names. this is the line that's giving me the error

for(i in names)
{

  if(i != "")
  {
    URL <- GET(paste("http://",i,"", sep = "" ),set_config(config(ssl_verifypeer = 0L)),timeout(500))

    if(status_code(URL) == "200")
    {
      r <- "Active"
    }
    else
    {
      r <- "Not active"
    }
    r
    print(paste(i,r))
    all_stat <- rbind(all_stat,r)
  }

}


问:
Keras - Making two predictions from one neural network
I'm trying to combine two outputs that are produced by the same network that makes predictions on a 4 class task and a 10 class task. Then I look to combine these outputs to give a length 14 array which I use as my end target.

While this seems to work actively the predictions are always for one class so it produces a probability dist which is only concerned with selecting 1 out of the 14 options instead of 2. What I actually need it to do is to provide 2 predictions, one for each class. I want this all to be produced by the same model.

```<code>input = Input(shape=(100, 100), name='input')
lstm = LSTM(128, input_shape=(100, 100)))(input)

output1 = Dense(len(4), activation='softmax', name='output1')(lstm)
output2 = Dense(len(10), activation='softmax', name='output2')(lstm)

output3 = concatenate([output1, output2])

model = Model(inputs=[input], outputs=[output3])
</code>```

My issue here is determining an appropriate loss function and method of prediction? For prediction I can simply grab the output of each layer after the softmax however I'm unsure how to set the loss function for each of these things to be trained.

Any ideas?

Thanks a lot

答:
You don't need to concatenate the outputs, your model can have two outputs:

```<code>input = Input(shape=(100, 100), name='input')
lstm = LSTM(128, input_shape=(100, 100)))(input)

output1 = Dense(len(4), activation='softmax', name='output1')(lstm)
output2 = Dense(len(10), activation='softmax', name='output2')(lstm)

model = Model(inputs=[input], outputs=[output1, output2])
</code>```

Then to train this model, you typically use two losses that are weighted to produce a single loss:

```<code>model.compile(optimizer='sgd', loss=['categorical_crossentropy',
              'categorical_crossentropy'], loss_weights=[0.2, 0.8])
</code>```

Just make sure to format your data right, as now each input sample corresponds to two output labeled samples. For more information check the Functional API Guide.

Body:
I'm trying to combine two outputs that are produced by the same network that makes predictions on a 4 class task and a 10 class task. Then I look to combine these outputs to give a length 14 array which I use as my end target.

While this seems to work actively the predictions are always for one class so it produces a probability dist which is only concerned with selecting 1 out of the 14 options instead of 2. What I actually need it to do is to provide 2 predictions, one for each class. I want this all to be produced by the same model.

input = Input(shape=(100, 100), name='input')
lstm = LSTM(128, input_shape=(100, 100)))(input)

output1 = Dense(len(4), activation='softmax', name='output1')(lstm)
output2 = Dense(len(10), activation='softmax', name='output2')(lstm)

output3 = concatenate([output1, output2])

model = Model(inputs=[input], outputs=[output3])

My issue here is determining an appropriate loss function and method of prediction? For prediction I can simply grab the output of each layer after the softmax however I'm unsure how to set the loss function for each of these things to be trained.

Any ideas?

Thanks a lot

Body:
You don't need to concatenate the outputs, your model can have two outputs:

input = Input(shape=(100, 100), name='input')
lstm = LSTM(128, input_shape=(100, 100)))(input)

output1 = Dense(len(4), activation='softmax', name='output1')(lstm)
output2 = Dense(len(10), activation='softmax', name='output2')(lstm)

model = Model(inputs=[input], outputs=[output1, output2])

Then to train this model, you typically use two losses that are weighted to produce a single loss:

model.compile(optimizer='sgd', loss=['categorical_crossentropy',
              'categorical_crossentropy'], loss_weights=[0.2, 0.8])

Just make sure to format your data right, as now each input sample corresponds to two output labeled samples. For more information check the Functional API Guide.


问:
Visual Basic Multiple Button to show Mulitple Picturebox/Richtext
So here's what I want. When i click on a button it will show 1 PictureBox and 1 RichtextBox (Which is btw Visible=False so that it will not show unless clicked when the program is opened) as you can see here on my screenshot:
enter image description here

But when I click other button it doesn't change it stays with the first button i clicked when i opened the program. I really don't know the code since I'm new with VB.

Here's the code I used:

```<code>    Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        PictureBox1.Visible = True
        RichTextBox1.Visible = True
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        PictureBox2.Visible = True
        RichTextBox2.Visible = True
    End Sub
End Class
</code>```

Thanks!

答:
Since (I guess) both of the images are right on top of each other, you need to set the first image to invisible again. If not controlled which image is on top depends on the order the images where added.

You could do something like this :

```<code>Private Sub hideElements()
    For i as Integer = 1 to 6
        Me.Controls("PictureBox" & i).Visible = False
        Me.Controls("RichTextBox" & i).Visible = False
    Next
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Call hideElements()

    PictureBox1.Visible = True
    RichTextBox1.Visible = True
End Sub
</code>```

This loop sets all PictureBox1 - Picturebox6 and RichtextBox1 - RichTextBox6 to invisible, now you can set the one you want to show to visible.

So just call hideElements at the beginning of all of your button handler.

If u want to change the amount of images/richtextboxes, you only need to adjust the 6 in the loop.

Hope I could help.

Body:
So here's what I want. When i click on a button it will show 1 PictureBox and 1 RichtextBox (Which is btw Visible=False so that it will not show unless clicked when the program is opened) as you can see here on my screenshot:
enter image description here

But when I click other button it doesn't change it stays with the first button i clicked when i opened the program. I really don't know the code since I'm new with VB.

Here's the code I used:

    Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        PictureBox1.Visible = True
        RichTextBox1.Visible = True
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        PictureBox2.Visible = True
        RichTextBox2.Visible = True
    End Sub
End Class

Thanks!

Body:
Since (I guess) both of the images are right on top of each other, you need to set the first image to invisible again. If not controlled which image is on top depends on the order the images where added.

You could do something like this :

Private Sub hideElements()
    For i as Integer = 1 to 6
        Me.Controls("PictureBox" & i).Visible = False
        Me.Controls("RichTextBox" & i).Visible = False
    Next
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Call hideElements()

    PictureBox1.Visible = True
    RichTextBox1.Visible = True
End Sub

This loop sets all PictureBox1 - Picturebox6 and RichtextBox1 - RichTextBox6 to invisible, now you can set the one you want to show to visible.

So just call hideElements at the beginning of all of your button handler.

If u want to change the amount of images/richtextboxes, you only need to adjust the 6 in the loop.

Hope I could help.


问:
Input View Not Changing For UITextField
I have created two buttons. One called Weight and the other Age. Both of these buttons set the same UITextField as a first responder. However, if the Weight button is touched, the keyboard type becomes a number pad; if the Age button is touched, the keyboard type becomes a UIPickerVIew. Here is the code below:

```<code>@IBOutlet var weightButton: UIButton!
@IBOutlet var ageButton: UIButton!
@IBOutlet var userInput: UITextField!

let agePicker = UIPickerView()
let ageAsString =  ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"]
var selectedAge: Double?

override func viewDidLoad() {
    super.viewDidLoad()
    createAgePicker()
}

//ButtonsClicked
@IBAction func weightSearch(_ sender: Any) {
    wieghtResponse()
}

@IBAction func ageSearch(_ sender: Any) {
    ageResponse()
}

func userInputResponse() {
    userInput.inputView = nil
    if weightButton.isTouchInside {
        userInput.inputView = nil
        userInput.keyboardType = UIKeyboardType.numberPad
        userInput.becomeFirstResponder()
    } else if ageButton.isTouchInside {
        userInput.inputView = nil
        userInput.inputView = agePicker
        userInput.becomeFirstResponder()
    }

//CreateAgePicker
func createAgePicker() {
    agePicker.delegate = self
    agePicker.backgroundColor = .white
    agePicker.tintColor = .clear
}
//Components
@available(iOS 2.0, *)
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
//Rows
@available(iOS 2.0, *)
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return ageAsString.count
}
//Labels
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return ageAsString[row]
}
</code>```

The issue I am having is that when I click on the Age button, the picker view loads. However, when I click back on the Weight button, the input view doesn't revert back to a number pad and stays as the picker. Any advice?

答:
Try </p>

```<code>func wieghtResponse(){
    userInput.inputView = nil // reset your input view for weight input
    userInput.keyboardType = UIKeyboardType.numberPad
    userInput.becomeFirstResponder()
}
</code>```

Title: Input View Not Changing For UITextField

Body:
I have created two buttons. One called Weight and the other Age. Both of these buttons set the same UITextField as a first responder. However, if the Weight button is touched, the keyboard type becomes a number pad; if the Age button is touched, the keyboard type becomes a UIPickerVIew. Here is the code below:

@IBOutlet var weightButton: UIButton!
@IBOutlet var ageButton: UIButton!
@IBOutlet var userInput: UITextField!

let agePicker = UIPickerView()
let ageAsString =  ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"]
var selectedAge: Double?

override func viewDidLoad() {
    super.viewDidLoad()
    createAgePicker()
}

//ButtonsClicked
@IBAction func weightSearch(_ sender: Any) {
    wieghtResponse()
}

@IBAction func ageSearch(_ sender: Any) {
    ageResponse()
}

func userInputResponse() {
    userInput.inputView = nil
    if weightButton.isTouchInside {
        userInput.inputView = nil
        userInput.keyboardType = UIKeyboardType.numberPad
        userInput.becomeFirstResponder()
    } else if ageButton.isTouchInside {
        userInput.inputView = nil
        userInput.inputView = agePicker
        userInput.becomeFirstResponder()
    }

//CreateAgePicker
func createAgePicker() {
    agePicker.delegate = self
    agePicker.backgroundColor = .white
    agePicker.tintColor = .clear
}
//Components
@available(iOS 2.0, *)
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
//Rows
@available(iOS 2.0, *)
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return ageAsString.count
}
//Labels
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return ageAsString[row]
}

The issue I am having is that when I click on the Age button, the picker view loads. However, when I click back on the Weight button, the input view doesn't revert back to a number pad and stays as the picker. Any advice?

Body:
Try

func wieghtResponse(){
    userInput.inputView = nil // reset your input view for weight input
    userInput.keyboardType = UIKeyboardType.numberPad
    userInput.becomeFirstResponder()
}