问:
Stop music of from Other APP
If in background the default music player is running and if I use my app to play music, both runs simultaneously.

Is there a way to stop background music player.

答:
You will have to implement Mediaplayer's AudioFocus. To do this you need to get an instance of the AudioManager. Once you have the instance you can then use requestAudioFocus.

```<code>AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(focusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        Log.d("AudioFocus", "Audio focus received");
        return true;
    } else {
        Log.d("AudioFocus", "Audio focus NOT received");
        return false;
    }
}
</code>```

AudioFocus is assigned to each application that requests it. When your app receives focus it can pass an AudioManager.OnAudioFocusChangeListener which provides callbacks for when an focus change happens.

If app gains audio focus, and another app requests audio focus, the focus will be given to the other app. Android will notify your app via an OnAudioFocusChangeListener so that your app can respond to the change. To receive focus events, you need to pass an instance of AudioManager.OnAudioFocusChangeListener like this.

```<code>private OnAudioFocusChangeListener focusChangeListener =
          new OnAudioFocusChangeListener() {
                  public void onAudioFocusChange(int focusChange) {
                             AudioManager am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
                    switch (focusChange) {

                           case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
                           // Lower the volume while ducking.
                           mediaPlayer.setVolume(0.2f, 0.2f);
                           break;
                           case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
                           pause();
                           break;

                           case (AudioManager.AUDIOFOCUS_LOSS) :
                           stop();
                           ComponentName component =new ComponentName(AudioPlayerActivity.this,MediaControlReceiver.class);
                           am.unregisterMediaButtonEventReceiver(component);
                           break;

                           case (AudioManager.AUDIOFOCUS_GAIN) :
                           // Return the volume to normal and resume if paused.
                           mediaPlayer.setVolume(1f, 1f);
                           mediaPlayer.start();
                           break;
                           default: break;
}
}
};
</code>```

Reference Documentation: https://developer.android.com/guide/topics/media-apps/volume-and-earphones.html

Title: Stop music of from Other APP

Body:
You will have to implement Mediaplayer's AudioFocus. To do this you need to get an instance of the AudioManager. Once you have the instance you can then use requestAudioFocus.

AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(focusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        Log.d("AudioFocus", "Audio focus received");
        return true;
    } else {
        Log.d("AudioFocus", "Audio focus NOT received");
        return false;
    }
}

AudioFocus is assigned to each application that requests it. When your app receives focus it can pass an AudioManager.OnAudioFocusChangeListener which provides callbacks for when an focus change happens.

If app gains audio focus, and another app requests audio focus, the focus will be given to the other app. Android will notify your app via an OnAudioFocusChangeListener so that your app can respond to the change. To receive focus events, you need to pass an instance of AudioManager.OnAudioFocusChangeListener like this.

private OnAudioFocusChangeListener focusChangeListener =
          new OnAudioFocusChangeListener() {
                  public void onAudioFocusChange(int focusChange) {
                             AudioManager am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
                    switch (focusChange) {

                           case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
                           // Lower the volume while ducking.
                           mediaPlayer.setVolume(0.2f, 0.2f);
                           break;
                           case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
                           pause();
                           break;

                           case (AudioManager.AUDIOFOCUS_LOSS) :
                           stop();
                           ComponentName component =new ComponentName(AudioPlayerActivity.this,MediaControlReceiver.class);
                           am.unregisterMediaButtonEventReceiver(component);
                           break;

                           case (AudioManager.AUDIOFOCUS_GAIN) :
                           // Return the volume to normal and resume if paused.
                           mediaPlayer.setVolume(1f, 1f);
                           mediaPlayer.start();
                           break;
                           default: break;
}
}
};

Reference Documentation: https://developer.android.com/guide/topics/media-apps/volume-and-earphones.html


来源: stackexchange

问:
Android: What is the minimum and maximum radius for geofence
I am working on an Android app which makes use of geofence. I want user to decide the radius of geofence. But I want to know what is the minimum and maximum radius for the geofence so that app will work fine. </p>

答:
For best results, the minimum radius of the geofence should be set between 100 - 150 meters.

=> When Wi-Fi is available location accuracy is usually between 20 - 50 meters.

=> When indoor location is available, the accuracy range can be as small as 5 meters. Unless you know indoor location is available inside the geofence, assume that Wi-Fi location accuracy is about 50 meters.

Check and read developer site

https://developer.android.com/training/location/geofencing.html

You can set 50-100 meters as minimum for all conditions.

ContentLicense: CC BY-SA 3.0


