问:
How do I access data in a class stored in a node through queue pointers?
In my current assignment I'm having trouble figuring out how I can access this particular piece of data.

To start off, the assignment calls for data to be pulled from a file to simulate a store operating normally. The only thing is, the data being pulled is about the customer. Specifically it's when the customer enters a queue and how long it takes for the cashiers to process their order.

Right now how I have customer data stored in an array of classes.

```<code>for(int i = 0; i < entries; i++)
{
  /* !!!!!IMPORTANT!!!!!
   * The way this program extracts file data assumes that the file will
follow a specific format
   * results will vary heavily based on how the file is set up
   *
   * before docking points please make sure that the file follows the format
   *
   *  "Number of entries"
   *  "Customer Number", "Arrival Time", "Service Time"
   *  "Customer Number", "Arrival Time", "Service Time"
   *  "Customer Number", "Arrival Time", "Service Time"
   */

  xfiles >> dataEntry;
  fileData[i].setNumber(dataEntry);
  //inserts a number from the file into the "number" variable in the customer class.
  xfiles >> dataEntry;
  fileData[i].setArrival(dataEntry);
  //inserts a number from the file into the "arrival" variable in the customer class.
  xfiles >> dataEntry;
  fileData[i].setServTime(dataEntry);
  //inserts a number from the file into the "servTime" variable in the customer class.
}

xfiles.close();
</code>```

It's not included with the code but there is a line that takes in account for entries earlier in the program.

In my next block I have to queue and process customers simultaneously through a period of time. I have an idea how what I should do to queue them but I'm not too sure how I should proceed on processing them. For what I know right now I believe I might want to do a conditional statement to check if a certain customer from the array have been queued or not.

The piece of data I'm currently trying to access would be the arrival time that was stored in the class.

So something like,

fileData[i].returnArrival();

but since that class is stored in a queue I'm not sure how I would be able to access it.

Right now how I have everything queued is

```<code>for(int x = 0; x < 570; x++)
{
  if(cusTime == x)
  {
     if(scully.isFull() = false)
        scully.enqueue(fileData[cusTime]);
     else if(mulder.isFull() = false)
        mulder.enqueue(fileData[cusTime]);
     else if(skinner.isFull() = false)
        skinner.enqueue(fileData[cusTime]);
     else
        cout << "queues are full, disposing..\n";
  }
  cusTime++;
}
</code>```

At first I thought it would be something like

```<code>scully.returnFront()->temp->returnClass()->fileData.returnArrival();
</code>```

but I'm unsure about since temp is only a pointer declared within the queue class.

There was another suggestion from a friend of mine who suggested it would probably be something like this instead, but I ended up getting segmentation errors when I ran the code.

```<code>scully.returnFront()->returnClass().returnArrival();
</code>```

答:
After discussing it a bit with the professor and TA the cause of the problem was that the return front function was returning a pointer making it more difficult to access the data within the node. A solution was to have the return front function return the Class associated with the data and have the return statement return a pointer that's pointing to the class function that returns the class stored in the node.

so

```<code>Node *returnFront();
</code>```

was changed to

```<code>Customer returnFront();
</code>```

changes within the function was

```<code>return front;
</code>```

to

```<code>return front->returnClass();
</code>```

these changes made it easier to access the Customer class data from inside the main file. So I was able to instantiate a new place holding variable for the class.

```<code>Customer scullyTemp;
</code>```

And after that store the data from inside the class that was stored in the node through an assignment statement.

```<code>scullyTemp = scully.returnFront();
scullyTemp.returnArrival();
</code>```

It might be a little more complicated than it needs to be, but for now it does what I need it to do.

Body:
In my current assignment I'm having trouble figuring out how I can access this particular piece of data.

To start off, the assignment calls for data to be pulled from a file to simulate a store operating normally. The only thing is, the data being pulled is about the customer. Specifically it's when the customer enters a queue and how long it takes for the cashiers to process their order.

Right now how I have customer data stored in an array of classes.

for(int i = 0; i < entries; i++)
{
  /* !!!!!IMPORTANT!!!!!
   * The way this program extracts file data assumes that the file will
follow a specific format
   * results will vary heavily based on how the file is set up
   *
   * before docking points please make sure that the file follows the format
   *
   *  "Number of entries"
   *  "Customer Number", "Arrival Time", "Service Time"
   *  "Customer Number", "Arrival Time", "Service Time"
   *  "Customer Number", "Arrival Time", "Service Time"
   */

  xfiles >> dataEntry;
  fileData[i].setNumber(dataEntry);
  //inserts a number from the file into the "number" variable in the customer class.
  xfiles >> dataEntry;
  fileData[i].setArrival(dataEntry);
  //inserts a number from the file into the "arrival" variable in the customer class.
  xfiles >> dataEntry;
  fileData[i].setServTime(dataEntry);
  //inserts a number from the file into the "servTime" variable in the customer class.
}

xfiles.close();

It's not included with the code but there is a line that takes in account for entries earlier in the program.

In my next block I have to queue and process customers simultaneously through a period of time. I have an idea how what I should do to queue them but I'm not too sure how I should proceed on processing them. For what I know right now I believe I might want to do a conditional statement to check if a certain customer from the array have been queued or not.

The piece of data I'm currently trying to access would be the arrival time that was stored in the class.

So something like,

fileData[i].returnArrival();

but since that class is stored in a queue I'm not sure how I would be able to access it.

Right now how I have everything queued is

for(int x = 0; x < 570; x++)
{
  if(cusTime == x)
  {
     if(scully.isFull() = false)
        scully.enqueue(fileData[cusTime]);
     else if(mulder.isFull() = false)
        mulder.enqueue(fileData[cusTime]);
     else if(skinner.isFull() = false)
        skinner.enqueue(fileData[cusTime]);
     else
        cout << "queues are full, disposing..\n";
  }
  cusTime++;
}

At first I thought it would be something like

scully.returnFront()->temp->returnClass()->fileData.returnArrival();

but I'm unsure about since temp is only a pointer declared within the queue class.

There was another suggestion from a friend of mine who suggested it would probably be something like this instead, but I ended up getting segmentation errors when I ran the code.

scully.returnFront()->returnClass().returnArrival();

Body:
After discussing it a bit with the professor and TA the cause of the problem was that the return front function was returning a pointer making it more difficult to access the data within the node. A solution was to have the return front function return the Class associated with the data and have the return statement return a pointer that's pointing to the class function that returns the class stored in the node.

so

Node *returnFront();

was changed to

Customer returnFront();

changes within the function was

return front;

to

return front->returnClass();

these changes made it easier to access the Customer class data from inside the main file. So I was able to instantiate a new place holding variable for the class.

Customer scullyTemp;

And after that store the data from inside the class that was stored in the node through an assignment statement.

scullyTemp = scully.returnFront();
scullyTemp.returnArrival();

It might be a little more complicated than it needs to be, but for now it does what I need it to do.


来源: stackexchange

问:
Twilio programmable chat messages with media and custom attributes
I'm wondering if I can attach media to a Twilio Chat message. I'm a bit confused with Twilio docs on this:

The Help Center's Programmable Chat file support for sending messages says it's not supported.
Looks like this is outdated?

The Programmable Chat's API Reference, "Channels and Messages" section says:

Today, a message is just a string of text. In the future, this may expand to include other media types, like images and binary data.

Also outdated?

This StackOverflow answer says it's possible to send multimedia messages, at least for JavaScript. Looks like the same is possible for  iOS with the TCHMessageOptions's withMediaStream:contentType:defaultFilename:onStarted:onProgress:onCompleted: method.

[Aside question] Using the method above, looks like I can create a multimedia message, but can I also set custom attributes?

Could you please clarify?

Thank you!

答:
Twilio developer evangelist here.

Attaching media to messages in Twilio Programmable Chat is now supported in beta. It seems that some of the documentation is a little outdated, but the page with the code and explanations you are looking for is here: https://www.twilio.com/docs/api/chat/guides/media-support.

As for sending custom attributes, each message has an attributes property that you can use to send arbitrary JSON.

I'm working to correct the misleading documentation now. Thanks for pointing it out!

ContentLicense: CC BY-SA 3.0


问:
How to make a method wait for an AJAX call to return a result before it returning its own result?
I can't get through this. Every thread I read about this problem leads me to failure, so I'll try again in this thread.

I need to make an AJAX call in a method. My function needs to wait for my ajax result before returning anything.

I read that Deferred should be the right way to do it, but it does not work.

```<code>my_method();

function my_method() {
  var d1 = $.Deferred();
  console.log('Start');
  $.when(d1).done(function(value) {
    console.log(value);
  });

  $.ajax({
    url: '/echo/js/?js=hello%20world',
    complete: function(response) {
      d1.resolve("Done");
    }
  });
  console.log('End method');
}

console.log('Outside World');
</code>```

SAMPLE JSFIDDLE: https://jsfiddle.net/ttx1qp0r/

As you can see this code outputs in order:
 -Start
 -End method
 -Outside World
 -Done

But this is not what I want. I need Outside World to be the last thing happening.

Technically, I'm trying to make a synchronous ajax call but using async: false is deprecated or not a good idea (not futureproof).

What am I doing wrong? The flow of my application relies on this.

Thanks

答:
How about wrapping your outside world in a function and then calling that function after done like:

```<code>my_method();

function my_method() {
  var d1 = $.Deferred();
  console.log('Start');
  $.when(d1).done(function(value) {
    console.log(value);
    outsideWorld();
  });

  $.ajax({
    url: '/echo/js/?js=hello%20world',
    complete: function(response) {
      d1.resolve("Done");
    }
  });
  console.log('End method');
}

function outsideWorld()
{
    console.log('Outside World');
}
</code>```

Body:
I can't get through this. Every thread I read about this problem leads me to failure, so I'll try again in this thread.

I need to make an AJAX call in a method. My function needs to wait for my ajax result before returning anything.

I read that Deferred should be the right way to do it, but it does not work.

my_method();

function my_method() {
  var d1 = $.Deferred();
  console.log('Start');
  $.when(d1).done(function(value) {
    console.log(value);
  });

  $.ajax({
    url: '/echo/js/?js=hello%20world',
    complete: function(response) {
      d1.resolve("Done");
    }
  });
  console.log('End method');
}