问:
Is it possible to block Tor users?
Would it be possible to block Tor users? (https://www.torproject.org/)

Due to the nature of the site I run I should do all I can to stop multiple accounts and block certain locations. Tor is worse than proxies -  a total nightmare...

答:
Here (see https://github.com/RD17/DeTor) is a simple REST API to determine whether a request was made from TOR network or not.

The request is:
curl -X GET http://detor.ambar.cloud/.

The response is:

{
  "sourceIp": "104.200.20.46",
  "destIp": "89.207.89.82",
  "destPort": "8080",
  "found": true
}
```

As a bonus you can add a badge to your site to detect whether a user comes from TOR or not:

Title: Is it possible to block Tor users?

Body:
Here (see https://github.com/RD17/DeTor) is a simple REST API to determine whether a request was made from TOR network or not.

The request is:
curl -X GET http://detor.ambar.cloud/.

The response is:

{
  "sourceIp": "104.200.20.46",
  "destIp": "89.207.89.82",
  "destPort": "8080",
  "found": true
}

As a bonus you can add a badge to your site to detect whether a user comes from TOR or not:

<img src="http://detor.ambar.cloud/badge" />

ContentLicense: CC BY-SA 4.0


问:
Getting the home tile rearranging effect in Windows Phone 7
I have a ListBox with items that I'd like the user to be able to re-arrange, in a similar fashion to how the tiles on the home screen can be re-arranged. Is there a control or some easy way to implement it, or will I have to roll it myself?

答: You'll need to roll this yourself. At this stage there has not been a control released that implements this out of the box.</p>

ContentLicense: CC BY-SA 2.5


问:
Is there a way to catch notification PendingIntent?
As title says - Is there a way to catch notification PendingIntent?

I want to trigger markNotification(id) from single spot in my application to avoid repetition. But I am unable to find a way to catch PendingIntent that is triggering my Activity. Maybe there is a way to do it some other way than catching PendingIntent?

Context

I've added schemes to my Activity and I have working FirebaseMessagingService which is responsible for creating my Notification and its triggers. My PendingIntent is holding Intent with URI that will trigger required Activity.

答:
So I found a way to resolve my dillema.

I've added to my PendingIntent class via intent.setClass() to forward it to my custom BroadcastReceiver. Then in this receiver I trigger my method responsible for marking the notification in the database. And finnaly I trigger startActivity() with my original intent that will start specific Activity with URI held inside intent.getData().


问:
Possible to use GroupBy in ElasticSearch querystring?
I have a few records in my elasticsearch collection and i want to use a GroupBy aggregation in elasticsearch querystring.

I want to know if it is possible, because i tried to google it always give result about this

i want to use this something like this in the query string , which can
give me records in the group.

For i.e.

```<code>http://localhost:9200/_all/tweets/_count?q=user:Pu*+user:Kim*
</code>```

This will give me count of all the records which has name starts from Pu and Kim,

But i want to know that how many records are there has name starting with Pu
and Kim,

答:
aggregations need to be specified in addition in the search request, you cannot specify them as part of a query string query.

You could also just execute two queries to find out this particular requirement...

Body:
I have a few records in my elasticsearch collection and i want to use a GroupBy aggregation in elasticsearch querystring.

I want to know if it is possible, because i tried to google it always give result about this

i want to use this something like this in the query string , which can
give me records in the group.

For i.e.

http://localhost:9200/_all/tweets/_count?q=user:Pu*+user:Kim*

This will give me count of all the records which has name starts from Pu and Kim,

But i want to know that how many records are there has name starting with Pu
and Kim,


问:
What is the most common waste of computing power in Javascript?
We've all seen people who do this:

```<code>jQuery('a').each(function(){
    jQuery(this)[0].innerHTML += ' proccessed';
});

function letsPoluteNS() {
    polute = '';
    for (morePolution = 0; morePolution < arguments.length; morePolution++)
        polute.join(arguments[morePolution]);
    return polute;
}
</code>```

and so on. I was wondering what people have seen the most common JavaScript/jQuery technique that is slowing down the page and/or wasting time for the JavaScript engine.

I know that this question may not seem to fit into what's an accepted question, yet I'm asking "what is the most common accepted waste?"

答: not declaring your vars from the getgo so they are cached, not using closures and repeating x number of the same function/call/etc but only changing id or class for each, using eval(). </p>

Body:
We've all seen people who do this:

jQuery('a').each(function(){
    jQuery(this)[0].innerHTML += ' proccessed';
});

function letsPoluteNS() {
    polute = '';
    for (morePolution = 0; morePolution < arguments.length; morePolution++)
        polute.join(arguments[morePolution]);
    return polute;
}

and so on. I was wondering what people have seen the most common JavaScript/jQuery technique that is slowing down the page and/or wasting time for the JavaScript engine.

I know that this question may not seem to fit into what's an accepted question, yet I'm asking "what is the most common accepted waste?"


问:
Redirect page doesn't automatically close after successful OAuth authorization
I am following the below tutorial: https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-windows-store-dotnet-get-started-users . I set up the OAuth (via Google) and the created the windows 10 app.
When I click on authenticate button, it takes me to Google site and authenticates me. Then it redirects me to a happy page. This happy page has not buttons. Closing the happy page gives me a [User cancelled login exception]. There is no way to proceed ahead after this. What am I missing here?</p>

答:
I set up the OAuth (via Google) and the created the windows 10 app. When I click on authenticate button, it takes me to Google site and authenticates me. Then it redirects me to a happy page. This happy page has not buttons. Closing the happy page gives me a [User cancelled login exception].

Per my understanding, you are creating a UWP project. I followed Add authentication to your Windows app and Configure App Service to use Google login, then I download the quick start project to check this issue. I could login successfully with my Google account as follows:

Here is my code sample, you could refer to AzureMobileApp-UWP.


问:
Update a Postgres daterange with jOOQ
I try to update a Postgres daterange. Whatever I try it isn't working. Currently I get

Error:(51, 17) java: reference to set is ambiguous
    both method set(org.jooq.Field,T) in org.jooq.UpdateSetStep and method set(org.jooq.Field,org.jooq.Field) in org.jooq.UpdateSetStep match

this is my code

```<code>    ctx.update(AT_PREFERENCS)
            .set(AT_PREFERENCS.DIRECTION, preferences.direction)
            .set(AT_PREFERENCS.START_END, (Field<Object>) DSL.field("daterange(?, ?)", Object.class, preferences.start, preferences.end))
            .where(AT_PREFERENCS.USER.eq(userId))
            .execute();
</code>```

How can I update daterange with jOOQ?

答:
This is due to the very unfortunate Java language design problem (a major flaw in my opinion) documented in this question here. jOOQ should have worked around this problem, but given that jOOQ predates Java 8 and the language design regression was introduced in Java 8, this cannot be fixed in the jOOQ API easily and backwards compatibly right now.

There are several workarounds for this:

Create a data type binding

This might be the most robust solution if you plan on using this range type more often, in case of which you should define a custom data type binding. It's a bit of extra work up front, but once you have that specified, you will be able to write:

```<code>.set(AT_PREFERENCES.START_END, new MyRangeType(preferences.start, preferences.end))
</code>```

Where AT_PREFERENCES.START_END would be a Field<MyRangeType>.

Cast to raw types and bind an unchecked, explicit type variable that isn't Object

This is a quick workaround if you're using this type only once or twice. It has no impact on the runtime, just tweaks the compiler into believing that this is correct.

```<code>.<Void>set(
    (Field) AT_PREFERENCES.START_END,
    (Field) DSL.field("daterange(?, ?)", Object.class, preferences.start, preferences.end))
</code>```

Cast to raw types and then back to some other Field<T> type

Same as before, but this lets type inference do the job of inferring <Void> for <T>

```<code>.set(
    (Field<Void>) (Field) AT_PREFERENCES.START_END,
    (Field<Void>) (Field) DSL.field("daterange(?, ?)", Object.class,
                            preferences.start, preferences.end))
</code>```

Explicitly bind to the "wrong" API method

jOOQ internally handles all method calls in those rare cases where type safety breaks and the "wrong" overload is called. So, you could also simply call this:

```<code>.set(
    AT_PREFERENCES.START_END,
    (Object) DSL.field("daterange(?, ?)", Object.class,
      preferences.start, preferences.end))
</code>```

With this cast, only the set(Field<T>, T) method is applicable and you no longer rely on the Java compiler finding the most specific method among the applicable overloads (which no longer works since Java 8).

jOOQ will run an instanceof check on the T argument, to see if it is really of type Field, in case of which it internally re-routes to the intended API method set(Field<T>, Field<T>)

Title: Update a Postgres daterange with jOOQ

Body:
I try to update a Postgres daterange. Whatever I try it isn't working. Currently I get

Error:(51, 17) java: reference to set is ambiguous
    both method set(org.jooq.Field,T) in org.jooq.UpdateSetStep and method set(org.jooq.Field,org.jooq.Field) in org.jooq.UpdateSetStep match

this is my code

    ctx.update(AT_PREFERENCS)
            .set(AT_PREFERENCS.DIRECTION, preferences.direction)
            .set(AT_PREFERENCS.START_END, (Field<Object>) DSL.field("daterange(?, ?)", Object.class, preferences.start, preferences.end))
            .where(AT_PREFERENCS.USER.eq(userId))
            .execute();

How can I update daterange with jOOQ?

Body:
This is due to the very unfortunate Java language design problem (a major flaw in my opinion) documented in this question here. jOOQ should have worked around this problem, but given that jOOQ predates Java 8 and the language design regression was introduced in Java 8, this cannot be fixed in the jOOQ API easily and backwards compatibly right now.

There are several workarounds for this:

Create a data type binding

This might be the most robust solution if you plan on using this range type more often, in case of which you should define a custom data type binding. It's a bit of extra work up front, but once you have that specified, you will be able to write:

.set(AT_PREFERENCES.START_END, new MyRangeType(preferences.start, preferences.end))

Where AT_PREFERENCES.START_END would be a Field<MyRangeType>.

Cast to raw types and bind an unchecked, explicit type variable that isn't Object

This is a quick workaround if you're using this type only once or twice. It has no impact on the runtime, just tweaks the compiler into believing that this is correct.

.<Void>set(
    (Field) AT_PREFERENCES.START_END,
    (Field) DSL.field("daterange(?, ?)", Object.class, preferences.start, preferences.end))

Cast to raw types and then back to some other Field<T> type

Same as before, but this lets type inference do the job of inferring <Void> for <T>

.set(
    (Field<Void>) (Field) AT_PREFERENCES.START_END,
    (Field<Void>) (Field) DSL.field("daterange(?, ?)", Object.class,
                            preferences.start, preferences.end))

Explicitly bind to the "wrong" API method

jOOQ internally handles all method calls in those rare cases where type safety breaks and the "wrong" overload is called. So, you could also simply call this:

.set(
    AT_PREFERENCES.START_END,
    (Object) DSL.field("daterange(?, ?)", Object.class,
      preferences.start, preferences.end))

With this cast, only the set(Field<T>, T) method is applicable and you no longer rely on the Java compiler finding the most specific method among the applicable overloads (which no longer works since Java 8).

jOOQ will run an instanceof check on the T argument, to see if it is really of type Field, in case of which it internally re-routes to the intended API method set(Field<T>, Field<T>)


问:
VHDL can't matching context of call for to_unsigned in user defined function
I'm using Quartus Prime Pro.

I'm dealing with a function as such:

```<code>library ieee ;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

function round_resize (a : unsigned; b : integer) return unsigned is
  variable c : signed (a'length - 1 downto 0); --problem child
  variable d : signed (b - 1 downto 0);
begin
  c := a + to_signed(2**(b-2), a'length);
  d := to_unsigned(c(c'length-2 downto (c'length-b-1)));
  return d;
end function;
</code>```

But I get the error:

Error(13643): VHDL error at file.vhd(109): can't determine definition of operator ""+"" -- found 0 possible definitions

So I changed the problem child to this:

```<code>c := to_unsigned( a + to_signed(2**(b-2), a'length), a'length);
</code>```

But I get the following error:

Error(13815): VHDL Qualified Expression error at cpmmod.vhd(110): to_unsigned type specified in Qualified Expression must match signed type that is implied for expression by context

What else can I try to make this work?

答: You are trying to add an unsigned with a signed value. You could convert one of the two to get the same type on the variables before add them.</p>

Body:
I'm using Quartus Prime Pro.

I'm dealing with a function as such:

library ieee ;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

function round_resize (a : unsigned; b : integer) return unsigned is
  variable c : signed (a'length - 1 downto 0); --problem child
  variable d : signed (b - 1 downto 0);
begin
  c := a + to_signed(2**(b-2), a'length);
  d := to_unsigned(c(c'length-2 downto (c'length-b-1)));
  return d;
end function;

But I get the error:

Error(13643): VHDL error at file.vhd(109): can't determine definition of operator ""+"" -- found 0 possible definitions

So I changed the problem child to this:

c := to_unsigned( a + to_signed(2**(b-2), a'length), a'length);

But I get the following error:

Error(13815): VHDL Qualified Expression error at cpmmod.vhd(110): to_unsigned type specified in Qualified Expression must match signed type that is implied for expression by context

What else can I try to make this work?


问:
Returning array from d3.json()
As a JQUERY/d3-noob, it seems I cannot figure out how to make this work:

```<code>  supdog = d3.json(dataPath, function(jsondata){
    return jsondata;
  })
  console.log(supdog);
</code>```

Thanks in advance.

答:
I'm aware that this is a very old post, but I've faced a similar problem recently, and found the following solution, which might worth sharing:

In my case the JSON file's syntax was broken. By default, no errors pop up in the browser in this case, unless you enhance the function suggested by @BertjanBroeksema with errorhandling. Something like this:

```<code>function doSomethingWithData(error, jsondata) {
  console.log("error:", error)
  console.log(jsondata);
}
</code>```

This way you'll see if there was something wrong with the processing of the JSON file.

Title: Returning array from d3.json()

Body:
As a JQUERY/d3-noob, it seems I cannot figure out how to make this work:

  supdog = d3.json(dataPath, function(jsondata){
    return jsondata;
  })
  console.log(supdog);

Thanks in advance.

Body:
I'm aware that this is a very old post, but I've faced a similar problem recently, and found the following solution, which might worth sharing:

In my case the JSON file's syntax was broken. By default, no errors pop up in the browser in this case, unless you enhance the function suggested by @BertjanBroeksema with errorhandling. Something like this:

function doSomethingWithData(error, jsondata) {
  console.log("error:", error)
  console.log(jsondata);
}

This way you'll see if there was something wrong with the processing of the JSON file.


问:
Camel kafka logging incorrect details in messageHistory
I am using camel kafka component 2.19 (Latest). I am initializing kafka producer endpoint with "my-topic". but topic is calculated at the runtime say "my-error-topic" and I set it in the header so the message is produced to "my-error-topic". Everything works fine.

The problem is when messageHistory is logged, it logs initial route with the topic which I used for initialization which makes it misleading information for support guys because it gives them an idea that message is produced to "my-topic." As a workaround, I have stopped logging message history. But still I got it in logs from defaultErrorHandler.log(). Hence it is still misleading.

Please tell me the solution.

答: No this is correct as it does it, as it logs the endpoint url from the route (eg you can find exactly where in the route it was). Any kind of header override is a special use-case here, you can log the headers if you use error handling in Camel where you can log anything you want, such as the exception message, stacktrace, message body, headers etc.</p>


问:
populating google forms dropdowns with global contact directory
I am a total newbie when it comes to coding but have created a couple of google forms with some success.

The first question on my new form is "what is your name?" and I was hoping to get a box identical to the one in Gmail when you select a recipient and it auto-completes as you type - is it possible to do this in google forms by piggy backing off whatever code makes that work?

I couldn't work it out so in the meantime I have been trying to use a list item dropdown which looks up the contacts using google apps script.
So far, I have got it to create a question which populates the dropdown with
84 instances of the word 'contact' (I have 84 contacts in my list!) but I cant work out how to actually get the names.

```<code>var form = FormApp.getActiveForm();
var group = ContactsApp.getContacts();
var item = form.addListItem();
item.setTitle('What is your name?');
</code>```

The above makes an array with 84 instances of the word contact.
So instead I tried this...

```<code>var form = FormApp.getActiveForm();
var group = ContactsApp.getContacts();
for (var i in group) {
var now = (group[i].getFullName());
}
var item = form.addListItem();
 item.setTitle('What is your name?');
 item.setChoiceValues(now);
</code>```

which still makes an array of 84 instances of contacts for var group, but also returns a string of one of my contacts for var now. Unfortunately item.setChoiceValues needs an array not a string.

In any case I'm not sure this is the right approach since this seems to be searching my personal contacts rather than the global directory on the domain. Is there a way to populate it with directory contacts without admin rights? (I have access to the contacts in Gmail so why not in Google Forms?)

I know its also possible to export a .csv from contacts to a sheet and populate from there but that won't be up to date unless I run a SIMS report daily (putting added strain on the system) and seems unnecessary when it clearly works in GMail already.

Like I said I am newbie and would appreciate any help.

Thanks

答:
To get each one of your peoples emails do</p>

```<code>var email = group[i].getEmails()[0].getAddress;
</code>```

Body:
I am a total newbie when it comes to coding but have created a couple of google forms with some success.

The first question on my new form is "what is your name?" and I was hoping to get a box identical to the one in Gmail when you select a recipient and it auto-completes as you type - is it possible to do this in google forms by piggy backing off whatever code makes that work?

I couldn't work it out so in the meantime I have been trying to use a list item dropdown which looks up the contacts using google apps script.
So far, I have got it to create a question which populates the dropdown with
84 instances of the word 'contact' (I have 84 contacts in my list!) but I cant work out how to actually get the names.

var form = FormApp.getActiveForm();
var group = ContactsApp.getContacts();
var item = form.addListItem();
item.setTitle('What is your name?');

The above makes an array with 84 instances of the word contact.
So instead I tried this...

var form = FormApp.getActiveForm();
var group = ContactsApp.getContacts();
for (var i in group) {
var now = (group[i].getFullName());
}
var item = form.addListItem();
 item.setTitle('What is your name?');
 item.setChoiceValues(now);

which still makes an array of 84 instances of contacts for var group, but also returns a string of one of my contacts for var now. Unfortunately item.setChoiceValues needs an array not a string.

In any case I'm not sure this is the right approach since this seems to be searching my personal contacts rather than the global directory on the domain. Is there a way to populate it with directory contacts without admin rights? (I have access to the contacts in Gmail so why not in Google Forms?)

I know its also possible to export a .csv from contacts to a sheet and populate from there but that won't be up to date unless I run a SIMS report daily (putting added strain on the system) and seems unnecessary when it clearly works in GMail already.

Like I said I am newbie and would appreciate any help.

Thanks

Body:
To get each one of your peoples emails do

var email = group[i].getEmails()[0].getAddress;


问:
Error:The "GenerateJavaStubs" task failed unexpectedly
after installing plugin.media library getting this error</p>

```<code>Severity    Code    Description Project File    Line    Suppression State Error     The "GenerateJavaStubs" task failed unexpectedly. System.InvalidOperationException: There can be only one type with an [Application] attribute; found: ,at Xamarin.Android.Tasks.ManifestDocument.CreateApplicationElement(XElement manifest, String applicationClass, List`1 subclasses, List`1 selectedWhitelistAssemblies)at Xamarin.Android.Tasks.ManifestDocument.Merge(List`1 subclasses, List`1 selectedWhitelistAssemblies, String applicationClass, Boolean embed, String bundledWearApplicationName, IEnumerable`1 mergedManifestDocuments)at Xamarin.Android.Tasks.GenerateJavaStubs.Run(DirectoryAssemblyResolver res)at Xamarin.Android.Tasks.GenerateJavaStubs.Execute()at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() XamarinForms.QbChat.Android
</code>```

答:
Some plugins as plugin.media, DeviceInfo, CurrentActivity etc. are adding  MainApplication.cs that contains MainActivity winch conflict with MainActivity that is already there.

To resolve delete MainApplication.cs.

Body:
after installing plugin.media library getting this error

Severity    Code    Description Project File    Line    Suppression State Error     The "GenerateJavaStubs" task failed unexpectedly. System.InvalidOperationException: There can be only one type with an [Application] attribute; found: ,at Xamarin.Android.Tasks.ManifestDocument.CreateApplicationElement(XElement manifest, String applicationClass, List`1 subclasses, List`1 selectedWhitelistAssemblies)at Xamarin.Android.Tasks.ManifestDocument.Merge(List`1 subclasses, List`1 selectedWhitelistAssemblies, String applicationClass, Boolean embed, String bundledWearApplicationName, IEnumerable`1 mergedManifestDocuments)at Xamarin.Android.Tasks.GenerateJavaStubs.Run(DirectoryAssemblyResolver res)at Xamarin.Android.Tasks.GenerateJavaStubs.Execute()at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() XamarinForms.QbChat.Android


问:
How to fill svg shape when i touch on svg image without loss quality of svg
This image is SVG image which is loaded into SVGImageView. I can't fill color into SVG with onTouch listener. I am tired to fill color into particular shape or area. Help me. Thank you.

https://i.stack.imgur.com/96TM5.png

And fill area with different color like this :

https://i.stack.imgur.com/t9zXG.jpg

答:
AFAIK at the moment none of the SVG libraries for Android support interaction.  I am the author of AndroidSVG and it is a high priority on my list of things to implement.

If you need it now, however, I think you will need to resort to displaying the SVG in a WebView and using Javascript events to determine what is clicked on.


问:
Block TOR Servers
I need a script that blocks TOR servers in php ... I need to get the list of servers and block them.

Or, any solution to install on the server (centos).

Title: Block TOR Servers

Body:
Here(https://github.com/RD17/DeTor) is a simple REST API to determine whether a request was made from TOR network or not. I think it will be pretty simple to use it from PHP

The request is:
curl -X GET http://detor.ambar.cloud/.

The response is

{
  "sourceIp": "104.200.20.46",
  "destIp": "89.207.89.82",
  "destPort": "8080",
  "found": true
}

As a bonus you can add a badge to your site to detect whether a user comes from TOR or not:

<img src='http://detor.ambar.cloud/badge' />


问:
How to append json from php to a listview?
I loaded a json fuction from a php page and I append it to an UL, Which creates a list.When I delete a row, I reuse the same function to re-append the list; it works, but sometime I have to click twice before it removes theselected row.

Is there a way to simplify this process as i am new to jquery?

```<code>$(document).on('pageinit', '#two', function () {
    var url="http://localhost/budget/items_list.php";
    $.getJSON(url,function(result){
    console.log(result);
    $.each(result, function(i, field){
        var budgeted_id=field.budgeted_id;
        var name=field.name;
        var budget_amount=field.budget_amount;
        var trans_amount=field.trans_amount;
        var balance=field.balance;
        $("#listview").append('<li  data-icon="delete"><a href="#">'+name+'<span class="ui-li-count">Bal: $'+balance+'</span></a><a class="del" id="'+budgeted_id+'" href="#"></a></li>').listview("refresh");
    });
});

$(document).on("click",'.del',function(){
    $("#listview").empty();
    budgeted_id = (this.id);
    $.post('delete_item.php',{postbudgeted_id:budgeted_id});
    var url="http://localhost/budget/items_list.php";
    $.getJSON(url,function(result){
        console.log(result);
        $.each(result, function(i, field){
           var budgeted_id=field.budgeted_id;
           var name=field.name;
           var budget_amount=field.budget_amount;
           var trans_amount=field.trans_amount;
           var balance=field.balance;
           $("#listview").append('<li data-icon="delete"><a href="#">'+name+'<span class="ui-li-count">Bal: $'+balance+'</span></a><a class="del" id="'+budgeted_id+'" href="#"></a></li>').listview("refresh");
        })
    })
});
</code>```

答:
IMHO, it isn't a bad idea to reuse the same function, you will be sure to get always the actual data you have on server-side.

From your description of the issue, I believe you just only need to chain the two ajax calls.

Here an example how to do that, adapted on the fly from jQuery documentation:

```<code>function createList(result){
  $.each(result, function(i, field){
    var budgeted_id=field.budgeted_id;
    var name=field.name;
    var budget_amount=field.budget_amount;
    var trans_amount=field.trans_amount;
    var balance=field.balance;
    $("#listview").empty().append('<li  data-icon="delete"><a href="#">'+name+'<span class="ui-li-count">Bal: $'+balance+'</span></a><a class="del" id="'+budgeted_id+'" href="#"></a></li>').listview("refresh");
  });
}

function getListData(){
  $.ajax({
    url: "http://localhost/budget/items_list.php",
    method: "GET",
    dataType: "json",
    success: function (result) {
      createList(result);
    }
  });
}

$(document).on("pageinit", "#two", function () {
  getListData();
});

$(document).on("click", ".del",function(){
  var budgeted_id = (this.id);
  var request = $.ajax({
    url: "delete_item.php"
    method: "POST",
    data: {postbudgeted_id:budgeted_id}
  });
  var chained = request.then(function() {
    getListData();
  });
});
</code>```

Please, note this is untested, but you got the idea. If there is an ajax error, your list will remain untouched, up to you to trap these errors and display in your web page a toaster notification.

If chaining the ajax calls won't work, maybe you should investigate your backend.

Body:
I loaded a json fuction from a php page and I append it to an UL, Which creates a list.When I delete a row, I reuse the same function to re-append the list; it works, but sometime I have to click twice before it removes theselected row.

Is there a way to simplify this process as i am new to jquery?

$(document).on('pageinit', '#two', function () {
    var url="http://localhost/budget/items_list.php";
    $.getJSON(url,function(result){
    console.log(result);
    $.each(result, function(i, field){
        var budgeted_id=field.budgeted_id;
        var name=field.name;
        var budget_amount=field.budget_amount;
        var trans_amount=field.trans_amount;
        var balance=field.balance;
        $("#listview").append('
'+name+'Bal: $'+balance+'
').listview("refresh");
    });
});

$(document).on("click",'.del',function(){
    $("#listview").empty();
    budgeted_id = (this.id);
    $.post('delete_item.php',{postbudgeted_id:budgeted_id});
    var url="http://localhost/budget/items_list.php";
    $.getJSON(url,function(result){
        console.log(result);
        $.each(result, function(i, field){
           var budgeted_id=field.budgeted_id;
           var name=field.name;
           var budget_amount=field.budget_amount;
           var trans_amount=field.trans_amount;
           var balance=field.balance;
           $("#listview").append('
'+name+'Bal: $'+balance+'
').listview("refresh");
        })
    })
});

Body:
IMHO, it isn't a bad idea to reuse the same function, you will be sure to get always the actual data you have on server-side.

From your description of the issue, I believe you just only need to chain the two ajax calls.

Here an example how to do that, adapted on the fly from jQuery documentation:

function createList(result){
  $.each(result, function(i, field){
    var budgeted_id=field.budgeted_id;
    var name=field.name;
    var budget_amount=field.budget_amount;
    var trans_amount=field.trans_amount;
    var balance=field.balance;
    $("#listview").empty().append('<li  data-icon="delete"><a href="#">'+name+'<span class="ui-li-count">Bal: $'+balance+'</span></a><a class="del" id="'+budgeted_id+'" href="#"></a></li>').listview("refresh");
  });
}

function getListData(){
  $.ajax({
    url: "http://localhost/budget/items_list.php",
    method: "GET",
    dataType: "json",
    success: function (result) {
      createList(result);
    }
  });
}

$(document).on("pageinit", "#two", function () {
  getListData();
});

$(document).on("click", ".del",function(){
  var budgeted_id = (this.id);
  var request = $.ajax({
    url: "delete_item.php"
    method: "POST",
    data: {postbudgeted_id:budgeted_id}
  });
  var chained = request.then(function() {
    getListData();
  });
});

Please, note this is untested, but you got the idea. If there is an ajax error, your list will remain untouched, up to you to trap these errors and display in your web page a toaster notification.

If chaining the ajax calls won't work, maybe you should investigate your backend.


问:
The animation scroll to top button does not work
a couple of days ago i started working with my companies website. I saw it was missing something so I decided to make a scroll to top button with animation. I am a noob in programming so i decided to look on the Internet. There I found this example. I literally copied the whole code but it does not work.

the button in the html:

```<code><a href="javascript:" id="return-to-top"><i class="icon-chevron-up"></i></a>
</code>```

and this is the jQuery:

```<code>$(window).scroll(function() {
    if ($(this).scrollTop() >= 50) {
        $('#return-to-top').fadeIn(200);
    } else {
        $('#return-to-top').fadeOut(200);
    }
});
$('#return-to-top').click(function() {
    $('body, html').animate({
        scrollTop : 0
    }, 500);
});
</code>```

I dont know what the problem is because it works on the codepen. Does anyone know how to fix this?

Thanks in advance

答: There is not enough information but if you use the same code from codepen then maybe you need to include jQuery into your site header. (https://cdnjs.com/libraries/jquery/)</p>

Body:
a couple of days ago i started working with my companies website. I saw it was missing something so I decided to make a scroll to top button with animation. I am a noob in programming so i decided to look on the Internet. There I found this example. I literally copied the whole code but it does not work.

the button in the html:

and this is the jQuery:

$(window).scroll(function() {
    if ($(this).scrollTop() >= 50) {
        $('#return-to-top').fadeIn(200);
    } else {
        $('#return-to-top').fadeOut(200);
    }
});
$('#return-to-top').click(function() {
    $('body, html').animate({
        scrollTop : 0
    }, 500);
});

I dont know what the problem is because it works on the codepen. Does anyone know how to fix this?

Thanks in advance


问:
python: taking random sample from data but keeping the same distribution
I have a training data that has 20,000 and more instances, split into 3 classes, with a distribution like A=10%, B=20%, C=70%. Is there a way in sklearn or pandas or anything else that can take a sample of 10% from this data but at the same time respecting the distribution of different classes? As I need do grid search on the data but the original dataset is too high dimensional (20,000 x 12,000 feature dimension)

The train_test_split will keep the distribution but it only splits the entire dataset into two sets, which are still too large.

Thanks

答:
You should use Stratifiefkfold. The folds are made by preserving the percentage of samples for each class.
See the documentation for using it.</p>


问:
What is incorrect with the following component in React.Component
This is upwork test problem.

I can't guess answer at all.

Which answer is right?

```<code>class MyComponent extends React.Component {
    render() {
        return (
        This is a component
        );
    }
}
</code>```

Answers:

react render

react component

class should be replaced by className

render should not be a function

答:
I suggest that you first read react-native docs. That should be a good start.

With regard to your question:

1. You can't return plain text inside render function, it needs to be wrapped inside an html tag. Thus your component should be something like :

```<code>class MyComponent extends React.Component {
    render() {
        return (<div>This is a component</div>);
    }
}
</code>```

Here is the fiddle.

Thus, react render isn't correct, because it returns nothing in your case.

And class should be replaced by className isn't correct. You use className instead of css classes.

Hope this helps. But I really suggest to read the docs first.

Body:
This is upwork test problem.

I can't guess answer at all.

Which answer is right?

class MyComponent extends React.Component {
    render() {
        return (
        This is a component
        );
    }
}

Answers:

react render

react component

class should be replaced by className

render should not be a function

Body:
I suggest that you first read react-native docs. That should be a good start.

With regard to your question:

1. You can't return plain text inside render function, it needs to be wrapped inside an html tag. Thus your component should be something like :

class MyComponent extends React.Component {
    render() {
        return (<div>This is a component</div>);
    }
}

Here is the fiddle.

Thus, react render isn't correct, because it returns nothing in your case.

And class should be replaced by className isn't correct. You use className instead of css classes.

Hope this helps. But I really suggest to read the docs first.


问:
unordered_map of a hash
From some source^, I get a hash buffer of length 20 (SHA-1) for a particular data (say a file or block of bytes). If this given hash (consider it as string, not hash) is not found in map, then I would pull more information, and insert this information with this hash. To make it clear:

unordered_map<Hash_of_20_Bytes, Information>

It is my map. The key would be a 20-byte buffer, and Information is some structure containing detailed information. So, if the source^ gives me some hash, I would lookup that hash into this Information-map and use/generate appropriately.

The point is, in my case, the given 20-byte hash is guaranteed to not have any collision. However, unordered_map would still calculate the (FNV) hash for the key (the key itself being a hash!). Can't I instruct the collection class not to generate the hash, instead use the key has unique-key itself (to ensure O(1))?

I am not sure if unordered_map computes the hash for integers also (i.e. to reduce the need for additional computation).

One approach is to use a vector of pair<20-byte, Info> itself, and do a binary search. However, just to avoid penalty of hash computation (by hash-container) it incurs more penalty of keeping the vector sorted).

答:
A hasher for std::unordered_map must satisfy the Hash concept. So it must return a std::size_t, which is extremely unlikely to be more than 20 bytes.

Therefore it is not possible to provide an identity hasher for this 20-byte hash, and so even if no collision is guaranteed for the 20-byte hash, unless it can be reliably reduced to a 32-bit space (or rather a sizeof(std::size_t) space) without collision, collisions will be unavoidable for this case and this container.

Title: unordered_map of a hash


问:
why am getting this exception: Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException
i am reading excel file using apache poi 3.16 here is my code

```<code>try
        {
            String excelPath = "C:\\Users\\wecme\\Desktop\\AccountStatement.xls";
            FileInputStream fileInputStream = new FileInputStream(new File(excelPath));

            // Create Workbook instance holding .xls file
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);

            // Get the first worksheet
            XSSFSheet sheet = workbook.getSheetAt(0);

            // Iterate through each rows
            java.util.Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext())
            {
                // Get Each Row
                Row row = rowIterator.next();

                // Iterating through Each column of Each Row
                java.util.Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext())
                {

                    Cell cell = cellIterator.next();

                    // Checking the cell format
                    switch (cell.getCellType())
                    {
                   case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                   case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        System.out.print(cell.getBooleanCellValue() + "\t");
                        break;

                    }
                }
                System.out.println("");
            }

        } catch (IOException ie)
        {
            ie.printStackTrace();
        }
</code>```

my excel data looks like this:

```<code>Datetime    Description TransactionId   Credit Amount   Debit Amount    Remaining   OdAmount    EnteredBy   Remarks
1/6/2017 8:14   IDEA (9542010237) COMMISSION    GLGHQN  0.31    0   2721.92 0   iNHYD0390437LO  IDEA COMMISSION
</code>```

when i read other file which is not having time with date its reading properly ,but when  i try to read this file this exception coming

```<code>Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:286)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:758)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:327)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:291)
at excelRead.ReadExcel.main(ReadExcel.java:27)
</code>```

please help me , thank you.

答:
According to the code where the Exception is thrown (see: https://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackage.java?view=markup#l286)

And also the name of the package (openxml4j) it is required that the files are in an openxml compatible format. (i.e. xlsx)

In your case the library cannot open the file because it is not in a .zip format that it can open.

This question has also been asked two months ago, maybe this is also helpful:

How to fix NotOfficeXmlFileException in java Apache POI?

Body:
i am reading excel file using apache poi 3.16 here is my code

try
        {
            String excelPath = "C:\\Users\\wecme\\Desktop\\AccountStatement.xls";
            FileInputStream fileInputStream = new FileInputStream(new File(excelPath));

            // Create Workbook instance holding .xls file
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);

            // Get the first worksheet
            XSSFSheet sheet = workbook.getSheetAt(0);

            // Iterate through each rows
            java.util.Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext())
            {
                // Get Each Row
                Row row = rowIterator.next();

                // Iterating through Each column of Each Row
                java.util.Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext())
                {

                    Cell cell = cellIterator.next();

                    // Checking the cell format
                    switch (cell.getCellType())
                    {
                   case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                   case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        System.out.print(cell.getBooleanCellValue() + "\t");
                        break;

                    }
                }
                System.out.println("");
            }

        } catch (IOException ie)
        {
            ie.printStackTrace();
        }

my excel data looks like this:

Datetime    Description TransactionId   Credit Amount   Debit Amount    Remaining   OdAmount    EnteredBy   Remarks
1/6/2017 8:14   IDEA (9542010237) COMMISSION    GLGHQN  0.31    0   2721.92 0   iNHYD0390437LO  IDEA COMMISSION

when i read other file which is not having time with date its reading properly ,but when  i try to read this file this exception coming

Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:286)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:758)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:327)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:291)
at excelRead.ReadExcel.main(ReadExcel.java:27)

please help me , thank you.


问:
how to grep part of the content from a string in bash
For example when filtering html file,
if every line is in this kind of pattern:

```<code><a href="xxxxxx" style="xxxx"><i>some text</i></a>
</code>```

how can I get the content of href, and how can I get the text between  and ?

答:
If href is always the second token separated by space in a,ine then u can try

grep "href" file | cut -d' ' -f2 | cut -d'=' -f2

Body:
For example when filtering html file,
if every line is in this kind of pattern:

some text

how can I get the content of href, and how can I get the text between  and ?


问:
Pandas average timestamp for DateFrame subset
I am really new of Pandas and I have a problem how to calculate the average value of a set of time.

I have a csv file with columns: Date, Time, Outside temperature

I imported and modify it as:

```<code>df = pd.read_csv("./file.csv", parse_dates=[0], dayfirst=True)
df["Date"] = pd.to_datetime(df["Date"])
df["Time"] = pd.to_datetime(df["Time"]).dt.time
</code>```

I prefer to have the date and time separate in two different columns and not use them as index.

I already extracted the part I need and obtaining something like this:

```<code>           Date      Time  Outside Temperature
4343 2006-06-30  13:00:00                 15.9
4344 2006-06-30  13:10:00                 15.9
4345 2006-06-30  13:20:00                 15.9
4346 2006-06-30  13:30:00                 15.9
4347 2006-06-30  13:40:00                 15.9
</code>```

as you can see at same temperature I have different time, I would like to have the average value of the time, something like: 13:22:34

How can I do it?

I checked other questions as: Average time for datetime list, I tried several way to access to the time, for example:

```<code>print(tempdf["Time"].dt.hour)
</code>```

but I obtain the error:

```<code>AttributeError: Can only use .dt accessor with datetimelike values
</code>```

I think I make a mistake in the conversion to timestamp.

Do you have any suggestion?

I am using python3.5 and pandas 0.20.2

Thanks a lot

Ciccio

Edit:

The original csv file for the time has the format hh:mm without the seconds.

答:
To take mean of time you convert time series to timedelta type and take mean. To get average of time and temperature for a perticular date use groupby

edit

If Time column only contains hh:mm
you need to add secs in it

```<code>df['Time'] = pd.to_timedelta(df["Time"] + ':00')
print(df)
</code>```

output:

```<code>         Date     Time  Outside Temperature
0  2006-06-30 13:00:00                 15.9
1  2006-06-30 13:10:00                 15.9
2  2006-06-30 13:20:00                 15.9
3  2006-06-30 13:30:00                 15.9
4  2006-06-30 13:40:00                 15.9
</code>```

Convert Time to int so that it can be used in groupby

```<code>df['Time'] = df['Time'].astype(int)
</code>```

Group by date column and get mean of time and Outside Temperature

```<code>df = df.groupby(['Date'])['Time', 'Outside Temperature'].mean()
</code>```

Now again convert time series to Timedelta type

```<code>df['Time'] = pd.to_timedelta(df['Time'])
</code>```

Output:

```<code>               Time  Outside Temperature
Date
2006-06-30 13:20:00                 15.9
</code>```

Body:
I am really new of Pandas and I have a problem how to calculate the average value of a set of time.

I have a csv file with columns: Date, Time, Outside temperature

I imported and modify it as:

df = pd.read_csv("./file.csv", parse_dates=[0], dayfirst=True)
df["Date"] = pd.to_datetime(df["Date"])
df["Time"] = pd.to_datetime(df["Time"]).dt.time

I prefer to have the date and time separate in two different columns and not use them as index.

I already extracted the part I need and obtaining something like this:

           Date      Time  Outside Temperature
4343 2006-06-30  13:00:00                 15.9
4344 2006-06-30  13:10:00                 15.9
4345 2006-06-30  13:20:00                 15.9
4346 2006-06-30  13:30:00                 15.9
4347 2006-06-30  13:40:00                 15.9

as you can see at same temperature I have different time, I would like to have the average value of the time, something like: 13:22:34

How can I do it?

I checked other questions as: Average time for datetime list, I tried several way to access to the time, for example:

print(tempdf["Time"].dt.hour)

but I obtain the error:

AttributeError: Can only use .dt accessor with datetimelike values

I think I make a mistake in the conversion to timestamp.

Do you have any suggestion?

I am using python3.5 and pandas 0.20.2

Thanks a lot

Ciccio

Edit:

The original csv file for the time has the format hh:mm without the seconds.

Body:
To take mean of time you convert time series to timedelta type and take mean. To get average of time and temperature for a perticular date use groupby

edit

If Time column only contains hh:mm
you need to add secs in it

df['Time'] = pd.to_timedelta(df["Time"] + ':00')
print(df)

output:

         Date     Time  Outside Temperature
0  2006-06-30 13:00:00                 15.9
1  2006-06-30 13:10:00                 15.9
2  2006-06-30 13:20:00                 15.9
3  2006-06-30 13:30:00                 15.9
4  2006-06-30 13:40:00                 15.9

Convert Time to int so that it can be used in groupby

df['Time'] = df['Time'].astype(int)

Group by date column and get mean of time and Outside Temperature

df = df.groupby(['Date'])['Time', 'Outside Temperature'].mean()

Now again convert time series to Timedelta type

df['Time'] = pd.to_timedelta(df['Time'])

Output:

               Time  Outside Temperature
Date
2006-06-30 13:20:00                 15.9


问:
Set point of projection
Im working on game project. I have a scenario, in which the stage will contain circles in random position. When I press the up arrow key I want the circles to move in 3 dimensional axis from the center.

The width of the stage is 550 and the height of the stage is 300.

What I want is,

the circles that are positioned equal to the center of the stage(550/2) should travel in 90 degree.

the circles that are positioned lesser than the center of the stage(550/2) should travel in angle lesser than 90 degree, with a difference from the center.

In the image the circles should travel in angle  lesser than 90 degree and the angle should increase based on the difference from the center

the circles that are positioned greater than the center of the stage(550/2) should travel in angle greater than 90 degree,  with a difference from the center.

In the image the circles should travel in angle  greater than 90 degree and the angle should increase based on the difference from the center

what I have done is

```<code>var stage_width = 550;
var stage_height = 300;
var stage_center = stage_width/2;
var speed = 5;
var default_angle = 90 * Math.PI/180;

for(i = 0; i< 1; i++)
{
     var circle = _root.attachMovie('circle','circle_mc_'+i,_root.getNextHighestDepth());
    circle._x = Math.floor(Math.random() * 551);
    circle._y = Math.floor(Math.random() * 301);
    circle.obj_x = circle._x;
    circle.onEnterFrame = function()
    {
        Key.addListener(this);
        this.onKeyDown = function()
        {
            if(Key.UP  == Key.getCode())
            {
                if(this._x == stage_center)
                {
                    this._x = this._x + Math.cos(default_angle) * speed;
                    this._y = this._y + Math.sin(default_angle) * speed;
                }
                else if(this._x > stage_center)
                {
                    var diff = this.obj_x - stage_center;
                    // I need a solution here to find the angle
                    var angle = ((90 - diff)<0)?-(90 - diff): 90 - diff;
                    var rad = (angle) * Math.PI/180;
                    this._x = this._x + Math.cos(rad) * speed;
                    this._y = this._y + Math.sin(rad) * speed;
                }
                else if(this._x < stage_center)
                {
                    var diff = stage_center - this.obj_x;
                    // I need a solution here to find the angle
                    var angle = ((90 + diff)>180)? 180: 90 + diff;
                    var rad = (angle) * Math.PI/180;
                    this._x = this._x + Math.cos(rad) * speed;
                    this._y = this._y + Math.sin(rad) * speed;
                }
            }
        }
    }
}
</code>```

I dont know how to find the angle greater or lesser than 90 degree based on the difference from the center and the assigned position. Kindly provide me  solution to find the angle

答:
The simplest way I can is to imagine a half circle with radius 550/2 around your centre. If you do that, then the X coordinate of your ball becomes the cosine of the angle you need, and the Y coordinate becomes the sine.

Now, to rotate a vector by some angle, let's say A, you just need to left multiply it by:

```<code>|cos(A) -sin(A)|
|sin(A)  cos(A)|
</code>```

But since cos(A) = X and sin(A) = Y:

```<code>|X -Y|
|Y  X|
</code>```

(I expect this to work if the Y=0 is at the top of the screen.)
https://en.wikipedia.org/wiki/Rotation_matrix

Title: Set point of projection

Body:
Im working on game project. I have a scenario, in which the stage will contain circles in random position. When I press the up arrow key I want the circles to move in 3 dimensional axis from the center.

The width of the stage is 550 and the height of the stage is 300.

What I want is,

the circles that are positioned equal to the center of the stage(550/2) should travel in 90 degree.

the circles that are positioned lesser than the center of the stage(550/2) should travel in angle lesser than 90 degree, with a difference from the center.

In the image the circles should travel in angle  lesser than 90 degree and the angle should increase based on the difference from the center

the circles that are positioned greater than the center of the stage(550/2) should travel in angle greater than 90 degree,  with a difference from the center.

In the image the circles should travel in angle  greater than 90 degree and the angle should increase based on the difference from the center

what I have done is

var stage_width = 550;
var stage_height = 300;
var stage_center = stage_width/2;
var speed = 5;
var default_angle = 90 * Math.PI/180;

for(i = 0; i< 1; i++)
{
     var circle = _root.attachMovie('circle','circle_mc_'+i,_root.getNextHighestDepth());
    circle._x = Math.floor(Math.random() * 551);
    circle._y = Math.floor(Math.random() * 301);
    circle.obj_x = circle._x;
    circle.onEnterFrame = function()
    {
        Key.addListener(this);
        this.onKeyDown = function()
        {
            if(Key.UP  == Key.getCode())
            {
                if(this._x == stage_center)
                {
                    this._x = this._x + Math.cos(default_angle) * speed;
                    this._y = this._y + Math.sin(default_angle) * speed;
                }
                else if(this._x > stage_center)
                {
                    var diff = this.obj_x - stage_center;
                    // I need a solution here to find the angle
                    var angle = ((90 - diff)<0)?-(90 - diff): 90 - diff;
                    var rad = (angle) * Math.PI/180;
                    this._x = this._x + Math.cos(rad) * speed;
                    this._y = this._y + Math.sin(rad) * speed;
                }
                else if(this._x < stage_center)
                {
                    var diff = stage_center - this.obj_x;
                    // I need a solution here to find the angle
                    var angle = ((90 + diff)>180)? 180: 90 + diff;
                    var rad = (angle) * Math.PI/180;
                    this._x = this._x + Math.cos(rad) * speed;
                    this._y = this._y + Math.sin(rad) * speed;
                }
            }
        }
    }
}

I dont know how to find the angle greater or lesser than 90 degree based on the difference from the center and the assigned position. Kindly provide me  solution to find the angle

Body:
The simplest way I can is to imagine a half circle with radius 550/2 around your centre. If you do that, then the X coordinate of your ball becomes the cosine of the angle you need, and the Y coordinate becomes the sine.

Now, to rotate a vector by some angle, let's say A, you just need to left multiply it by:

|cos(A) -sin(A)|
|sin(A)  cos(A)|

But since cos(A) = X and sin(A) = Y:

|X -Y|
|Y  X|

(I expect this to work if the Y=0 is at the top of the screen.)
https://en.wikipedia.org/wiki/Rotation_matrix


答:
You cannot use the hash as-is anyway, since unordered_map expects a size_t as hash, not a 20 bytes buffer.

Now, what you can do is to provide an extremely simple custom hash function: since the input is already a good hash you can just take the first sizeof(size_t) bytes and brutally memcpy them into a size_t, discarding all the others. I don't know think you'll get incredible performance speedups, but it doesn't cost much to try this out.

Can't I instruct the collection class not to generate the hash, instead, use the key has unique-key itself (to ensure O(1))?

The underlying assumption here is flawed; yes, your key is already a good, well-behaved hash, so you don't need to apply a complex hash function over it go get the expected hash properties and you won't get collisions of the type "different data map to the same hash"; but in general if you have a decent hash function most collisions don't come from the hash function mapping the same key to the same hash, but from the current size of the hash table - i.e. from the fact that multiple hash values are mapped to the same bucket. So, again, you aren't going to gain much.

Title: unordered_map of a hash

Body:
From some source^, I get a hash buffer of length 20 (SHA-1) for a particular data (say a file or block of bytes). If this given hash (consider it as string, not hash) is not found in map, then I would pull more information, and insert this information with this hash. To make it clear:

unordered_map<Hash_of_20_Bytes, Information>

It is my map. The key would be a 20-byte buffer, and Information is some structure containing detailed information. So, if the source^ gives me some hash, I would lookup that hash into this Information-map and use/generate appropriately.

The point is, in my case, the given 20-byte hash is guaranteed to not have any collision. However, unordered_map would still calculate the (FNV) hash for the key (the key itself being a hash!). Can't I instruct the collection class not to generate the hash, instead use the key has unique-key itself (to ensure O(1))?

I am not sure if unordered_map computes the hash for integers also (i.e. to reduce the need for additional computation).

One approach is to use a vector of pair<20-byte, Info> itself, and do a binary search. However, just to avoid penalty of hash computation (by hash-container) it incurs more penalty of keeping the vector sorted).


问:
Selected Option to none value is not working
I am having a Select input field in html page.In a if block a condition should work.

```<code><select id='selectopt'>
  <option value="">Select<option>
  <option value="1">1<option>
</select>

<input type="text" id='text1'>

if($('#text1').val==='name'){
    $("#selectopt option[value='']").attr('selected', true);
}
else{
}
</code>```

when i put this condition inside if its working in chrome and IE but not working in firefox..

答:
Use .prop() instead of .attr()

prop()

Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.

```<code>$("#selectopt option[value='']").prop('selected', true);
</code>```

Body:
I am having a Select input field in html page.In a if block a condition should work.

<select id='selectopt'>
  <option value="">Select<option>
  <option value="1">1<option>
</select>

<input type="text" id='text1'>

if($('#text1').val==='name'){
    $("#selectopt option[value='']").attr('selected', true);
}
else{
}

when i put this condition inside if its working in chrome and IE but not working in firefox..

Body:
Use .prop() instead of .attr()

prop()

Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.

$("#selectopt option[value='']").prop('selected', true);


问:
swift 3 ViewController to TableViewController
I'm building a todo list app. So far I have a tableViewController in which i have the list of todo created and when I click on it a viewcontroller opens with the content inside. I have a navigationController linked to the tableviewcontroller, and tableviewcontroller linked to viewcontroller.
What I want to do now is create a new viewcontroller with an input inside, you insert your name and after clicking on a button it opens the tableviewcontroller with the list inside.
Is is the same way as linking tableviewcontroller to viewcontroller or is there a difference ?

[EDIT]

Here's what I've got so far :

答:
you remove navigation bar in all controller than accepted action clicked event for viewing controller present.

your login view controller to table view  for applay push view controller code and back for pop view controller code apply.

3.you search in google table view to detail view you will get exact idea how to pass data tableview data to view controller in show data ...


问:
bootstrap - make the page non-responsive and show desktop version to all devices
I have currently a website that is responsive but since its not very good in mobiles and tablets I want to make it like desktop (.col-md-x) on all smaller devices. I use bootstrap 3.

so if the resolution is more than 1200px it should show large version (.col-lg-x) and if not, it should always show the desktop version (.col-md-x).

to do this I deleted the

<meta name="viewport" content="width=device-width, initial-scale=1">

tag from the page head tag and replaced it with

<meta name="viewport" content="width=1024">

that do the trick but the page was very very zoomed out. so I changed the bootstrap break points in bootstrap customization page so that col-xs-x and col-sm-x and col-md-x breaks on 1px page width, and col-lg-x on 1200px.

its better now but the sidebars and some other elements will hide on small devices and full page is not shown there. what I want is a complete page like desktop with horizontal and vertical scrollbars and no breaking and no hiding and no collapsing navbar and other things. how can I achieve this?

答:
If you define only the behaviour for col-xs-x, it should automatically show the same behaviour for the larger formats, so the solution here is to just use col-xs-x on your elements.

We don't have to define anything for extra small devices since the default is one column. We have to define a grid size for small devices, but not for medium devices. This is because the grid cascades up. So if you define a size at sm, then it will be that grid size for sm, md, and lg.

More information can be found here


问:
How to convert all values in a pandas DataFrame to string according to display settings?
How can I turn a DataFrame into DataFrame of strings according to the same rules that str(df) uses?

I tried df.astype("str") and df.applymap(str), but both left floats with larger precision than indicated by display.precision setting.

答:
Use .round() before converting to str:

```<code>p = pd.get_option('display.precision')
df.round(p).astype(str)
</code>```

Pandas rounds numerical data when you try to display it, to the precision specified by display.precision; the data is still stored by its full precision.

Directly casting to str results in pandas using the full precision of the float; it is independent of whatever setting you have for display.precision.

Body:
Use .round() before converting to str:

p = pd.get_option('display.precision')
df.round(p).astype(str)

Pandas rounds numerical data when you try to display it, to the precision specified by display.precision; the data is still stored by its full precision.

Directly casting to str results in pandas using the full precision of the float; it is independent of whatever setting you have for display.precision.


答:
cat file | cut -f2 -d\"

FYI: Just about every other HTML/regexp post on Stackoverflow explains why getting values from HTML using anything other than HTML parsing is a bad idea. You may want to read some of those.  This one for example.

Title: how to grep part of the content from a string in bash


问:
Testing @TransactionalEvents and @Rollback
I've been trying to test out @TransactionalEvents (a feature of Spring 4.2 https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2) with our existing Spring JUnit Tests (run via either @TransactionalTestExecutionListener or subclassing AbstractTransactionalUnit4SpringContextTests but, it seems like there's a forced choice -- either run the test without a @Rollback annotation, or the events don't fire.  Has anyone come across a good way to test @TransactionalEvents while being able to @Rollback tests?

答:
Sam Brannen's solution almost works with regard to adam's comment.

Actually the methods annotated with @TransactionalEventListener are called after the test method transaction is committed. This is so because the calling method, which raises the event, is executing within a logical transaction, not a physical one.

Instead, when the calling method is executed within a new physical transaction, then the methods annotated with @TransactionalEventListener are invoked at the right time, i.e., before the test method transaction is committed.

Also, we don't need @Commit on the test methods, since we actually don't care about these transactions. However, we do need the @Sql(...) statement as explained by Sam Brannen to undo the committed changes of the calling method.

See the small example below.

First the listener that is called when the transaction is committed (default behavior of @TransactionalEventListener):

```<code>@Component
public class MyListener {

    @TransactionalEventListener
    public void when(MyEvent event) {
        ...
    }
}
</code>```

Then the application service that publishes the event listened to by the above class. Notice that the transactions are configured to be new physical ones each time a method is invoked (see the Spring Framework doc for more details):

```<code>@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class MyApplicationService {

    public void doSomething() {
        // ...
        // publishes an instance of MyEvent
        // ...
    }
}
</code>```

Finally the test method as proposed by Sam Brannen but without the @Commitannotation which is not needed at this point:

```<code>@Transactional
@Sql(scripts = "/cleanup.sql", executionPhase = AFTER_TEST_METHOD,
     config = @SqlConfig(transactionMode = TransactionMode.ISOLATED))
@Test
public void test() {
    MyApplicationService target = // ...
    target.doSomething();
    // the event is now received by MyListener
    // assertions on the side effects of MyListener
    // ...
}
</code>```

This way it works like a charm :-)

Body:
Sam Brannen's solution almost works with regard to adam's comment.

Actually the methods annotated with @TransactionalEventListener are called after the test method transaction is committed. This is so because the calling method, which raises the event, is executing within a logical transaction, not a physical one.

Instead, when the calling method is executed within a new physical transaction, then the methods annotated with @TransactionalEventListener are invoked at the right time, i.e., before the test method transaction is committed.

Also, we don't need @Commit on the test methods, since we actually don't care about these transactions. However, we do need the @Sql(...) statement as explained by Sam Brannen to undo the committed changes of the calling method.

See the small example below.

First the listener that is called when the transaction is committed (default behavior of @TransactionalEventListener):

@Component
public class MyListener {

    @TransactionalEventListener
    public void when(MyEvent event) {
        ...
    }
}

Then the application service that publishes the event listened to by the above class. Notice that the transactions are configured to be new physical ones each time a method is invoked (see the Spring Framework doc for more details):

@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class MyApplicationService {

    public void doSomething() {
        // ...
        // publishes an instance of MyEvent
        // ...
    }
}

Finally the test method as proposed by Sam Brannen but without the @Commitannotation which is not needed at this point:

@Transactional
@Sql(scripts = "/cleanup.sql", executionPhase = AFTER_TEST_METHOD,
     config = @SqlConfig(transactionMode = TransactionMode.ISOLATED))
@Test
public void test() {
    MyApplicationService target = // ...
    target.doSomething();
    // the event is now received by MyListener
    // assertions on the side effects of MyListener
    // ...
}

This way it works like a charm :-)


问:
Splitting XML into rows (TSQL)
I've been wrestling with this for hours and I'm completely befuddled on why it's not working. I have the following XML as a single column (a few dozen records stored this way).

```<code><dsMQ1License xmlns="http://tempuri.org/dsMQ1License.xsd">
  <licenseModuleInfo>
    <module>AP</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
  <licenseModuleInfo>
    <module>AU</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
  <licenseModuleInfo>
    <module>CO</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
  <licenseModuleInfo>
    <module>DO</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
.
.
.
</dsMQ1License>
</code>```

I want to be able to take the XML column, and turn it into rows where each column represents the inner most element.

```
+--------+--------+---------------+
| Module | Status | StatusEndDate |
+--------+--------+---------------+
| AD     |      1 | 2017-12-28    |
| AU     |      1 | 2017-12-28    |
| CO     |      1 | 2017-12-28    |
| DO     |      1 | 2017-12-28    |
+--------+--------+---------------+
```

Based on everything I've read so far, I feel like what I've done should work.

```<code>SELECT
T.C.value('(module)[1]','VARCHAR(MAX)') AS ModuleAbbr
,T.C.value('(status)[1]','bit') AS Active
FROM LicenseXML
CROSS APPLY LicenseXML.License.nodes('/dsMQ1License/licenseModuleInfo') T(C)
</code>```

But it just returns 0 rows.

Where am I going wrong?

答:
Try This</p>

```<code> DECLARE @x xml = '<dsMQ1License xmlns="http://tempuri.org/dsMQ1License.xsd">

  <licenseModuleInfo>

    <module>AP</module>

    <status>1</status>

    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>

  </licenseModuleInfo>

  <licenseModuleInfo>

    <module>AU</module>

    <status>1</status>

    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>

  </licenseModuleInfo>

  <licenseModuleInfo>

    <module>CO</module>

    <status>1</status>

    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>

  </licenseModuleInfo>

  <licenseModuleInfo>

    <module>DO</module>

    <status>1</status>

    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>

  </licenseModuleInfo>

</dsMQ1License>'

;WITH XMLNAMESPACES

(

DEFAULT 'http://tempuri.org/dsMQ1License.xsd'

)

    SELECT

    x.item.value('module[1]','VARCHAR(100)') AS ModuleAbbr

    ,x.item.value('status[1]','bit') AS Active

    ,x.item.value('statusEndDate[1]','datetime') AS EndDate

    FROM @x.nodes('//dsMQ1License/licenseModuleInfo') AS x(item)
</code>```

Title: Splitting XML into rows (TSQL)

Body:
I've been wrestling with this for hours and I'm completely befuddled on why it's not working. I have the following XML as a single column (a few dozen records stored this way).

<dsMQ1License xmlns="http://tempuri.org/dsMQ1License.xsd">
  <licenseModuleInfo>
    <module>AP</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
  <licenseModuleInfo>
    <module>AU</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
  <licenseModuleInfo>
    <module>CO</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
  <licenseModuleInfo>
    <module>DO</module>
    <status>1</status>
    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>
  </licenseModuleInfo>
.
.
.
</dsMQ1License>

I want to be able to take the XML column, and turn it into rows where each column represents the inner most element.

+--------+--------+---------------+
| Module | Status | StatusEndDate |
+--------+--------+---------------+
| AD     |      1 | 2017-12-28    |
| AU     |      1 | 2017-12-28    |
| CO     |      1 | 2017-12-28    |
| DO     |      1 | 2017-12-28    |
+--------+--------+---------------+

Based on everything I've read so far, I feel like what I've done should work.

SELECT
T.C.value('(module)[1]','VARCHAR(MAX)') AS ModuleAbbr
,T.C.value('(status)[1]','bit') AS Active
FROM LicenseXML
CROSS APPLY LicenseXML.License.nodes('/dsMQ1License/licenseModuleInfo') T(C)

But it just returns 0 rows.

Where am I going wrong?

Body:
Try This

 DECLARE @x xml = '<dsMQ1License xmlns="http://tempuri.org/dsMQ1License.xsd">

  <licenseModuleInfo>

    <module>AP</module>

    <status>1</status>

    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>

  </licenseModuleInfo>

  <licenseModuleInfo>

    <module>AU</module>

    <status>1</status>

    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>

  </licenseModuleInfo>

  <licenseModuleInfo>

    <module>CO</module>

    <status>1</status>

    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>

  </licenseModuleInfo>

  <licenseModuleInfo>

    <module>DO</module>

    <status>1</status>

    <statusEndDate>2007-12-28T00:00:00.0000000-05:00</statusEndDate>

  </licenseModuleInfo>

</dsMQ1License>'

;WITH XMLNAMESPACES

(

DEFAULT 'http://tempuri.org/dsMQ1License.xsd'

)

    SELECT

    x.item.value('module[1]','VARCHAR(100)') AS ModuleAbbr

    ,x.item.value('status[1]','bit') AS Active

    ,x.item.value('statusEndDate[1]','datetime') AS EndDate

    FROM @x.nodes('//dsMQ1License/licenseModuleInfo') AS x(item)


问:
Fatal error: Uncaught Error: Call to a member function format() on string
```<code><?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hello";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

echo "connected";

use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;

// Include Spout library
include ('spout-2.4.3\src\Spout\Autoloader\autoload.php');

// check file name is not empty
if (!empty($_FILES['file']['name'])) {

    // Get File extension eg. 'xlsx' to check file is excel sheet
    $pathinfo = pathinfo($_FILES["file"]["name"]);

    // check file has extension xlsx, xls and also check
    // file is not empty
   if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
           && $_FILES['file']['size'] > 0 ) {

        // Temporary file name
        $inputFileName = $_FILES['file']['tmp_name'];

        // Read excel file by using ReadFactory object.
        $reader = ReaderFactory::create(Type::XLSX);

        // Open file
        $reader->open($inputFileName);
        $count = 1;
        $rows = array();

        // Number of sheet in excel file
        foreach ($reader->getSheetIterator() as $sheet) {

            // Number of Rows in Excel sheet
            foreach ($sheet->getRowIterator() as $row) {

                // It reads data after header. In the my excel sheet,
                // header is in the first row.
                if ($count> 1){

                $newDate = $row[4]-> format('d/m/Y');

                $result=mysqli_query($conn,"INSERT INTO stud VALUES                         ('NULL','$row[1]','$row[2]','$row[3]','$newDate','$row[5]','$row[6]','$row[7]')");

                }
                $count++;
            }

        }

        // Close excel file
        $reader->close();

    } else {

        echo "Please Select Valid Excel File";
    }

} else {

    echo "Please Select Excel File";

}
?>
</code>```

This is the php script am used to import excel file to mysql database ,i got an error while inserting date from excel to mysql table.

```<code>$newDate = $row[4]-> format('d/m/Y');
$result=mysqli_query($conn,"INSERT INTO stud VALUES           ('NULL','$row[1]','$row[2]','$row[3]','$newDate','$row[5]','$row[6]','$row[7]')");
</code>```

I try to format the row[4] ,but it shows "Uncaught Error: Call to a member function format() on string"  error.Any solution?

Excel file:
click to view excel which am working

答:
NEW CODE

```<code><!doctype>
    <html>
    <head>
    </head>
    <body>
    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";

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

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    //disply db table in php page
    mysqli_select_db($conn,'demo_data');

    require_once "Classes/PHPExcel.php";

            $tmpfname = "test.xlsx";
            $excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
            $excelObj = $excelReader->load($tmpfname);
            $worksheet = $excelObj->getSheet(0);
            $lastRow = $worksheet->getHighestRow();

            //echo "<table>";
            for ($row = 2; $row <= $lastRow; $row++) {
                // echo "<tr><td>";
                 $a= $worksheet->getCell('A'.$row)->getValue();
                // echo "</td><td>";
                 $b= $worksheet->getCell('B'.$row)->getValue();
                 $c= $worksheet->getCell('C'.$row)->getFormattedValue();
                 echo $a." ".$b." ".$c." ";
                $timestamp = strtotime($c);
    $e = date('Y-m-d',$timestamp );
    //echo $e;
                // echo "</td><tr>";
                $query="INSERT INTO excel_data VALUES('NULL','$a','$b','$e') ";
                $check=mysqli_query($conn,$query);
                if($check)
                {
                    echo "ok";
                    }
                    else {
                        "no data insertion";
                    }

            }
            //echo "</table>";
    ?>

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

I used PHPExcel library for importing excel files to mysql.The PHPExcel library simply handle the date conversion problem while importing to mysql.
Thanks ....

Body:
<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hello";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

echo "connected";

use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;

// Include Spout library
include ('spout-2.4.3\src\Spout\Autoloader\autoload.php');

// check file name is not empty
if (!empty($_FILES['file']['name'])) {

    // Get File extension eg. 'xlsx' to check file is excel sheet
    $pathinfo = pathinfo($_FILES["file"]["name"]);

    // check file has extension xlsx, xls and also check
    // file is not empty
   if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
           && $_FILES['file']['size'] > 0 ) {

        // Temporary file name
        $inputFileName = $_FILES['file']['tmp_name'];

        // Read excel file by using ReadFactory object.
        $reader = ReaderFactory::create(Type::XLSX);

        // Open file
        $reader->open($inputFileName);
        $count = 1;
        $rows = array();

        // Number of sheet in excel file
        foreach ($reader->getSheetIterator() as $sheet) {

            // Number of Rows in Excel sheet
            foreach ($sheet->getRowIterator() as $row) {

                // It reads data after header. In the my excel sheet,
                // header is in the first row.
                if ($count> 1){

                $newDate = $row[4]-> format('d/m/Y');

                $result=mysqli_query($conn,"INSERT INTO stud VALUES                         ('NULL','$row[1]','$row[2]','$row[3]','$newDate','$row[5]','$row[6]','$row[7]')");

                }
                $count++;
            }

        }

        // Close excel file
        $reader->close();

    } else {

        echo "Please Select Valid Excel File";
    }

} else {

    echo "Please Select Excel File";

}
?>