console.log('Outside World');

SAMPLE JSFIDDLE: https://jsfiddle.net/ttx1qp0r/

As you can see this code outputs in order:
 -Start
 -End method
 -Outside World
 -Done

But this is not what I want. I need Outside World to be the last thing happening.

Technically, I'm trying to make a synchronous ajax call but using async: false is deprecated or not a good idea (not futureproof).

What am I doing wrong? The flow of my application relies on this.

Thanks

Body:
How about wrapping your outside world in a function and then calling that function after done like:

my_method();

function my_method() {
  var d1 = $.Deferred();
  console.log('Start');
  $.when(d1).done(function(value) {
    console.log(value);
    outsideWorld();
  });

  $.ajax({
    url: '/echo/js/?js=hello%20world',
    complete: function(response) {
      d1.resolve("Done");
    }
  });
  console.log('End method');
}

function outsideWorld()
{
    console.log('Outside World');
}


问:
Launching Android AVD device crashes after 2 secs (mac). How to fix?
I'm on a Mac Pro, OS version 10.5.8.

Installed android SDK, and was successfully launching and using emulators all morning.  Then this afternoon, the emulator CRASHES every single time I try to launch one.

The sequence is: select (or create a new) AVD targeting Android 2.3, Skin is set to WVGA854... click "start"... emulator device launches, shows the black screen with "Android _ " for about 1-2 seconds, then crashes.

Tried restarting the mac, deleted android SDK along with the hidden .android folder it creates, then reinstalled SDK, tried different settings on the AVD device, all lead to the same result.

Pasted below is the error log from the last crash.

Anyone know what I can do to fix??

答:
On the web I found these suggestions:

Remove your USB sound while the emulator is booting.

Pull the audio device from the USB slot, start the emulator, and re-insert the audio device after the emulator has booted.

Assign the audio-in to the internal microphone it works.

Use -noaudio (See the emulator -help).

ContentLicense: CC BY-SA 2.5


问:
Install specific git commit with pip
I'm developing a django app and I'm using pip to manage my requirements. How can I do to install a specific git's commit?

In my case I need to install this commit:
https://github.com/aladagemre/django-notification/commit/2927346f4c513a217ac8ad076e494dd1adbf70e1

答: If you want to create an egg package, you can still use the same @branch_or_commit appendage: pip install git+ssh://git@github.com/myrepo.git@mybranch#egg=myeggscript

Title: Install specific git commit with pip


问:
How to overcome "'aclocal-1.15' is missing on your system" warning?
Im trying to run a c++ program on github. (available at the following link https://github.com/mortehu/text-classifier)

I have a mac, and am trying to run it in the terminal. I think I have downloaded autoconf and automake but am not sure. To run the program I am going to the correct folder in terminal then running

```<code>./configure && make
</code>```

But I get the error:

WARNING: 'aclocal-1.15' is missing on your system.
           You should only need it if you modified 'acinclude.m4' or
           'configure.ac' or m4 files included by 'configure.ac'.
           The 'aclocal' program is part of the GNU Automake package:
           http://www.gnu.org/software/automake
           It also requires GNU Autoconf, GNU m4 and Perl in order to run:
           http://www.gnu.org/software/autoconf
           http://www.gnu.org/software/m4/
           http://www.perl.org/ make: *** [aclocal.m4] Error 127

I have xcode and g++ and all the things required to run c programs, but as is probably obvious, I have no idea what Im doing.

What is the easiest, simplest way to run the program in the above link? I realise it comes with a readme and example usage but I can not get that to work.

答:
2017 - High Sierra

It is really hard to get autoconf 1.15 working on Mac. We hired an expert to get it working. Everything worked beautifully.

Later I happened to upgrade a Mac to High Sierra.

The Docker pipeline stopped working!

Even though autoconf 1.15 is working fine on the Mac.

How to fix,

Short answer, I simply trashed the local repo, and checked out the repo again.

This suggestion is noted in the mix on this QA page and elsewhere.

It then worked fine!

It likely has something to do with the aclocal.m4 and similar files. (But who knows really). I endlessly massaged those files ... but nothing.

For some unknown reason if you just scratch your repo and get the repo again: everything works!

I tried for hours every combo of touching/deleting etc etc the files in question, but no.  Just check out the repo from scratch!

ContentLicense: CC BY-SA 4.0

Body:
Im trying to run a c++ program on github. (available at the following link https://github.com/mortehu/text-classifier)

I have a mac, and am trying to run it in the terminal. I think I have downloaded autoconf and automake but am not sure. To run the program I am going to the correct folder in terminal then running

./configure && make

But I get the error:

WARNING: 'aclocal-1.15' is missing on your system.
           You should only need it if you modified 'acinclude.m4' or
           'configure.ac' or m4 files included by 'configure.ac'.
           The 'aclocal' program is part of the GNU Automake package:
           http://www.gnu.org/software/automake
           It also requires GNU Autoconf, GNU m4 and Perl in order to run:
           http://www.gnu.org/software/autoconf
           http://www.gnu.org/software/m4/
           http://www.perl.org/ make: *** [aclocal.m4] Error 127

I have xcode and g++ and all the things required to run c programs, but as is probably obvious, I have no idea what Im doing.

What is the easiest, simplest way to run the program in the above link? I realise it comes with a readme and example usage but I can not get that to work.


问:
What does the standard say about move-assignment to self in the case of MoveAssignable?
Here's C++17's current description of MoveAssignable:

t = rv;

If t and rv do not refer to the same object, t is equivalent to the
  value of rv before the assignment rv's state is unspecified. [ Note:
  rv must still meet the requirements of the library component that is
  using it, whether or not t and rv refer to the same object. The
  operations listed in those requirements must work as specified whether
  rv has been moved from or not. — end note ]

What does "rv must still meet the requirements of the library component that is using it" refer to?

What if t & rv refer to the same object? What can/should a type with MoveAssignable do in this case?

Does the description mean:

the library won't call move assignment with self at all, so the type can do whatever it wants in this case (even crash)

or the type should handle this case somehow (no crashing allowed), but its result doesn't matter

or something else?

Note: there are similar questions here at SO, but there are conflicting/old (C++14 has different rules) answers, comments, so I'd like to clarify this.

答:
What does "rv must still meet the requirements of the library component that is using it" refer to?

This is a roundabout way of saying that even though rv's state is unspecified, it must be a valid state. For instance, a type which records an "I'm gone!" state and throws exceptions for subsequent re-assignments is not allowed, if assignment is one of the required-to-be-supported operations.

What if t & rv refer to the same object?

You already quoted the answer to that: "rv's state is unspecified." This is independent of whether t refers to the same object.

Does the description mean:

or the type should handle this case somehow (no crashing allowed), but its result doesn't matter

Yes, this, pretty much.


问:
Cannot upgrade 2SXC from 8.2.3 to 9.6.1
I've tried several times to upgrade 2SXC content from 8.2.3 to 9.6.1 and keep running into an installation error.  This is a site that was previously on 7.2.2 and then upgraded to 9.1.1. I received the same error on both versions.

Steps to Reproduce:

Go to the Extensions page in DNN 9.1.1 with 2SXC 8.2.3 installed

Upload and attempt to upgrade 2SXC to version 9.6.1

Expected Behavior:
The upgrade occurs without error.

Actual Behavior:
There is an error during upgrade, but the module appears to be upgraded when you reload the extensions page.

https://www.screencast.com/t/Y8Gk2ZuzLl

There are specific upgrade errors, but there are a large number of other errors cascaded as well.

```<code>2017-10-23 09:17:27,066 [UPENDO-PC1][Thread:30][ERROR] DotNetNuke.Data.SqlDataProvider - System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'Packages'.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at DotNetNuke.Data.SqlDataProvider.ExecuteScriptInternal(String connectionString, String script, Int32 timeoutSec)
ClientConnectionId:7df9af36-80ea-46e0-8760-f33a2536071b
Error Number:208,State:1,Class:16
2017-10-23 09:17:27,150 [UPENDO-PC1][Thread:30][ERROR] DotNetNuke.Services.Installer.Log.Logger - SQL Execution resulted in following Exceptions:
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'Packages'.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at DotNetNuke.Data.SqlDataProvider.ExecuteScriptInternal(String connectionString, String script, Int32 timeoutSec)
ClientConnectionId:7df9af36-80ea-46e0-8760-f33a2536071b
Error Number:208,State:1,Class:16

-- This SQL file is used for the app-module package (in .dnn manifest file) which must not be installed or upgraded if the 2sxc module fails to install

DECLARE @RequiredVersion int
SET @RequiredVersion = 9

DECLARE @RequiredVersionIsInstalled int
SELECT @RequiredVersionIsInstalled = CASE WHEN EXISTS(SELECT * FROM Packages WHERE Name = N'2SexyContent' AND CONVERT(int, LEFT([Version], CHARINDEX('.', [Version])-1)) >= @RequiredVersion) THEN CAST (1 AS BIT) ELSE CAST (0 AS BIT) END

If @RequiredVersionIsInstalled = 0
BEGIN
    RAISERROR(N'2sxc 9 or newer must be installed for the app module to install. Probably something else went wrong while installing - see previous errors for more information. ****************************************************************************************************************************************************************************************************************************************************************************************************************************************************', 16, 1)
    RETURN
END

2017-10-23 09:17:27,224 [UPENDO-PC1][Thread:30][ERROR] DotNetNuke.Services.Installer.Log.Logger - Installation Failed - Script
2017-10-23 09:17:27,634 [UPENDO-PC1][Thread:30][ERROR] DotNetNuke.Services.Installer.Log.Logger - Package Installation aborted
2017-10-23 09:20:32,338 [UPENDO-PC1][Thread:9][ERROR] DotNetNuke.Services.Exceptions.Exceptions - System.NullReferenceException: Object reference not set to an instance of an object.
   at ToSic.SexyContent.Environment.Dnn7.ImportExportEnvironment.SaveOptions(Int32 zoneId) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\ImportExportEnvironment.cs:line 186
   at ToSic.Eav.Apps.ImportExport.Import..ctor(Nullable`1 zoneId, Int32 appId, Boolean skipExistingAttributes, Boolean preserveUntouchedAttributes, Log parentLog)
   at ToSic.Eav.Apps.ImportExport.XmlImportWithFiles.ImportXml(Int32 zoneId, Int32 appId, XDocument doc, Boolean leaveExistingValuesUntouched)
   at ToSic.SexyContent.Installer.V8.Version080302() in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Installer\V8.cs:line 105
   at ToSic.SexyContent.Installer.InstallationController.UpgradeModule(String version) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Installer\InstallationController.cs:line 187
   at ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.UpgradeModule(String version) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\DnnBusinessController.cs:line 75
   at DotNetNuke.Entities.Modules.EventMessageProcessor.UpgradeModule(EventMessage message)