This is the php script am used to import excel file to mysql database ,i got an error while inserting date from excel to mysql table.

$newDate = $row[4]-> format('d/m/Y');
$result=mysqli_query($conn,"INSERT INTO stud VALUES           ('NULL','$row[1]','$row[2]','$row[3]','$newDate','$row[5]','$row[6]','$row[7]')");

I try to format the row[4] ,but it shows "Uncaught Error: Call to a member function format() on string"  error.Any solution?

Excel file:
click to view excel which am working

Body:
NEW CODE

<!doctype>
    <html>
    <head>
    </head>
    <body>
    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";

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

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    //disply db table in php page
    mysqli_select_db($conn,'demo_data');

    require_once "Classes/PHPExcel.php";

            $tmpfname = "test.xlsx";
            $excelReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
            $excelObj = $excelReader->load($tmpfname);
            $worksheet = $excelObj->getSheet(0);
            $lastRow = $worksheet->getHighestRow();

            //echo "<table>";
            for ($row = 2; $row <= $lastRow; $row++) {
                // echo "<tr><td>";
                 $a= $worksheet->getCell('A'.$row)->getValue();
                // echo "</td><td>";
                 $b= $worksheet->getCell('B'.$row)->getValue();
                 $c= $worksheet->getCell('C'.$row)->getFormattedValue();
                 echo $a." ".$b." ".$c." ";
                $timestamp = strtotime($c);
    $e = date('Y-m-d',$timestamp );
    //echo $e;
                // echo "</td><tr>";
                $query="INSERT INTO excel_data VALUES('NULL','$a','$b','$e') ";
                $check=mysqli_query($conn,$query);
                if($check)
                {
                    echo "ok";
                    }
                    else {
                        "no data insertion";
                    }

            }
            //echo "</table>";
    ?>

    </body>
    </html>

I used PHPExcel library for importing excel files to mysql.The PHPExcel library simply handle the date conversion problem while importing to mysql.
Thanks ....


问:
Cross-platform (microcontroller-PC) algorithm development
I was asked to develop a algorithm for network application on C. This project will be developed on Linux for PC and then it will be transferred to a more portable platform, something that will include a microcontroller. There are many microcontroller/companies out there that provide very nice and large libraries for TCP/IP. This software will hold statistics on the network performance.

The whole idea of a cross platform (uC - PC) seems rubbish to me cause eventually the code should be written in a more platform specific way for the microcontroller, but I am not expert to judge anyway.

Is there any clever way of doing this or is there a anyone that did this before? My brainstorming has "Wrapper library" and "Matlab"... Any ideas?

Thx!

答:
If using a simulator was not an option I would try to wrap the Linux functions up in interfaces that match those of the embedded system, if possible.  That way any extra bulk in the system will be on the Linux development system (which is not resource constrained).  Various embedded OSes and TCP/IP stacks can have vastly different architectures, so how easy this is can range from nearly impossible to no work at all.

If it turns out that writing wrapper libraries to make Linux look like the embedded system is too difficult then I suggest at least trying to keep the embedded OS in mind while writing the Linux version so that you can try to at least write some functions so that they work on both systems.