2017-10-23 09:21:34,131 [UPENDO-PC1][Thread:11][ERROR] DotNetNuke.Framework.Reflection - ToSic.SexyContent.SexyContent
System.Web.HttpException (0x80004005): Could not load type 'ToSic.SexyContent.SexyContent'.
   at System.Web.Compilation.BuildManager.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase)
   at DotNetNuke.Framework.Reflection.CreateType(String TypeName, String CacheKey, Boolean UseCache, Boolean IgnoreErrors)
2017-10-23 09:21:34,147 [UPENDO-PC1][Thread:11][ERROR] DotNetNuke.Services.Search.ModuleIndexer - System.ArgumentNullException: Value cannot be null.
Parameter name: type
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at DotNetNuke.Services.Search.ModuleIndexer.GetModulesForIndex(Int32 portalId)
2017-10-23 09:21:34,162 [UPENDO-PC1][Thread:11][ERROR] DotNetNuke.Services.Exceptions.Exceptions - System.Exception: Error Creating BusinessControllerClass 'ToSic.SexyContent.SexyContent' of module(2sxc-app) id=(3183) in tab(958) and portal(8) ---> System.ArgumentNullException: Value cannot be null.
Parameter name: type
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at DotNetNuke.Services.Search.ModuleIndexer.GetModulesForIndex(Int32 portalId)
   --- End of inner exception stack trace ---
   at DotNetNuke.Services.Search.ModuleIndexer.ThrowLogError(ModuleInfo module, Exception ex)
</code>```

Has anyone else run into this, and do you know how to resolve it?

答:
This actually was resolved by adding the missing {databaseOwner} and {objectQualifier} tokens to the SqlDataProvider script.  It can be seen in the pull request below.

https://github.com/2sic/2sxc/pull/1363

Title: Cannot upgrade 2SXC from 8.2.3 to 9.6.1

Body:
I've tried several times to upgrade 2SXC content from 8.2.3 to 9.6.1 and keep running into an installation error.  This is a site that was previously on 7.2.2 and then upgraded to 9.1.1. I received the same error on both versions.

Steps to Reproduce:

Go to the Extensions page in DNN 9.1.1 with 2SXC 8.2.3 installed

Upload and attempt to upgrade 2SXC to version 9.6.1

Expected Behavior:
The upgrade occurs without error.

Actual Behavior:
There is an error during upgrade, but the module appears to be upgraded when you reload the extensions page.

https://www.screencast.com/t/Y8Gk2ZuzLl

There are specific upgrade errors, but there are a large number of other errors cascaded as well.

2017-10-23 09:17:27,066 [UPENDO-PC1][Thread:30][ERROR] DotNetNuke.Data.SqlDataProvider - System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'Packages'.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at DotNetNuke.Data.SqlDataProvider.ExecuteScriptInternal(String connectionString, String script, Int32 timeoutSec)
ClientConnectionId:7df9af36-80ea-46e0-8760-f33a2536071b
Error Number:208,State:1,Class:16
2017-10-23 09:17:27,150 [UPENDO-PC1][Thread:30][ERROR] DotNetNuke.Services.Installer.Log.Logger - SQL Execution resulted in following Exceptions:
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'Packages'.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at DotNetNuke.Data.SqlDataProvider.ExecuteScriptInternal(String connectionString, String script, Int32 timeoutSec)
ClientConnectionId:7df9af36-80ea-46e0-8760-f33a2536071b
Error Number:208,State:1,Class:16

-- This SQL file is used for the app-module package (in .dnn manifest file) which must not be installed or upgraded if the 2sxc module fails to install

DECLARE @RequiredVersion int
SET @RequiredVersion = 9

DECLARE @RequiredVersionIsInstalled int
SELECT @RequiredVersionIsInstalled = CASE WHEN EXISTS(SELECT * FROM Packages WHERE Name = N'2SexyContent' AND CONVERT(int, LEFT([Version], CHARINDEX('.', [Version])-1)) >= @RequiredVersion) THEN CAST (1 AS BIT) ELSE CAST (0 AS BIT) END

If @RequiredVersionIsInstalled = 0
BEGIN
    RAISERROR(N'2sxc 9 or newer must be installed for the app module to install. Probably something else went wrong while installing - see previous errors for more information. ****************************************************************************************************************************************************************************************************************************************************************************************************************************************************', 16, 1)
    RETURN
END

2017-10-23 09:17:27,224 [UPENDO-PC1][Thread:30][ERROR] DotNetNuke.Services.Installer.Log.Logger - Installation Failed - Script
2017-10-23 09:17:27,634 [UPENDO-PC1][Thread:30][ERROR] DotNetNuke.Services.Installer.Log.Logger - Package Installation aborted
2017-10-23 09:20:32,338 [UPENDO-PC1][Thread:9][ERROR] DotNetNuke.Services.Exceptions.Exceptions - System.NullReferenceException: Object reference not set to an instance of an object.
   at ToSic.SexyContent.Environment.Dnn7.ImportExportEnvironment.SaveOptions(Int32 zoneId) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\ImportExportEnvironment.cs:line 186
   at ToSic.Eav.Apps.ImportExport.Import..ctor(Nullable`1 zoneId, Int32 appId, Boolean skipExistingAttributes, Boolean preserveUntouchedAttributes, Log parentLog)
   at ToSic.Eav.Apps.ImportExport.XmlImportWithFiles.ImportXml(Int32 zoneId, Int32 appId, XDocument doc, Boolean leaveExistingValuesUntouched)
   at ToSic.SexyContent.Installer.V8.Version080302() in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Installer\V8.cs:line 105
   at ToSic.SexyContent.Installer.InstallationController.UpgradeModule(String version) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\SexyContent\Installer\InstallationController.cs:line 187
   at ToSic.SexyContent.Environment.Dnn7.DnnBusinessController.UpgradeModule(String version) in C:\Projects\2SexyContent\Web\DesktopModules\ToSIC_SexyContent\Environment\Dnn7\DnnBusinessController.cs:line 75
   at DotNetNuke.Entities.Modules.EventMessageProcessor.UpgradeModule(EventMessage message)
2017-10-23 09:21:34,131 [UPENDO-PC1][Thread:11][ERROR] DotNetNuke.Framework.Reflection - ToSic.SexyContent.SexyContent
System.Web.HttpException (0x80004005): Could not load type 'ToSic.SexyContent.SexyContent'.
   at System.Web.Compilation.BuildManager.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase)
   at DotNetNuke.Framework.Reflection.CreateType(String TypeName, String CacheKey, Boolean UseCache, Boolean IgnoreErrors)
2017-10-23 09:21:34,147 [UPENDO-PC1][Thread:11][ERROR] DotNetNuke.Services.Search.ModuleIndexer - System.ArgumentNullException: Value cannot be null.
Parameter name: type
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at DotNetNuke.Services.Search.ModuleIndexer.GetModulesForIndex(Int32 portalId)
2017-10-23 09:21:34,162 [UPENDO-PC1][Thread:11][ERROR] DotNetNuke.Services.Exceptions.Exceptions - System.Exception: Error Creating BusinessControllerClass 'ToSic.SexyContent.SexyContent' of module(2sxc-app) id=(3183) in tab(958) and portal(8) ---> System.ArgumentNullException: Value cannot be null.
Parameter name: type
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at DotNetNuke.Services.Search.ModuleIndexer.GetModulesForIndex(Int32 portalId)
   --- End of inner exception stack trace ---
   at DotNetNuke.Services.Search.ModuleIndexer.ThrowLogError(ModuleInfo module, Exception ex)

Has anyone else run into this, and do you know how to resolve it?


问:
Webpack and Node modules
I was wondering if webpack automatically bundles the files inside the node_modules folder that are being used or if there was someway to bundle them.

Thanks!

答: That's exactly what webpack is for. However it only bundles files that have been required or imported. </p>

Title: Webpack and Node modules


问:
Type class constraints in type signature inside an instance when the type is a free variable
How can I add type class constraints in type signature inside an instance when the type is a free variable in Haskell. For example:

```<code>{-# LANGUAGE InstanceSigs #-}

class Pair a where
    pair :: a -> b -> (a, b)

instance Pair Int where
    pair :: (Show a) => a -> b -> (a, b)
    pair a b = (a, b)
</code>```

works, 'a' is a bound type variable whereas:

```<code>{-# LANGUAGE InstanceSigs #-}

class Pair a where
    pair :: a -> b -> (a, b)

instance Pair Int where
    pair :: (Show b) => a -> b -> (a, b)
    pair a b = (a, b)
</code>```

gives this error:

```<code>source_file.hs:8:13:
    No instance for (Show b)
    Possible fix:
      add (Show b) to the context of
        the type signature for pair :: Int -> b -> (Int, b)
    When checking that: forall a b. Show b => a -> b -> (a, b)
      is more polymorphic than: forall b. Int -> b -> (Int, b)
    When checking that instance signature for ‘pair’
      is more general than its signature in the class
      Instance sig: forall a b. Show b => a -> b -> (a, b)
         Class sig: forall b. Int -> b -> (Int, b)
    In the instance declaration for ‘Pair Int’
</code>```

答:
You can't.

The type of pair is forall a b. Pair a => a -> b -> (a, b).

Where a = Int, this specializes to forall b. Int -> b -> (Int, b).