If it doesn't take too long writing a Linux version of at least part of the code may help you to shake out a few flaws in the overall design, at the very least.  At most it will allow you to more quickly test changes to the system since loading code onto an embedded device often takes more time than you would like.  It may also be easier to debug on your development machine.

Some embedded OSes will run on x86, and it would not surprise me if some of them have drivers that allow them to be run in virtual machines, so this may be an option as well.

Another thing to consider is the endian-ness and the word size of the development machine verses the embedded system.  If these differ then you need to keep this in mind as you code.  Getting this type of thing right when you originally write the code is easier than going back and trying to fix code, in my opinion.


问:
CGLIB errors converting a weblogic spring web app to springboot app
I am attempting to convert an existing spring weblogic application to a spring boot embedded tomcat application.

There are lots of moving parts so it's hard to show any code, I'm hoping there is some general answer that might clue me in to the issue.

Under weblogic, using the spring-framework 4.3.6.RELEASE libraries, the application deploys fine. It has no problems creating the different service, repository and component beans.

However, when I migrate it to Spring Boot 1.5.1.RELEASE, I get the following error:

```<code>2017-06-21 17:08:16,402 [ERROR] SpringApplication reportFailure (815) - Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'alertEventServiceImpl': Unsatisfied dependency expressed through field 'alertEventDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'alertEventDaoImpl' defined in URL [jar:file:/Users/username/Development/source/carma-war/target/carma-war-2.0.0-SNAPSHOT.war!/WEB-INF/lib/protocol-manager-1.8.0-SNAPSHOT.jar!/org/ihc/hwcir/protocol/dao/AlertEventDaoImpl.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class org.ihc.hwcir.protocol.dao.AlertEventDaoImpl]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class org.ihc.hwcir.protocol.dao.AlertEventDaoImpl
</code>```