In the first example, your type declaration forall a b. Show a => a -> b -> (a, b) specializes to forall b. Show Int => Int -> b -> (Int, b), and then further reduces to forall b. Int -> b -> (Int, b). (The Show constraint just gets dropped because it is redundant; you're "constraining" a concrete type, which is meaningless.) This is the correct type.

In the second example, you're trying to define an instance where pair has the type forall b. Show b => Int -> b -> (Int, b), which doesn't work because that's a different type.

Body:
How can I add type class constraints in type signature inside an instance when the type is a free variable in Haskell. For example:

{-# LANGUAGE InstanceSigs #-}

class Pair a where
    pair :: a -> b -> (a, b)

instance Pair Int where
    pair :: (Show a) => a -> b -> (a, b)
    pair a b = (a, b)

works, 'a' is a bound type variable whereas:

{-# LANGUAGE InstanceSigs #-}

class Pair a where
    pair :: a -> b -> (a, b)

instance Pair Int where
    pair :: (Show b) => a -> b -> (a, b)
    pair a b = (a, b)

gives this error:

source_file.hs:8:13:
    No instance for (Show b)
    Possible fix:
      add (Show b) to the context of
        the type signature for pair :: Int -> b -> (Int, b)
    When checking that: forall a b. Show b => a -> b -> (a, b)
      is more polymorphic than: forall b. Int -> b -> (Int, b)
    When checking that instance signature for ‘pair’
      is more general than its signature in the class
      Instance sig: forall a b. Show b => a -> b -> (a, b)
         Class sig: forall b. Int -> b -> (Int, b)
    In the instance declaration for ‘Pair Int’


问:
Is there a query which selects columns from only one table which would give incorrect results if grouped by only the primary key of that table?
For example, a bookpub database contains the following tables (pseudocode):

```<code>book (key: isbn)
bookauthor (key:author_id, isbn)
author (key: author_id)
</code>```

The following query returns the number of books by each author:

```<code>select lastname, firstname, count(isbn)
from author
join bookauthor using (author_id)
group by lastname, firstname;
</code>```

However, the following query also produces identical results in MySQL without complaint:

```<code>select lastname, firstname, count(isbn)
from author
join bookauthor using (author_id)
group by author_id;
</code>```

So why shouldn't author_id be used instead of lastname, firstname?

I might add that the formal SQL spec contains the following:

```<code>All non-aggregate groups in a SELECT expression list or HAVING expression list must be included in the GROUP BY clause.
</code>```

Can somebody please interpret this? What is a "non-aggregate group"? Why not just say "columns"? Furthermore, what is an "expression list"? Does an expression in this case always evaluate to a column?

答:
No SQL Implementation is 100% true to the ANSI definition.  Some things are missing, some things are added, something are just different.

In MySQL's case, it was chosen to not enforce the restriction you mention:

All non-aggregate groups in a SELECT expression list or HAVING expression list must be included in the GROUP BY clause.

This allows the GROUP BY primary_key syntax that you have noticed, instead of the clunky (and actually slightly more costly) GROUP BY property1, property2, property3, etc.  It's clean and elegant.

There are downsides, however; misuse and misunderstanding are rife in web developers because of MySQL, and the flexibility allows bugs to slip though undetected.  I recommend avoiding it it in most cases as the performance gains are minimal and the potential for bugs can be huge.

An example of an bug that slips through could be:

```<code>SELECT
    person.name,
    address.city
FROM
    person
INNER JOIN
    address
        ON  address.person_id = person.id
GROUP BY
    person.id
</code>```

MySQL will pretty much always allow that code to execute.  Even if the address table can have multiple entries per person (I've lived at more than one address).

The code could possibly need to be as follows, but MySQL will never enforce this:

```<code>SELECT
    person.name,
    address.move_in_date,
    address.city
FROM
    person
INNER JOIN
    address
        ON  address.person_id = person.id
GROUP BY
    person.id,
    address.id
</code>```

The more joins involved, the more chance the GROUP BY needs to include multiple primary keys, or other fields.

The behavior you get is that MySQL arbitrarily chooses what values to return when the code is ambiguous.  It is explicitly non-deterministic.  The following code could give the city from one address and the city's population from another address :-/

```<code>SELECT
    person.name,
    address.move_in_date,
    address.city,
    city.population
FROM
    person
INNER JOIN
    address
        ON  address.person_id = person.id
INNER JOIN
    city
        ON  address.city_id = city.id
GROUP BY
    person.id
</code>```

People then try to abuse this with "tricks" like the following...

```<code>SELECT
    person.name,
    address.move_in_date,
    address.city,
    city.population
FROM
    person
INNER JOIN
    address
        ON  address.person_id = person.id
INNER JOIN
    city
        ON  address.city_id = city.id
GROUP BY
    person.id
ORDER BY
    person.id,
    city.population DESC
</code>```

This happens to cause the MySQL engine to choose the city with the highest population.  Useful for finding the most populous city each person has lived in?  Well, it's not actually guaranteed to work.  It's still arbitrary; if the tables are being written to, or the database is in a distributed environment, or the MySQL code changes, etc, the behavior could change.

But people do it anyway.  Because "well, it's always worked for me so far!"...

Body:
For example, a bookpub database contains the following tables (pseudocode):

book (key: isbn)
bookauthor (key:author_id, isbn)
author (key: author_id)

The following query returns the number of books by each author:

select lastname, firstname, count(isbn)
from author
join bookauthor using (author_id)
group by lastname, firstname;

However, the following query also produces identical results in MySQL without complaint:

select lastname, firstname, count(isbn)
from author
join bookauthor using (author_id)
group by author_id;

So why shouldn't author_id be used instead of lastname, firstname?

I might add that the formal SQL spec contains the following:

All non-aggregate groups in a SELECT expression list or HAVING expression list must be included in the GROUP BY clause.

Can somebody please interpret this? What is a "non-aggregate group"? Why not just say "columns"? Furthermore, what is an "expression list"? Does an expression in this case always evaluate to a column?

Body:
No SQL Implementation is 100% true to the ANSI definition.  Some things are missing, some things are added, something are just different.

In MySQL's case, it was chosen to not enforce the restriction you mention:

All non-aggregate groups in a SELECT expression list or HAVING expression list must be included in the GROUP BY clause.

This allows the GROUP BY primary_key syntax that you have noticed, instead of the clunky (and actually slightly more costly) GROUP BY property1, property2, property3, etc.  It's clean and elegant.

There are downsides, however; misuse and misunderstanding are rife in web developers because of MySQL, and the flexibility allows bugs to slip though undetected.  I recommend avoiding it it in most cases as the performance gains are minimal and the potential for bugs can be huge.

An example of an bug that slips through could be:

SELECT
    person.name,
    address.city
FROM
    person
INNER JOIN
    address
        ON  address.person_id = person.id
GROUP BY
    person.id

MySQL will pretty much always allow that code to execute.  Even if the address table can have multiple entries per person (I've lived at more than one address).

The code could possibly need to be as follows, but MySQL will never enforce this:

SELECT
    person.name,
    address.move_in_date,
    address.city
FROM
    person
INNER JOIN
    address
        ON  address.person_id = person.id
GROUP BY
    person.id,
    address.id

The more joins involved, the more chance the GROUP BY needs to include multiple primary keys, or other fields.

The behavior you get is that MySQL arbitrarily chooses what values to return when the code is ambiguous.  It is explicitly non-deterministic.  The following code could give the city from one address and the city's population from another address :-/

SELECT
    person.name,
    address.move_in_date,
    address.city,
    city.population
FROM
    person
INNER JOIN
    address
        ON  address.person_id = person.id
INNER JOIN
    city
        ON  address.city_id = city.id
GROUP BY
    person.id

People then try to abuse this with "tricks" like the following...

SELECT
    person.name,
    address.move_in_date,
    address.city,
    city.population
FROM
    person
INNER JOIN
    address
        ON  address.person_id = person.id
INNER JOIN
    city
        ON  address.city_id = city.id
GROUP BY
    person.id
ORDER BY
    person.id,
    city.population DESC

This happens to cause the MySQL engine to choose the city with the highest population.  Useful for finding the most populous city each person has lived in?  Well, it's not actually guaranteed to work.  It's still arbitrary; if the tables are being written to, or the database is in a distributed environment, or the MySQL code changes, etc, the behavior could change.

But people do it anyway.  Because "well, it's always worked for me so far!"...


问:
How to check if an Array of strings is sorted in alphabetical order or not using Kotlin?
I am given a list of strings and I need to see if they are in alphabetical order.

I know I need to use a for loop and check the first character of each string but I don't know how to progress from there.

```<code>for (item in array)
     println(item[0])
</code>```

For example ["adam", "ben", "chloe"] should return true.

And likewise for ["ben", "adam", "chloe"] should return false.

答:
UPD: Since Kotlin 1.2 the following is available:

Most efficient variant, creates the smallest amount of intermediate objects:

```<code>listOf(1, 2, 3).asSequence().zipWithNext { a, b -> a <= b }.all { it }
</code>```

Note on efficiency: Creates only two Sequence objects and one function object. Uses Boolean constants as an intermediate value. The final all invocation is inlined as a while loop over the sequence.

Slightly less efficient variant:

```<code>listOf(1, 2, 3).asSequence().windowed(2).all { (a, b) -> a <= b }
</code>```

It's slightly less efficient, as it creates creates intermediate List(a, b) for every element of the original list.

Both of these variants were listed in the answers below by @Billbucket and @AshishChaudhary.

Old answer, for previous versions of Kotlin:

Here is a one liner:

```<code>val a = listOf("a", "b", "c")
a.zip(a.drop(1)).all { (a, b) -> a <= b }
// true
</code>```

Explanation:

a.zip(a.drop(1)) returns pairs of neighbour elements. If in every pair first element is less or equal to the next, array is in order.

If you want to improve performance, you can wrap your array in lazy sequence first. In this case array won't be copied:

```<code>a.asSequence().let { it.zip(it.drop(1)).all { (a, b) -> a < b }  }
</code>```

The whole thing is O(N) (single pass through array), which is optimal for this task.

Body:
I am given a list of strings and I need to see if they are in alphabetical order.

I know I need to use a for loop and check the first character of each string but I don't know how to progress from there.

for (item in array)
     println(item[0])

For example ["adam", "ben", "chloe"] should return true.

And likewise for ["ben", "adam", "chloe"] should return false.

Body:
UPD: Since Kotlin 1.2 the following is available:

Most efficient variant, creates the smallest amount of intermediate objects:

listOf(1, 2, 3).asSequence().zipWithNext { a, b -> a <= b }.all { it }

Note on efficiency: Creates only two Sequence objects and one function object. Uses Boolean constants as an intermediate value. The final all invocation is inlined as a while loop over the sequence.

Slightly less efficient variant:

listOf(1, 2, 3).asSequence().windowed(2).all { (a, b) -> a <= b }

It's slightly less efficient, as it creates creates intermediate List(a, b) for every element of the original list.

Both of these variants were listed in the answers below by @Billbucket and @AshishChaudhary.

Old answer, for previous versions of Kotlin:

Here is a one liner:

val a = listOf("a", "b", "c")
a.zip(a.drop(1)).all { (a, b) -> a <= b }
// true

Explanation:

a.zip(a.drop(1)) returns pairs of neighbour elements. If in every pair first element is less or equal to the next, array is in order.

If you want to improve performance, you can wrap your array in lazy sequence first. In this case array won't be copied:

a.asSequence().let { it.zip(it.drop(1)).all { (a, b) -> a < b }  }

The whole thing is O(N) (single pass through array), which is optimal for this task.


问:
Custom back indicator image and iOS 11
I'm using a custom back button in my app. This custom back button is set globally like this:

```<code>    UINavigationBar.appearance().backIndicatorImage = UIImage(named: "Back").withRenderingMode(.alwaysOriginal)
    UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(asset: .back).withRenderingMode(.alwaysOriginal)
</code>```

Before iOS 11 this code did the trick, but now in iOS 11 the button is not centered vertically anymore as you can see here:

I could change the height of the back button image to 44, but that would break it in iOS < 11. I could also use two different images, but I was looking for something cleaner, like a way to vertically center the image in the back button container view.

EDIT:

Turns out that, as said by banxii1988, the problem is caused by setBackButtonTitlePositionAdjustment when the values deliberately move the title outside the visible screen. That was an hack to avoid removing the back button title in every view controller. I decided to remove this hack and I did the right thing which is:

set the back button item in the storyboard to " ".

in each view controller without an associated storyboard, I set
the backBarButtonItem programmatically
navigationItem.backBarButtonItem = UIBarButtonItem(title: "",
style: .plain, target: nil, action: nil)

Note that the back button title that you see in a view controller is set in the previous one in the navigation stack.

答:
FOR SWIFT 3+

```<code>     if #available(iOS 11, *) {
            UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .normal)
            UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .highlighted)
     } else {
            UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0,
-60), for:UIBarMetrics.default)
        }
</code>```

Title: Custom back indicator image and iOS 11

Body:
I'm using a custom back button in my app. This custom back button is set globally like this:

    UINavigationBar.appearance().backIndicatorImage = UIImage(named: "Back").withRenderingMode(.alwaysOriginal)
    UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(asset: .back).withRenderingMode(.alwaysOriginal)

Before iOS 11 this code did the trick, but now in iOS 11 the button is not centered vertically anymore as you can see here:

I could change the height of the back button image to 44, but that would break it in iOS < 11. I could also use two different images, but I was looking for something cleaner, like a way to vertically center the image in the back button container view.

EDIT:

Turns out that, as said by banxii1988, the problem is caused by setBackButtonTitlePositionAdjustment when the values deliberately move the title outside the visible screen. That was an hack to avoid removing the back button title in every view controller. I decided to remove this hack and I did the right thing which is:

set the back button item in the storyboard to " ".

in each view controller without an associated storyboard, I set
the backBarButtonItem programmatically
navigationItem.backBarButtonItem = UIBarButtonItem(title: "",
style: .plain, target: nil, action: nil)

Note that the back button title that you see in a view controller is set in the previous one in the navigation stack.

Body:
FOR SWIFT 3+

     if #available(iOS 11, *) {
            UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .normal)
            UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .highlighted)
     } else {
            UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0,
-60), for:UIBarMetrics.default)
        }


问:
Angular property decorator adding to component's lifecycle hooks?
The following code allows me to add a @Test() to my component, however I need to add a command to the ngOnInit hook and it currently replaces the hook within the component.

```<code>function Test(value:any) {

  return function(target: any, propertyKey: string | symbol) {

    target.ngOnInit = () => {
      console.log("This replaces the component's hook")
    }

  }
}
</code>```

How do I just add to it?

答:
Decorators are actually just functions, A method decorator will be called with the value of the method it’s decorating, and a class decorator will be called with the class to be decorated.

Below decorator is just going to simply log the class to the console:

```<code>function Console(target) {
  console.log('Our decorated class', target);
}
</code>```

The target will in fact be the class that we decorate, which means we can now decorate any class with our decorator and see it outputted in the console:

```<code>@Console
class ExampleClass {
  constructor() {
    console.log('Yo!');
  }
}
</code>```

Taken this from link to detail decorator. And there are tons of example available in google.

Hope it helps.

Body:
The following code allows me to add a @Test() to my component, however I need to add a command to the ngOnInit hook and it currently replaces the hook within the component.

function Test(value:any) {

  return function(target: any, propertyKey: string | symbol) {

    target.ngOnInit = () => {
      console.log("This replaces the component's hook")
    }

  }
}

How do I just add to it?

Body:
Decorators are actually just functions, A method decorator will be called with the value of the method it’s decorating, and a class decorator will be called with the class to be decorated.

Below decorator is just going to simply log the class to the console:

function Console(target) {
  console.log('Our decorated class', target);
}

The target will in fact be the class that we decorate, which means we can now decorate any class with our decorator and see it outputted in the console:

@Console
class ExampleClass {
  constructor() {
    console.log('Yo!');
  }
}

Taken this from link to detail decorator. And there are tons of example available in google.

Hope it helps.


问:
Best way to handle dynamic css in a rails app
I'm researching a problem for handling dynamic css in a rails app.  Within the app, individual users and/or groups of users can have customized look and feel that is accomplished via CSS.  There will not be any fixed number of "look and feels" or css files, the number will grow as the number of users and groups grows and the look and feel is defined by the users via the  application's admin interface.  Throughout the course of a typical day thousands (it not tens of thousands) of different variations of the css will be served up.  The app will store the pre-built css in mongodb, so there it will not have to pay the price of constructing the css for every request, the question is more about how is the best way to serve up this dynamic css content.  I've seen other questions like [this one][1] that speak to using erb or sass, but some of these answers are dated by several years so I wanted to make sure there wasn't a better answer with Rails 3.</p>

答:
Well, I have worked with this a couple of times but they were definitely fixed no of CSS files to choose from. Its should be the same more or less.

One of things I used alot was the content_for blocks. Basically

```
<% content_for :css do %>
 // some css file or css content
<% end %>

```

And in the layout

```
<%=  yield :css %>
 ```

very simple way for managing the layouts.

Body:
Well, I have worked with this a couple of times but they were definitely fixed no of CSS files to choose from. Its should be the same more or less.

One of things I used alot was the content_for blocks. Basically

<% content_for :css do %>
 // some css file or css content
<% end %>

And in the layout

<%=  yield :css %>

very simple way for managing the layouts.


问:
Calculate sum ((v/u) * (d^a)) ^ (1/a) for large d and a
In R, I need to calculate sum((v/u) * (d^a))^(1/a) (see below) when d can be from 0 up to 10000 and a may be from 0 to 100. However, this overflows to Inf. v/u is dimensionless, as is a. I therefore assume that the result is on the same scale as d.

Is there a way to avoid the overflow in this calculation, either by some clever math, built-in functions, or by auto-scaling d, and then re-scaling the result without losing precision?

```<code>> N <- 200
> a <- 100
> v <- runif(N, min=1, max=20)
> u <- sum(v)
> d <- runif(N, min=1, max=8000)
> sum((v/u) * (d^a))^(1/a)
[1] Inf
</code>```

答:
I'm not sure if this is what you look for, but you can rescale your d vector

```<code>N <- 200
a <- 100
v <- runif(N, min=1, max=20)
u <- sum(v)
d <- runif(N, min=1, max=8000)
D <- max(d)
D*sum((v/u) * ((d/D)^a))^(1/a)
[1] 7721.741
</code>```

Here I used the maximum value, but you can get better results as long as D is large enough to avoid (d/D)^a reaching computer infinity.

The point is, if you choose D too small your sum is ruined because you get Inf in a term, but if you D is chosen excessively large some terms of your sum will be rounded to zero, which is less precise but definitely better than infinity.

Body:
In R, I need to calculate sum((v/u) * (d^a))^(1/a) (see below) when d can be from 0 up to 10000 and a may be from 0 to 100. However, this overflows to Inf. v/u is dimensionless, as is a. I therefore assume that the result is on the same scale as d.

Is there a way to avoid the overflow in this calculation, either by some clever math, built-in functions, or by auto-scaling d, and then re-scaling the result without losing precision?

> N <- 200
> a <- 100
> v <- runif(N, min=1, max=20)
> u <- sum(v)
> d <- runif(N, min=1, max=8000)
> sum((v/u) * (d^a))^(1/a)
[1] Inf

Body:
I'm not sure if this is what you look for, but you can rescale your d vector

N <- 200
a <- 100
v <- runif(N, min=1, max=20)
u <- sum(v)
d <- runif(N, min=1, max=8000)
D <- max(d)
D*sum((v/u) * ((d/D)^a))^(1/a)
[1] 7721.741

Here I used the maximum value, but you can get better results as long as D is large enough to avoid (d/D)^a reaching computer infinity.

The point is, if you choose D too small your sum is ruined because you get Inf in a term, but if you D is chosen excessively large some terms of your sum will be rounded to zero, which is less precise but definitely better than infinity.


问:
How to get binary representation of floating-point number in PHP?
Is there any way to get the binary representation of a floating point number in PHP? Something like Java's Double.doubleToRawLongBits().

Given a positive floating point number, I'd like to get the largest representable floating-point number which is less than that number. In Java, I can do it like this:

```<code>double x = Double.longBitsToDouble(Double.doubleToRawLongBits(d) - 1);
</code>```