Many of our service classes are final as they shouldn't be extended. Since there are so many that are final, I wanted to minimize the amount of code in our different libraries that we modify to make this work.

I thought because the bean creation process works under weblogic, it should work under spring boot.

Things I have tried to force not using the cglib proxies:

All implementations implement interfaces already

In beans created via xml, added <aop:scoped-proxy proxy-target-class="false"/>

In beans created through annotations, added (example for service bean)

@Service
@Scope(proxyMode = ScopedProxyMode.INTERFACE)

However, in the end, I'm perplexed as to why spring can create beans (the classes marked as final) under the weblogic container but unable to do so under the embedded tomcat spring-boot container.

答:
I was unable to make this work using M. Deinums' answer using spring.aop.proxy-target-class=false.

What worked for me was to add in the application.properties file

```<code>spring.dao.exceptiontranslation.enabled=false
</code>```

Please note that this option disables proxy creation for repositories.

And in my spring boot application configurer the annotation to handle transactions without using a proxy class.

```<code>@EnableTransactionManagement(proxyTargetClass = false)
</code>```

This is using Spring Boot version 1.5.1.RELEASE.

Body:
I am attempting to convert an existing spring weblogic application to a spring boot embedded tomcat application.

There are lots of moving parts so it's hard to show any code, I'm hoping there is some general answer that might clue me in to the issue.

Under weblogic, using the spring-framework 4.3.6.RELEASE libraries, the application deploys fine. It has no problems creating the different service, repository and component beans.

However, when I migrate it to Spring Boot 1.5.1.RELEASE, I get the following error:

2017-06-21 17:08:16,402 [ERROR] SpringApplication reportFailure (815) - Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'alertEventServiceImpl': Unsatisfied dependency expressed through field 'alertEventDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'alertEventDaoImpl' defined in URL [jar:file:/Users/username/Development/source/carma-war/target/carma-war-2.0.0-SNAPSHOT.war!/WEB-INF/lib/protocol-manager-1.8.0-SNAPSHOT.jar!/org/ihc/hwcir/protocol/dao/AlertEventDaoImpl.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class org.ihc.hwcir.protocol.dao.AlertEventDaoImpl]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class org.ihc.hwcir.protocol.dao.AlertEventDaoImpl

Many of our service classes are final as they shouldn't be extended. Since there are so many that are final, I wanted to minimize the amount of code in our different libraries that we modify to make this work.

I thought because the bean creation process works under weblogic, it should work under spring boot.

Things I have tried to force not using the cglib proxies:

All implementations implement interfaces already

In beans created via xml, added <aop:scoped-proxy proxy-target-class="false"/>

In beans created through annotations, added (example for service bean)

@Service
@Scope(proxyMode = ScopedProxyMode.INTERFACE)

However, in the end, I'm perplexed as to why spring can create beans (the classes marked as final) under the weblogic container but unable to do so under the embedded tomcat spring-boot container.

Body:
I was unable to make this work using M. Deinums' answer using spring.aop.proxy-target-class=false.

What worked for me was to add in the application.properties file

spring.dao.exceptiontranslation.enabled=false

Please note that this option disables proxy creation for repositories.

And in my spring boot application configurer the annotation to handle transactions without using a proxy class.

@EnableTransactionManagement(proxyTargetClass = false)

This is using Spring Boot version 1.5.1.RELEASE.