But I'm not seeing anything similar in PHP.

答: This isn't a full answer, but the only way I know of to put a float into binary is with pack()</p>

Body:
Is there any way to get the binary representation of a floating point number in PHP? Something like Java's Double.doubleToRawLongBits().

Given a positive floating point number, I'd like to get the largest representable floating-point number which is less than that number. In Java, I can do it like this:

double x = Double.longBitsToDouble(Double.doubleToRawLongBits(d) - 1);

But I'm not seeing anything similar in PHP.


问:
Javascript ES6 spread operator on undefined
While developing my react App, I needed to send a conditional prop to a component so I found somewhere a pattern to do so, although it seems really weird to me and I couldn't understand how and why it worked.

If I type:

```<code>console.log(...undefined)   // Error
console.log([...undefined]) // Error
console.log({...undefined}) // Work
</code>```

When the spread operator is activated on undefined an error is raised, although when the undefined is inside an object, an empty object returned.

I'm quite surprised regarding this behavior, is that really how it supposed to be, can I rely on this and is that a good practice?

答:
This behavior is useful for doing something like optional spreading:

```<code>function foo(options) {
  const bar = {
    baz: 1,
    ...(options && options.bar) // options and bar can be undefined
  }
}
</code>```

And it gets even better with optional chaining, which is in Stage 4 now (and already available in TypeScript 3.7+):

```<code>function foo(options) {
  const bar = {
    baz: 1,
    ...options?.bar //options and bar can be undefined
  }
}
</code>```

a thought: its too bad it doesn't also work for spreading into an array

Body:
While developing my react App, I needed to send a conditional prop to a component so I found somewhere a pattern to do so, although it seems really weird to me and I couldn't understand how and why it worked.

If I type:

console.log(...undefined)   // Error
console.log([...undefined]) // Error
console.log({...undefined}) // Work

When the spread operator is activated on undefined an error is raised, although when the undefined is inside an object, an empty object returned.

I'm quite surprised regarding this behavior, is that really how it supposed to be, can I rely on this and is that a good practice?

Body:
This behavior is useful for doing something like optional spreading:

function foo(options) {
  const bar = {
    baz: 1,
    ...(options && options.bar) // options and bar can be undefined
  }
}

And it gets even better with optional chaining, which is in Stage 4 now (and already available in TypeScript 3.7+):

function foo(options) {
  const bar = {
    baz: 1,
    ...options?.bar //options and bar can be undefined
  }
}

a thought: its too bad it doesn't also work for spreading into an array


问:
Django 1.10 seed database without using fixtures
So I've looked at the documentation, as well as this SO question, and the django-seed package, but none of these seem to fit what I'm trying to do.

Basically, I want to programmatically seed my Games model from an external API, but all the information I can find seems to be reliant on generating a fixture first, which seems like an unnecessary step.

For example, in Ruby/Rails you can write directly to seed.rb and seed the database in anyway that's desired.

If a similar functionality available in Django, or do I need to generate the fixture first from the API, and then import it?

答: Would it work for you to write some class method on the  Games model that creates the data? Presumably this method query the external API, package up the Games() objects as a list called games and then use a Games.objects.bulk_create(games) to insert it into the database.


问:
I need to echo multiplication with decimals in bash
I am trying to multiply decimals and echo them

Here is what I have so far ...

```<code>#!/bin/bash

gbspace=1
limitUsers=2
limitInstances=2

echo $(($gbspace*0.5)) GB Webspace
echo limitUsers:$(($limitUsers*5))
echo limitUsers:$(($limitUsers*5)), limitInstances:$(($limitInstances)) \| Hi
</code>```

and this is what I get ...

```<code>root@home /home/work # bash run
run: line 7: 1*0.5: syntax error: invalid arithmetic operator (error token is ".5")
limitUsers:10
limitUsers:10, limitInstances:2 | Hi
</code>```

答:
Use bc which is pre-installed on most systems, with the -l flag to enable floating-point arithmetic:

```<code>echo $(echo "$gbspace*0.5" | bc -l) "GB Webspace"
</code>```

Note that you have to be careful with the quoting, and you have to pipe the expression you want to compute to bc with the echo command.

Body:
I am trying to multiply decimals and echo them

Here is what I have so far ...

#!/bin/bash

gbspace=1
limitUsers=2
limitInstances=2

echo $(($gbspace*0.5)) GB Webspace
echo limitUsers:$(($limitUsers*5))
echo limitUsers:$(($limitUsers*5)), limitInstances:$(($limitInstances)) \| Hi

and this is what I get ...

root@home /home/work # bash run
run: line 7: 1*0.5: syntax error: invalid arithmetic operator (error token is ".5")
limitUsers:10
limitUsers:10, limitInstances:2 | Hi

Body:
Use bc which is pre-installed on most systems, with the -l flag to enable floating-point arithmetic:

echo $(echo "$gbspace*0.5" | bc -l) "GB Webspace"

Note that you have to be careful with the quoting, and you have to pipe the expression you want to compute to bc with the echo command.


问:
Could syntax check for your code be taken as distinct step?
I've had a dispute with some colleges on should I take a syntax check after every code modification as a distinct step or I'd better rely on unit tests to catch possible syntax breakage ... ( of course unit tests do that ).

This is not a question whether to use or not tests for your code ( of course yes, but see below )

My use case is pretty simple, I am newbie in Python and try to play with some web application (MVC) by modifying model file. The changes are quite simple, indeed a couple or so lines at once, however as I am pretty unfamiliar with Python syntax, some stupid errors ( like wrong indentation, so on ) easily creep into.

The real hurdle is that I deploy an application via Google Cloud Platform ( as app engine ), so it takes a while for application comes up with new version and I can hit an endpoint and finally look into its error logs to understand what's happening. So I'd like to get a shorter and simple way - at least for these types of errors - just running syntax check before deploy.

The central part of the dispute was that I hadn't been advised to take a syntax check explicitly, but better relying on higher level tests for this ( units tests for example ), on what I say that:

1) And don't have unit tests yet ( and even if I had them I'd treat them as a next step in my test chain ).

2) I only edit a certain file ( one and only one ), with a minimum modifications, and MOSTLY the types of errors I have ( as I told as I am newbie in Python ) is syntax errors, not logic or semantic ones, so as I assume I am safe to have just syntax checking and then give it a deploy. And even though I hit a semantic/logic problems with my code later ( even syntax check pass ) this is a undoubtedly question for high level tests ( unit / acceptance so on) - but for now I'm just playing with a code written in a language I am not feel quite at home.

3) I don't commit my changes outside and don't trouble anyone.

4) the last argument is controversial, because it's a bit of the scope, however I'd like to leave it here - in some cases even lightweight unit tests might be overkill if ALL you need is to get a syntax check in a single file. Consider this example. One just edits the code in place, deployed at server trying to fix immediate issues, so no unit or other tests exists and you want to be sure that your modification won't break the code syntactically.

答: Personally speaking, if you drill into your head the PEP8 than most of the time syntax will come naturally i.e. like touch typing.  However, most of you know multiple languages so I can imagine it get hard remembering all :) </p>


问:
UINavigationController Back button doesn't hide title on iOS 11
I've updated my device to iOS 11 Beta yesterday and my app using this code in AppDelegate for hide back button title on all screen:

```<code>@implementation UINavigationItem (Customization)

/**
 Removes text from all default back buttons so only the arrow or custom image shows up.
 */
-(UIBarButtonItem *)backBarButtonItem
{
    return [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}
</code>```

It's working normally on older version but when I run my app on iOS 11 Beta, the title of back button still shown.
Does anyone face this problem? Is it a beta version bug of iOS or iOS 11 need another way to hide the back button title?

答:
FOR SWIFT 3+

Use below code to support iOS 9 to 11

```<code>     if #available(iOS 11, *) {
            UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .normal)
            UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .highlighted)
     } else {
            UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0,
-60), for:UIBarMetrics.default)
        }
</code>```

Body:
I've updated my device to iOS 11 Beta yesterday and my app using this code in AppDelegate for hide back button title on all screen:

@implementation UINavigationItem (Customization)

/**
 Removes text from all default back buttons so only the arrow or custom image shows up.
 */
-(UIBarButtonItem *)backBarButtonItem
{
    return [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

It's working normally on older version but when I run my app on iOS 11 Beta, the title of back button still shown.
Does anyone face this problem? Is it a beta version bug of iOS or iOS 11 need another way to hide the back button title?

Body:
FOR SWIFT 3+

Use below code to support iOS 9 to 11

     if #available(iOS 11, *) {
            UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .normal)
            UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .highlighted)
     } else {
            UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0,
-60), for:UIBarMetrics.default)
        }


问:
Tooltip doesn't let me type text when it is appeared. IDEA's editor
I am working with Itellij IDEA (2017.2.4). I am not sure whether the reason is new version of IDEA, but I started to face it after new version installed.

When I type some code in editor and Tooltip is shown (it can be inspection or just parameters of method shown ect.) I cannot type new symbols until pressing ESCAPE button, it is not useful for me. Before updating the IDEA there was behavior when user types new code, tooltip is hidden without ESCAPE pressing. It was made hidden by any key pressed.

Actually maybe I just change some setting property unconsciously, if yes - what is the property needed to be restored to default?

How to make it hidden not by ESCAPE but by any button?

In next image I pictured the moment when only ESCAPE key can be pressed.

答:
I'm not able to reproduce the issue, even when I use v2017.2.4 on windows. The behavior should be that you can still type even when the tooltip is present:

I can't think of anything in terms of settings that could cause this issue. If it's just the "parameter info" tooltip that is causing the issue, you can disable it (or just increase the delay time) from automatically popping up via the setting: Settings > Editor > Code Completion > "Parameter Info" > "Autopopup" You can then manually open it via the Parameter Info Action via Ctrl+P / ⌘P. The setting @Maciej-Białorucki mentioned will effect the time before other tooltips open. Setting to a high value might help if other tooltips are causing issues.

Personally, I find the auto popup useful. To troubleshoot why this is causing issues, I'd recommend trying the following:

Upgrade to v 2017.2.6 which was released yesterday. While I personally can't reproduce it, and I'm not seeing anything about it in the 2017.2.5 Release Notes nor the 2017.2.6 Release Notes, it can't hurt to try and upgrade.

Disable all third party plugins and restart IDEA. See if the issue persists. In my 14 years of using IDEA and helping people with it on the forums, I've seen 3rd party plugins having bugs that cause other parts of IDEA to misbehave. Since you recently upgraded, it's possible a 3rd party plugin is having a compatibility issue with the new version. If the disabling them solves it, use a binary search to as you re-enable the plugins to track down the culprit and then report the bug to the plugin's developer.

See if it happens in other projects. If not there may be something wrong with the project's configuration. (A long shot. But worth checking out)

As another long shot, you can try invalidating the caches and then restarting IDEA via File > Invalidate Caches / Restart... I have on occasion over the years seen a corrupted index file or cache cause strange behavior.

If none of the above work, I suggest opening a bug report with JetBrains at: https://youtrack.jetbrains.com


问:
There is an error in XML document (1, 1)
I have been trying to read data from XML. When I try to deserialize it, I get the following error:

"There is an error in XML document (1, 1)."

For your reference, I am attaching my entire code as well as my xml file.

C# Code:

```<code>CarCollection cars = null;
string path = @"C:\Users\harsha\Desktop\Doc.xml";
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
var reader = XmlReader.Create(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();
</code>```

Also,the data structure is as follows:

```<code>namespace XMLDataReader
{
   [Serializable()]
   public class Car
   {
       [System.Xml.Serialization.XmlElement("StockNumber")]
       public string StockNumber { get; set; }

       [System.Xml.Serialization.XmlElement("Make")]
       public string Make { get; set; }

       [System.Xml.Serialization.XmlElement("Model")]
       public string Model { get; set; }
   }

   [Serializable()]
   [System.Xml.Serialization.XmlRoot("CarCollection")]
   public class CarCollection
   {
       [XmlArray("Cars")]
       [XmlArrayItem("Car", typeof(Car))]
       public Car[] Car { get; set; }
   }
</code>```

XML File:

```<code>   <CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>
</code>```

Waiting for some help. Thanks in advance!

答: Your code works fine (with and without the XML declaration), the problem is most probably the content of your XML file. I guess the encoding is broken or there are some hidden special characters that look like regular characters but are something else (e.g. the < sign).

Body:
I have been trying to read data from XML. When I try to deserialize it, I get the following error:

"There is an error in XML document (1, 1)."

For your reference, I am attaching my entire code as well as my xml file.

C# Code:

CarCollection cars = null;
string path = @"C:\Users\harsha\Desktop\Doc.xml";
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
var reader = XmlReader.Create(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();

Also,the data structure is as follows:

namespace XMLDataReader
{
   [Serializable()]
   public class Car
   {
       [System.Xml.Serialization.XmlElement("StockNumber")]
       public string StockNumber { get; set; }

       [System.Xml.Serialization.XmlElement("Make")]
       public string Make { get; set; }

       [System.Xml.Serialization.XmlElement("Model")]
       public string Model { get; set; }
   }

   [Serializable()]
   [System.Xml.Serialization.XmlRoot("CarCollection")]
   public class CarCollection
   {
       [XmlArray("Cars")]
       [XmlArrayItem("Car", typeof(Car))]
       public Car[] Car { get; set; }
   }

XML File:

   <CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>

Waiting for some help. Thanks in advance!


问:
How do I fix an "Invalid license data. Reinstall is required." error in Visual C# 2010 Express?
I've tried to install Visual C# 2010 Express edition onto my PC, but whenever I try to run it, I get a error message.

Invalid license data. Reinstall is required.

I've already tried reinstalling it, and the message persists.

OS is Vista Home Premium. I already have VC# 2008 Express installed.

答:
If you're here from Google and are experiencing this issue with GFI MailEssentials's config export tool, check to make sure you aren't trying to open WebMon.SettingsImporterTool.exe.xml instead of WebMon.SettingsImporterTool.exe

If you have "hide common file extensions" enabled, you will see the .exe but not the .xml


问:
Accessing Hovertext with html
I am trying to access hover text found on graph points at this site (bottom):

http://matchhistory.na.leagueoflegends.com/en/#match-details/TRLH1/1002200043?gameHash=b98e62c1bcc887e4&tab=overview

I have the full site html but I am unable to find the values displayed in the hover text. All that can be seen when inspecting a point are x and y values that are transformed versions of these values. The mapping can be determined with manual input taken from the hovertext but this defeats the purpose of looking at the html. Additionally, the mapping changes with each match history so it is not feasible to do this for a large number of games.

Is there any way around this?

thank you

答:
Explanation

Nearly everything on this webpage is loaded via JSON through JavaScript.  We don't even have to request the original page.  You will, however, have to repiece together the page via id's of items, mysteries and etc., which won't be too hard because you can request masteries similar to how we fetch items.

So, I went through the network tab in inspect and I noticed that it loaded the following JSON formatted URL:

https://acs.leagueoflegends.com/v1/stats/game/TRLH1/1002200043?gameHash=b98e62c1bcc887e4

If you notice, there is a gameHash and the id (similar to that of the link you just sent me).  This page contains everything you need to rebuild it, given that you fetch all reliant JSON files.

Dealing with JSON

You can use json.loads in Python to load it, but a great tool I would recomend is:

https://jsonformatter.curiousconcept.com/

You copy and paste JSON in there and it will  help you understand the data structure.

Fetching items

The webpage loads all this information via a JSON file:

https://ddragon.leagueoflegends.com/cdn/7.10.1/data/en_US/item.json

It contains all of the information and tool tips about each item in the game. You can access your desired item via: theirJson['data']['1001'].  Each image on the page's file name is the id (or 1001) in this example.

For instance, for 'Boots of Speed':

```<code>import requests, json

itemJson = json.loads(requests.get('https://ddragon.leagueoflegends.com/cdn/7.10.1/data/en_US/item.json').text)
print(itemJson['data']['1001'])
</code>```

An alternative: Selenium

Selenium could be used for this.  You should look it up.  It's been ported for several programming languages, one being Python.  It may work as you want it to here, but I sincerely think that the JSON method (describe above), although a little more convoluted, will perform faster (since speed, based on your post, seems to be an important factor).

Title: Accessing Hovertext with html

Body:
Explanation

Nearly everything on this webpage is loaded via JSON through JavaScript.  We don't even have to request the original page.  You will, however, have to repiece together the page via id's of items, mysteries and etc., which won't be too hard because you can request masteries similar to how we fetch items.

So, I went through the network tab in inspect and I noticed that it loaded the following JSON formatted URL:

https://acs.leagueoflegends.com/v1/stats/game/TRLH1/1002200043?gameHash=b98e62c1bcc887e4

If you notice, there is a gameHash and the id (similar to that of the link you just sent me).  This page contains everything you need to rebuild it, given that you fetch all reliant JSON files.

Dealing with JSON

You can use json.loads in Python to load it, but a great tool I would recomend is:

https://jsonformatter.curiousconcept.com/

You copy and paste JSON in there and it will  help you understand the data structure.

Fetching items

The webpage loads all this information via a JSON file:

https://ddragon.leagueoflegends.com/cdn/7.10.1/data/en_US/item.json

It contains all of the information and tool tips about each item in the game. You can access your desired item via: theirJson['data']['1001'].  Each image on the page's file name is the id (or 1001) in this example.

For instance, for 'Boots of Speed':

import requests, json

itemJson = json.loads(requests.get('https://ddragon.leagueoflegends.com/cdn/7.10.1/data/en_US/item.json').text)
print(itemJson['data']['1001'])

An alternative: Selenium

Selenium could be used for this.  You should look it up.  It's been ported for several programming languages, one being Python.  It may work as you want it to here, but I sincerely think that the JSON method (describe above), although a little more convoluted, will perform faster (since speed, based on your post, seems to be an important factor).


问:
Powershell ps1 file fails but code is good
When I run my Powershell script from the command line, it fails, however if I copy line by line and run it in Powershell Console it runs fine.

```<code>powershell -ExecutionPolicy Bypass -File "F:\email.ps1" -FFFeatureOff
</code>```

yields:

At F:\email.ps1:16 char:126
  + ... ential("username", "password");
  +                                                                       ~~~ The string is missing the terminator: ".

At F:\email.ps1:9 char:1
  + {
  + ~ Missing closing '}' in statement block or type definition.

Its just really odd if I open powershell window and paste the script in, it works, but running the ps1 file I get the error, even in the editor I get the same issues

Full Script:

```<code>$EmailTo = "xxxxx"
$EmailFrom = "xxxxxx"
$Subject = "LicenceKey & Instructions"
$Body = "This is an automated email"
$SMTPServer = "smtp.gmail.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$files=Get-ChildItem "C:\Users\alber\Desktop\LicenceKey\newuser"
Foreach($file in $files)
{
    Write-Host “Attaching File :- ” $file
    $attachment = New-Object System.Net.Mail.Attachment –ArgumentList "C:\Users\alber\Desktop\LicenceKey\newuser\$file"
    $SMTPMessage.Attachments.Add($attachment)
}
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password");
$SMTPClient.Send($SMTPMessage)
</code>```

答:
The fact that James C.'s answer was accepted by the OP suggests that it was motivated by the OP's gratitude for the generally helpful, but non-specific - and ultimately potentially confusing - pointers contained in it.

Unfortunately, it falls short as an answer of general interest to future readers and is likely to cause confusion; as of this writing:

It contains an overtly incorrect claim:

The issue here is that the $file is outside the param for the message, moving the quote will fix that: Write-Host “Attaching File :- $file”

However, there is no problem with Write-Host “Attaching File :- ” $file, because Write-Host simply concatenates multiple arguments with spaces - no strict need for a single argument.

(As stated, PowerShell recognizes "smart quotes" (non-ASCII quotes), assuming they're properly encoded - see below).

It does not explain the OP's symptoms as posted.

It almost makes it sound as if it weren't possible to embed a literal " - or $, for that matter - in a double-quoted string due to a limitation in PowerShell, which, of course, isn't true; escaping with backticks is all that is needed: "Pa`$`$`"w0rd".

Instead, PetSerAl's helpful comments on the question presumably point to the actual answer:

There may be a character encoding issue, given that "smart quotes" (non-ASCII quote characters) are used, which would surface in an incorrectly encoded script file.

PetSerAl's answer here suggests that UTF-8-encoded script content must be saved to a file with a BOM in order for PowerShell to recognize the encoding.

Update: PetSerAl surmises that the "actual troublemaker is an EN DASH here:

–ArgumentList, which, when improperly decoded: [Text.Encoding]::GetEncoding(1250).GetString([Text.Encoding]::UTF8.GetBytes('–')), yields â€“, an unpaired double quote."

Body:
When I run my Powershell script from the command line, it fails, however if I copy line by line and run it in Powershell Console it runs fine.

powershell -ExecutionPolicy Bypass -File "F:\email.ps1" -FFFeatureOff

yields:

At F:\email.ps1:16 char:126
  + ... ential("username", "password");
  +                                                                       ~~~ The string is missing the terminator: ".

At F:\email.ps1:9 char:1
  + {
  + ~ Missing closing '}' in statement block or type definition.

Its just really odd if I open powershell window and paste the script in, it works, but running the ps1 file I get the error, even in the editor I get the same issues

Full Script:

$EmailTo = "xxxxx"
$EmailFrom = "xxxxxx"
$Subject = "LicenceKey & Instructions"
$Body = "This is an automated email"
$SMTPServer = "smtp.gmail.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$files=Get-ChildItem "C:\Users\alber\Desktop\LicenceKey\newuser"
Foreach($file in $files)
{
    Write-Host “Attaching File :- ” $file
    $attachment = New-Object System.Net.Mail.Attachment –ArgumentList "C:\Users\alber\Desktop\LicenceKey\newuser\$file"
    $SMTPMessage.Attachments.Add($attachment)
}
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password");
$SMTPClient.Send($SMTPMessage)


问:
how to change textbox data remotely by tcp socket in QT?
i would like to code a program by Qt tcp socket and QML together.
i am going to change a textbox variable that created by QML to the new data that get by remote client by tcp socket?
my snippet code is :

```<code>void Server::startRead()
{

   client->waitForReadyRead(3000);
   QString buf=  client->readAll();
   qDebug() << buf;
   QQmlApplicationEngine engine;
   engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

   QObject *rootObject = engine.rootObjects().first();
   QObject *qmlObject = rootObject->findChild<QObject*>("ttt");
   qDebug() << "before change"
   qDebug() << qmlObject->property("text");
   qmlObject->setProperty("text", "new data");
   qDebug() << "after change"
   qDebug() << qmlObject->property("text");

 }
</code>```

main.qml

```<code>import QtQuick 2.0
import QtQuick 2.2
import QtQuick.Window 2.1
import QtQuick.Window 2.2
import QtQuick.Controls 1.2

Window{
    width:400
    height:400
    visible:true

    Item {
      id: rootItem
      property string text
      Text {
        id: message
        text: rootItem.text
      }
    }

}
</code>```

I really appreciate it.

答:
There are many ways to do that. Next examples demonstrate how to change qml element properties from cpp. If you need to change visibility just use bool properties instead of string that i used in examples.

1. This is good solution i think.

You could create qml adapter

```<code>class ServerQMLAdapter : public QQuickItem
{
    Q_OBJECT
Q_PROPERTY(QString data READ data WRITE setData NOTIFY dataChanged)
public:
  explicit ServerQMLAdapter(QQuickItem *parent = nullptr) : QQuickItem(parent){}
  QString data() const {
    return mData;
  }
  void setData(const QString &data) {
    if(mData == data)
      return;
    mData = data;
    emit dataChanged();
  }
private slots:
/**
this slots called on data read
*/
  void onDataRead(const QString &data) {
    setData(data);
  }
private:
  QString mData = QString();
};
</code>```

in application class you sould register your adapter

```<code>qmlRegisterType<ServerQMLAdapter>("ServerQMLAdapter", 1, 0, "ServerQMLAdapter");
</code>```

After that you can use it in your qml file

```<code>import ServerQMLAdapter 1.0
Item {
  ServerQMLAdapter {
    id: myAdapter
  }
  Text {
    id: message
    text: myAdapter.data
  }
}
</code>```

2. You can change properties from cpp.

Just like you do in your snippet

```<code>auto rootObject = engine.rootObjects().first();
rootObject->setProperty("text", "new data");
</code>```

and add this propetry to your qml file

```<code>Item {
  id: rootItem
  property string text
  Text {
    id: message
    text: rootItem.text
  }
}
</code>```

3. Use invoked methods

From you cpp file

```<code>auto rootObject = engine.rootObjects().first();
QMetaObject::invokeMethod(rootObject, "setText",
                              Q_ARG(QVariant, QVariant::fromValue(data)));
</code>```

and add function to your qml file

```<code>Item {
  id: rootItem
  function setText(data) {
    message.text = data;
  }
  Text {
    id: message
  }
}
</code>```

Body:
i would like to code a program by Qt tcp socket and QML together.
i am going to change a textbox variable that created by QML to the new data that get by remote client by tcp socket?
my snippet code is :

void Server::startRead()
{

   client->waitForReadyRead(3000);
   QString buf=  client->readAll();
   qDebug() << buf;
   QQmlApplicationEngine engine;
   engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

   QObject *rootObject = engine.rootObjects().first();
   QObject *qmlObject = rootObject->findChild<QObject*>("ttt");
   qDebug() << "before change"
   qDebug() << qmlObject->property("text");
   qmlObject->setProperty("text", "new data");
   qDebug() << "after change"
   qDebug() << qmlObject->property("text");

 }

main.qml

import QtQuick 2.0
import QtQuick 2.2
import QtQuick.Window 2.1
import QtQuick.Window 2.2
import QtQuick.Controls 1.2

Window{
    width:400
    height:400
    visible:true

    Item {
      id: rootItem
      property string text
      Text {
        id: message
        text: rootItem.text
      }
    }

}

I really appreciate it.

Body:
There are many ways to do that. Next examples demonstrate how to change qml element properties from cpp. If you need to change visibility just use bool properties instead of string that i used in examples.

1. This is good solution i think.

You could create qml adapter

class ServerQMLAdapter : public QQuickItem
{
    Q_OBJECT
Q_PROPERTY(QString data READ data WRITE setData NOTIFY dataChanged)
public:
  explicit ServerQMLAdapter(QQuickItem *parent = nullptr) : QQuickItem(parent){}
  QString data() const {
    return mData;
  }
  void setData(const QString &data) {
    if(mData == data)
      return;
    mData = data;
    emit dataChanged();
  }
private slots:
/**
this slots called on data read
*/
  void onDataRead(const QString &data) {
    setData(data);
  }
private:
  QString mData = QString();
};

in application class you sould register your adapter

qmlRegisterType<ServerQMLAdapter>("ServerQMLAdapter", 1, 0, "ServerQMLAdapter");

After that you can use it in your qml file

import ServerQMLAdapter 1.0
Item {
  ServerQMLAdapter {
    id: myAdapter
  }
  Text {
    id: message
    text: myAdapter.data
  }
}

2. You can change properties from cpp.

Just like you do in your snippet

auto rootObject = engine.rootObjects().first();
rootObject->setProperty("text", "new data");

and add this propetry to your qml file

Item {
  id: rootItem
  property string text
  Text {
    id: message
    text: rootItem.text
  }
}

3. Use invoked methods

From you cpp file

auto rootObject = engine.rootObjects().first();
QMetaObject::invokeMethod(rootObject, "setText",
                              Q_ARG(QVariant, QVariant::fromValue(data)));

and add function to your qml file

Item {
  id: rootItem
  function setText(data) {
    message.text = data;
  }
  Text {
    id: message
  }
}


问:
How to debug an AppRegistryNotReady exception in Django 1.9?
I am migrating a large project from Django 1.8 to Django 1.9, and when I try to run the project, I get a AppRegistryNotReady exception.  The traceback for this problem seems completely unhelpful.

```<code>Traceback (most recent call last):
  File "/opt/project/myproject/manage.py", line 16, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 342, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 176, in fetch_command
    commands = get_commands()
  File "/usr/local/lib/python2.7/dist-packages/django/utils/lru_cache.py", line 100, in wrapper
    result = user_function(*args, **kwds)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 71, in get_commands
    for app_config in reversed(list(apps.get_app_configs())):
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 137, in get_app_configs
    self.check_apps_ready()
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
</code>```

Since nothing in the backtrace is my project's code, how can I go about tracking down the source of this problem?

答: Since this error might occur when you have an app in your INSTALLED_APPS that is not installed properly, try commenting out the apps to try to find which is causing the problem.

Body:
I am migrating a large project from Django 1.8 to Django 1.9, and when I try to run the project, I get a AppRegistryNotReady exception.  The traceback for this problem seems completely unhelpful.

Traceback (most recent call last):
  File "/opt/project/myproject/manage.py", line 16, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 342, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 176, in fetch_command
    commands = get_commands()
  File "/usr/local/lib/python2.7/dist-packages/django/utils/lru_cache.py", line 100, in wrapper
    result = user_function(*args, **kwds)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 71, in get_commands
    for app_config in reversed(list(apps.get_app_configs())):
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 137, in get_app_configs
    self.check_apps_ready()
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Since nothing in the backtrace is my project's code, how can I go about tracking down the source of this problem?


问:
In Firefox Quantum, how can I get rid of the tab bar, want Tree Style Tabs only
I'm a long time user of the "Tree Style Tabs" add-on of Firefox.  As a matter of fact it is the reason why I use Firefox

Firefox automatically upgraded to their new version, Firefox Quantum.  Now there's an annoying bar of tabs across the top which is redundant because the Tree Style Tabs also puts the tabs on the left.

Is there a way I can disable tabs on the top bar?  If not, is there a way I can go back to an old version of Firefox and not have it update to Firefox Quantum?

答:
Through further research I realized that my question is a duplicate of the one posted here.

The answer there worked for me, though it was a bit of a pain (requires creating a text file in a magic place, and the first time I tried I put it in the wrong place).  It would be nice if this was a configuration option provided in Firefox's menus.