问:
WCF in IIS, using MSMQ in workgroup mode
I've been trying out MSMQ with WCF, but I can't seem to get it to work properly. I've got the client (which sends messages to the queue) working, by using WCF and a service reference. The code that does this is more or less this:

```<code>static void Main(string[] args)
{
    var client = new MsmqServiceReference.MsmqContractClient();
    client.SendMessage("TEST");
    client.Close();
    Console.ReadKey();
}
</code>```

Where MsmqContractClient is a proxy generated by visual studio when I add a service reference. The endpoint in the app.config is pointing to a msmqueue:

```<code><client>
  <endpoint
    address="net.msmq://localhost/private/MsmqService/MsmqService.svc"
    binding="netMsmqBinding"
    bindingConfiguration="MsmqBindingNonTransactionalNoSecurity"
    contract="MsmqServiceReference.IMsmqContract" name="MsmqService" />
</client>
</code>```

This works, messages are being posted to the queue.

Now I am trying to actually get the service to work, but I keep getting this error:

Binding validation failed because the
  binding's MsmqAuthenticationMode
  property is set to WindowsDomain but
  MSMQ is installed with Active
  Directory integration disabled. The
  channel factory or service host cannot
  be opened.

Things I've tried are:

give everyone full access (including anonymous logon) to the queue

configuring the app to use a specific binding from the config file using:

```<code><bindings>
  <netMsmqBinding>
     <binding name="MsmqBindingNonTransactionalNoSecurity"
              deadLetterQueue="Custom"
              exactlyOnce="false">
       <security mode="None" />
     </binding>
  </netMsmqBinding>
</bindings>
</code>```

I tried running the app pool in IIS (7) under my own account and administrator account

What stumps me is that it keeps trying to convince me that I am trying to run it with WindowsDomain authentication. I stated that I DIDN'T want to do that with the security mode set to none, right?

My app at the moment is simply a webforms asp.net site with a WCF service added to it.

If someone could at least point me into the right direction I'll be very grateful, as I've spent too much time on this already.

It seems as if the configuration is being ignored, or overridden. The full error message:

```<code>WebHost failed to process a request.
 Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/63721755
 Exception: System.ServiceModel.ServiceActivationException: The service '/MsmqService/MsmqService.svc' cannot be activated due to an exception during compilation.  The exception message is: Binding validation failed because the binding's MsmqAuthenticationMode property is set to WindowsDomain but MSMQ is installed with Active Directory integration disabled. The channel factory or service host cannot be opened.. ---> System.InvalidOperationException: Binding validation failed because the binding's MsmqAuthenticationMode property is set to WindowsDomain but MSMQ is installed with Active Directory integration disabled. The channel factory or service host cannot be opened.
   at System.ServiceModel.Channels.MsmqVerifier.VerifySecurity(MsmqTransportSecurity security, Nullable`1 useActiveDirectory)
   at System.ServiceModel.Channels.MsmqVerifier.VerifyReceiver(MsmqReceiveParameters receiveParameters, Uri listenUri)
   at System.ServiceModel.Channels.MsmqTransportBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.MessageEncodingBindingElement.InternalBuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BinaryMessageEncodingBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.Binding.BuildChannelListener[TChannel](Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, BindingParameterCollection parameters)
   at System.ServiceModel.Description.DispatcherBuilder.MaybeCreateListener(Boolean actuallyCreate, Type[] supportedChannels, Binding binding, BindingParameterCollection parameters, Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, ServiceThrottle throttle, IChannelListener& result, Boolean supportContextSession)
   at System.ServiceModel.Description.DispatcherBuilder.BuildChannelListener(StuffPerListenUriInfo stuff, ServiceHostBase serviceHost, Uri listenUri, ListenUriMode listenUriMode, Boolean supportContextSession, IChannelListener& result)
   at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
   at System.ServiceModel.ServiceHostBase.InitializeRuntime()
   at System.ServiceModel.ServiceHostBase.OnBeginOpen()
   at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open()
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
   --- End of inner exception stack trace ---
   at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
 Process Name: w3wp
 Process ID: 5660
</code>```

I tried figuring out what happens using Reflector, but it simply seems that somehow a MsmqTransportBindingElement is passed into the channel building process, which is convinced it has to use WindowsDomain as a security measure. However, I have security set to none in my config file. Any ideas on where this override behavior comes from?

Resolution:

I feel really stupid on one hand, but I feel there's room for improvement on the other hand.
The short version is that I messed up the value in the 'name' attribute on the service element:

```<code><services>
  <service name="WcfService.MsmqService">
    <!--        <endpoint binding="mexHttpBinding" contract="IMetadataExchange" />-->
    <endpoint name="msmq"
            address="net.msmq://localhost/private/MsmqService/MsmqService.svc"
            binding="netMsmqBinding"
            bindingConfiguration="NoSecurity"
            contract="WcfService.IMsmqContract" />
  </service>
</services>
</code>```

The name was the same as on my client, however, the client had bindings generated by visual studio. I gave it a different name (MsmqService), so the name value was 'MsmqService.MsmqService'.

What kinda bothers me is that I didn't get any warning whatsoever that I was configuring a non-existing service, or any indication I am using the default configuration for the service. It would be really nice if the framework would at least generate a warning somewhere that I am using defaults, or an option to turn on some form of strict mode. Either way, thanks for all your input, and I am going to bang my head against the wall a few more times.

And yes, you may now point and laugh ;-)

答:
Dennis van der Stelt provide a good sample on WCF + MSMQ.

You may also be interested in this Q/A on MSDN:

Q: When I run the sample that uses a default binding in workgroup mode, messages seem to get sent but are never received by the receiver.

A: By default, messages are signed using an MSMQ internal certificate that requires the Active Directory directory service. In workgroup mode, because Active Directory is not available, signing the message fails. So the message lands in the dead-letter queue and failure cause, such as “Bad signature”, is indicated.

The workaround is to turn off security. This is done by setting Mode = None to make it work in workgroup mode.

Another workaround is to get the MsmqTransportSecurity from the Transport property and set it to Certificate, and set the client certificate.

Yet another workaround is to install MSMQ with Active Directory integration.

Body:
I've been trying out MSMQ with WCF, but I can't seem to get it to work properly. I've got the client (which sends messages to the queue) working, by using WCF and a service reference. The code that does this is more or less this:

static void Main(string[] args)
{
    var client = new MsmqServiceReference.MsmqContractClient();
    client.SendMessage("TEST");
    client.Close();
    Console.ReadKey();
}

Where MsmqContractClient is a proxy generated by visual studio when I add a service reference. The endpoint in the app.config is pointing to a msmqueue:

<client>
  <endpoint
    address="net.msmq://localhost/private/MsmqService/MsmqService.svc"
    binding="netMsmqBinding"
    bindingConfiguration="MsmqBindingNonTransactionalNoSecurity"
    contract="MsmqServiceReference.IMsmqContract" name="MsmqService" />
</client>

This works, messages are being posted to the queue.

Now I am trying to actually get the service to work, but I keep getting this error:

Binding validation failed because the
  binding's MsmqAuthenticationMode
  property is set to WindowsDomain but
  MSMQ is installed with Active
  Directory integration disabled. The
  channel factory or service host cannot
  be opened.

Things I've tried are:

give everyone full access (including anonymous logon) to the queue

configuring the app to use a specific binding from the config file using:

<bindings>
  <netMsmqBinding>
     <binding name="MsmqBindingNonTransactionalNoSecurity"
              deadLetterQueue="Custom"
              exactlyOnce="false">
       <security mode="None" />
     </binding>
  </netMsmqBinding>
</bindings>

I tried running the app pool in IIS (7) under my own account and administrator account

What stumps me is that it keeps trying to convince me that I am trying to run it with WindowsDomain authentication. I stated that I DIDN'T want to do that with the security mode set to none, right?

My app at the moment is simply a webforms asp.net site with a WCF service added to it.

If someone could at least point me into the right direction I'll be very grateful, as I've spent too much time on this already.

It seems as if the configuration is being ignored, or overridden. The full error message:

WebHost failed to process a request.
 Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/63721755
 Exception: System.ServiceModel.ServiceActivationException: The service '/MsmqService/MsmqService.svc' cannot be activated due to an exception during compilation.  The exception message is: Binding validation failed because the binding's MsmqAuthenticationMode property is set to WindowsDomain but MSMQ is installed with Active Directory integration disabled. The channel factory or service host cannot be opened.. ---> System.InvalidOperationException: Binding validation failed because the binding's MsmqAuthenticationMode property is set to WindowsDomain but MSMQ is installed with Active Directory integration disabled. The channel factory or service host cannot be opened.
   at System.ServiceModel.Channels.MsmqVerifier.VerifySecurity(MsmqTransportSecurity security, Nullable`1 useActiveDirectory)
   at System.ServiceModel.Channels.MsmqVerifier.VerifyReceiver(MsmqReceiveParameters receiveParameters, Uri listenUri)
   at System.ServiceModel.Channels.MsmqTransportBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.MessageEncodingBindingElement.InternalBuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BinaryMessageEncodingBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.Binding.BuildChannelListener[TChannel](Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, BindingParameterCollection parameters)
   at System.ServiceModel.Description.DispatcherBuilder.MaybeCreateListener(Boolean actuallyCreate, Type[] supportedChannels, Binding binding, BindingParameterCollection parameters, Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, ServiceThrottle throttle, IChannelListener& result, Boolean supportContextSession)
   at System.ServiceModel.Description.DispatcherBuilder.BuildChannelListener(StuffPerListenUriInfo stuff, ServiceHostBase serviceHost, Uri listenUri, ListenUriMode listenUriMode, Boolean supportContextSession, IChannelListener& result)
   at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
   at System.ServiceModel.ServiceHostBase.InitializeRuntime()
   at System.ServiceModel.ServiceHostBase.OnBeginOpen()
   at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open()
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
   --- End of inner exception stack trace ---
   at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
 Process Name: w3wp
 Process ID: 5660

I tried figuring out what happens using Reflector, but it simply seems that somehow a MsmqTransportBindingElement is passed into the channel building process, which is convinced it has to use WindowsDomain as a security measure. However, I have security set to none in my config file. Any ideas on where this override behavior comes from?

Resolution:

I feel really stupid on one hand, but I feel there's room for improvement on the other hand.
The short version is that I messed up the value in the 'name' attribute on the service element:

<services>
  <service name="WcfService.MsmqService">

    <endpoint name="msmq"
            address="net.msmq://localhost/private/MsmqService/MsmqService.svc"
            binding="netMsmqBinding"
            bindingConfiguration="NoSecurity"
            contract="WcfService.IMsmqContract" />
  </service>
</services>

The name was the same as on my client, however, the client had bindings generated by visual studio. I gave it a different name (MsmqService), so the name value was 'MsmqService.MsmqService'.

What kinda bothers me is that I didn't get any warning whatsoever that I was configuring a non-existing service, or any indication I am using the default configuration for the service. It would be really nice if the framework would at least generate a warning somewhere that I am using defaults, or an option to turn on some form of strict mode. Either way, thanks for all your input, and I am going to bang my head against the wall a few more times.

And yes, you may now point and laugh ;-)


来源: stackexchange

问:
iOS : bar button doesn't appear
Hi I have two View Controller. there is two segue from first vc to the second vc.I have implemented (with code) right bar button and back button and title in second vc in the view did load .when I segue with button I can see them but when I segue by view controller(for choosing table view cell (did select)) I don't see them

how should I fix them???

this is in the second view did load

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    let img = UIImage(named: "delBtn")
    if let top = self.navigationController?.navigationBar.topItem {
        top.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    }
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: img, style: .plain, target: self, action: #selector(dele))
    self.navigationItem.title = "Add/Edit"
    pickerS.delegate = self
    pickerS.dataSource = self
    getMajor()
    if preStudent != nil {
        receivedData()
    }
}
</code>```

this is segue of first view controller

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let con = controller.fetchedObjects, con.count > 0 {
        let obj = con[indexPath.row]
        performSegue(withIdentifier: "edit", sender: obj)
    }
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if  segue.identifier == "edit" {
        if let des = segue.destination as? EditVC {
            if let obj = sender as? Student {
                des.preStudent = obj
            }
        }
    }
}
</code>```

答: Navigation bar is inherited from parent view controller. If your parent view controller is embedded in a navigation controller and you push to a child view controller, your child view controller will have the navigation bar automatically, and thus have the navigation bar items. In your storyboard, check to make sure your segue type is set to show & push. If it's set to present modally, you will lose your navigation bar in your child controller.

ContentLicense: CC BY-SA 3.0

Title: iOS : bar button doesn't appear

Body:
Hi I have two View Controller. there is two segue from first vc to the second vc.I have implemented (with code) right bar button and back button and title in second vc in the view did load .when I segue with button I can see them but when I segue by view controller(for choosing table view cell (did select)) I don't see them

how should I fix them???

this is in the second view did load

override func viewDidLoad() {
    super.viewDidLoad()
    let img = UIImage(named: "delBtn")
    if let top = self.navigationController?.navigationBar.topItem {
        top.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    }
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: img, style: .plain, target: self, action: #selector(dele))
    self.navigationItem.title = "Add/Edit"
    pickerS.delegate = self
    pickerS.dataSource = self
    getMajor()
    if preStudent != nil {
        receivedData()
    }
}

this is segue of first view controller

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let con = controller.fetchedObjects, con.count > 0 {
        let obj = con[indexPath.row]
        performSegue(withIdentifier: "edit", sender: obj)
    }
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if  segue.identifier == "edit" {
        if let des = segue.destination as? EditVC {
            if let obj = sender as? Student {
                des.preStudent = obj
            }
        }
    }
}


问:
Sort month and year in R
I want to sort the month-year data in r, I tried using this

```<code>Data_Full$Year_Month <- paste(Data_Full$Year, Data_Full$Month, sep = "")
for(i in 1: length(Data_Full$Year_Month)){

  if(length(Data_Full$Year_Monthi[i] == 5)){
    Data_Full$Year_Month[i] <- paste(substr(Data_Full$Year_Month[i], 1, 4), "0", substr(Data_Full$Year_Month[i], 5, nchar(Data_Full$Year_Month[i])), sep = "")

  } else

  {
    Data_Full$Year_Month[i] <- Data_Full$Year_Month[i]

  }
  i

}
</code>```

Once I get this I will sort it, but I unable to do it

答:
This code will give you back a new date column, which you can then sort normally.</p>

```<code># Test dataframe
Data_Full <- data.frame(Year = rep(2017,12),
                        Month = c(12:1))

# Create a date column from Month and Year
Data_Full$Date <- as.Date(apply(Data_Full, 1, function(x){
                                                paste0(x["Year"], ifelse(nchar(as.character(x["Month"])) == 2, x["Month"], paste0(0,x["Month"])), "01")
                                              }), format = "%Y%m%d")

# Order dataframe by date
Data_Full <- Data_Full[with(Data_Full, order(Date)),]
</code>```

Title: Sort month and year in R

Body:
I want to sort the month-year data in r, I tried using this

Data_Full$Year_Month <- paste(Data_Full$Year, Data_Full$Month, sep = "")
for(i in 1: length(Data_Full$Year_Month)){

  if(length(Data_Full$Year_Monthi[i] == 5)){
    Data_Full$Year_Month[i] <- paste(substr(Data_Full$Year_Month[i], 1, 4), "0", substr(Data_Full$Year_Month[i], 5, nchar(Data_Full$Year_Month[i])), sep = "")

  } else

  {
    Data_Full$Year_Month[i] <- Data_Full$Year_Month[i]

  }
  i

}

Once I get this I will sort it, but I unable to do it

Body:
This code will give you back a new date column, which you can then sort normally.

# Test dataframe
Data_Full <- data.frame(Year = rep(2017,12),
                        Month = c(12:1))

# Create a date column from Month and Year
Data_Full$Date <- as.Date(apply(Data_Full, 1, function(x){
                                                paste0(x["Year"], ifelse(nchar(as.character(x["Month"])) == 2, x["Month"], paste0(0,x["Month"])), "01")
                                              }), format = "%Y%m%d")

# Order dataframe by date
Data_Full <- Data_Full[with(Data_Full, order(Date)),]


问:
jquery/javascript: $(document).trigger vs normal function call?
I just saw two javascript files:

first one had called following line after some success ajax call:

```<code>$(document).trigger("locationloaded");
</code>```

The second js had:

```<code>$(document).on('locationloaded', function () {
   //few lines of code here
});
</code>```

Bit new to JS, just curious to know, could there be any valid reason for calling locationloaded through trigger? Why can't we have simple function as locationloaded() which would be called from first js? If both do the same work, which one should be used?

答:
As per documentation of jQuery trigger

Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method.

Body:
I just saw two javascript files:

first one had called following line after some success ajax call:

$(document).trigger("locationloaded");

The second js had:

$(document).on('locationloaded', function () {
   //few lines of code here
});

Bit new to JS, just curious to know, could there be any valid reason for calling locationloaded through trigger? Why can't we have simple function as locationloaded() which would be called from first js? If both do the same work, which one should be used?


问:
What does "leaking the Activity" mean and how do I prevent it?
I often see advice like "Don't do X this way or else you risk leaking the Activity / Context."

I don't actually know what "leaking" means or how to know that you're at risk of leaking. Can anyone elaborate?

答:
Leaking means you are creating a situation where an object can't be garbage collected - so even though the activity has gone away, it's still in memory and can't be cleaned up - i.e. you are wasting memory unnecessarily (called a memory leak).

Basically what it means, in this case, is don't create references to activities that will prevent the activities from being garbage collected when they are done.  Avoid assigning the context or activity to a variable in another activity, class, service, etc..  or if you must have the context, consider using a weak reference.

i.e. don't store a strong reference to an activity in a static class, don't use a strong reference to an activity in a long running process, etc.


问:
Keep Office add-in task pane open at document load
I have a task pane (desktop) Office add-in built with the latest VS 2015 template for Excel and Word add-ins. When I open the file, the add-in task pane is not visible. My users need to click a button on the toolbar to open it, which they complain about.

In addition, I save the document with the task pane expanded but it does not affect that behavior. I remember a previous version of the add-in manifest (when it was called app for Office) kept the pane open but I upgraded it so I can use custom tabs in the Office ribbon.

Can I make the task pane stay expanded when the document or worksheet load?

答: There is now a way to do this: Automatically open a task pane with a document. And a sample at: Office OOXML EmbedAddin</p>


问:
npm ERR! Please try running this command again as root/Administrator
Trying to get ionic up and running but getting lots of errors. Any Tips?</p>

```<code>Nates-MacBook-Pro:~ TheRainmaker$ npm install -g cordova ionic
npm ERR! Error: EACCES, mkdir '/usr/local/lib/node_modules/cordova'
npm ERR!  { [Error: EACCES, mkdir '/usr/local/lib/node_modules/cordova']
npm ERR!   errno: 3,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/usr/local/lib/node_modules/cordova',
npm ERR!   fstream_type: 'Directory',
npm ERR!   fstream_path: '/usr/local/lib/node_modules/cordova',
npm ERR!   fstream_class: 'DirWriter',
npm ERR!   fstream_stack:
npm ERR!    [ '/usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23',
npm ERR!      '/usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53',
npm ERR!      'Object.oncomplete (fs.js:107:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Darwin 14.0.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "cordova" "ionic"
npm ERR! cwd /Users/TheRainmaker
npm ERR! node -v v0.10.32
npm ERR! npm -v 1.4.28
npm ERR! path /usr/local/lib/node_modules/cordova
npm ERR! fstream_path /usr/local/lib/node_modules/cordova
npm ERR! fstream_type Directory
npm ERR! fstream_class DirWriter
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, mkdir '/usr/local/lib/node_modules/cordova'
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53
npm ERR! fstream_stack Object.oncomplete (fs.js:107:15)
npm ERR! Error: EACCES, mkdir '/usr/local/lib/node_modules/ionic'
npm ERR!  { [Error: EACCES, mkdir '/usr/local/lib/node_modules/ionic']
npm ERR!   errno: 3,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/usr/local/lib/node_modules/ionic',
npm ERR!   fstream_type: 'Directory',
npm ERR!   fstream_path: '/usr/local/lib/node_modules/ionic',
npm ERR!   fstream_class: 'DirWriter',
npm ERR!   fstream_stack:
npm ERR!    [ '/usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23',
npm ERR!      '/usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53',
npm ERR!      'Object.oncomplete (fs.js:107:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Darwin 14.0.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "cordova" "ionic"
npm ERR! cwd /Users/TheRainmaker
npm ERR! node -v v0.10.32
npm ERR! npm -v 1.4.28
npm ERR! path /usr/local/lib/node_modules/ionic
npm ERR! fstream_path /usr/local/lib/node_modules/ionic
npm ERR! fstream_type Directory
npm ERR! fstream_class DirWriter
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, mkdir '/usr/local/lib/node_modules/ionic'
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53
npm ERR! fstream_stack Object.oncomplete (fs.js:107:15)
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/TheRainmaker/npm-debug.log
npm ERR! not ok code 0
Nates-MacBook-Pro:~ TheRainmaker$
</code>```

答:
Running scripts from the internet with root/administrator access is a bad idea. You should change your default installation path of npm modules to a different folder.

On linux you should use

```<code>echo prefix=${HOME}/.localnpm >> ~/.npmrc
</code>```

This will make npm install everything to ~/.localnpm/bin and ~/.localnpm/lib

Body:
Trying to get ionic up and running but getting lots of errors. Any Tips?

Nates-MacBook-Pro:~ TheRainmaker$ npm install -g cordova ionic
npm ERR! Error: EACCES, mkdir '/usr/local/lib/node_modules/cordova'
npm ERR!  { [Error: EACCES, mkdir '/usr/local/lib/node_modules/cordova']
npm ERR!   errno: 3,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/usr/local/lib/node_modules/cordova',
npm ERR!   fstream_type: 'Directory',
npm ERR!   fstream_path: '/usr/local/lib/node_modules/cordova',
npm ERR!   fstream_class: 'DirWriter',
npm ERR!   fstream_stack:
npm ERR!    [ '/usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23',
npm ERR!      '/usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53',
npm ERR!      'Object.oncomplete (fs.js:107:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Darwin 14.0.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "cordova" "ionic"
npm ERR! cwd /Users/TheRainmaker
npm ERR! node -v v0.10.32
npm ERR! npm -v 1.4.28
npm ERR! path /usr/local/lib/node_modules/cordova
npm ERR! fstream_path /usr/local/lib/node_modules/cordova
npm ERR! fstream_type Directory
npm ERR! fstream_class DirWriter
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, mkdir '/usr/local/lib/node_modules/cordova'
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53
npm ERR! fstream_stack Object.oncomplete (fs.js:107:15)
npm ERR! Error: EACCES, mkdir '/usr/local/lib/node_modules/ionic'
npm ERR!  { [Error: EACCES, mkdir '/usr/local/lib/node_modules/ionic']
npm ERR!   errno: 3,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/usr/local/lib/node_modules/ionic',
npm ERR!   fstream_type: 'Directory',
npm ERR!   fstream_path: '/usr/local/lib/node_modules/ionic',
npm ERR!   fstream_class: 'DirWriter',
npm ERR!   fstream_stack:
npm ERR!    [ '/usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23',
npm ERR!      '/usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53',
npm ERR!      'Object.oncomplete (fs.js:107:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Darwin 14.0.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "cordova" "ionic"
npm ERR! cwd /Users/TheRainmaker
npm ERR! node -v v0.10.32
npm ERR! npm -v 1.4.28
npm ERR! path /usr/local/lib/node_modules/ionic
npm ERR! fstream_path /usr/local/lib/node_modules/ionic
npm ERR! fstream_type Directory
npm ERR! fstream_class DirWriter
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, mkdir '/usr/local/lib/node_modules/ionic'
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53
npm ERR! fstream_stack Object.oncomplete (fs.js:107:15)
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/TheRainmaker/npm-debug.log
npm ERR! not ok code 0
Nates-MacBook-Pro:~ TheRainmaker$

Body:
Running scripts from the internet with root/administrator access is a bad idea. You should change your default installation path of npm modules to a different folder.

On linux you should use

echo prefix=${HOME}/.localnpm >> ~/.npmrc

This will make npm install everything to ~/.localnpm/bin and ~/.localnpm/lib


问:
Escape special characters in mount command
I am trying to mount a windows shared folder on Mac OSX Mavericks. A simplistic user name and password worked fine

mount -t smbfs //user2:password2@server1.mydomain.com/myproject ~/localmap

On trying out the more valid user name and password I am getting errors that parsing URL failed.
The details are
Username: mydomain\user1
Password: A%b$c@d!e#f

The command tried is

mount -t smbfs //mydomain\user1:A%b\$c\@d\!e#f@server1.mydomain.com/myproject ~/localmap

Based on what I found, $ and ! needs to be escaped. Need help on how to escape the special characters. Incidentally, using only the username without the domain seems to work in the first case

答:
Might be handy to use nodejs to encode the url stuff:

```<code>$ node -e 'console.log(encodeURIComponent("A%b$c@d!e#f"))'
A%25b%24c%40d!e%23f
</code>```

Decode to go the other way:

```<code>$ node -e 'console.log(decodeURIComponent("A%25b%24c%40d!e%23f"))'
A%b$c@d!e#f
</code>```

Body:
Might be handy to use nodejs to encode the url stuff:

$ node -e 'console.log(encodeURIComponent("A%b$c@d!e#f"))'
A%25b%24c%40d!e%23f

Decode to go the other way:

$ node -e 'console.log(decodeURIComponent("A%25b%24c%40d!e%23f"))'
A%b$c@d!e#f


问:
How to find memory leak in a C++ code/project?
I am a C++ programmer on the Windows platform. I am using Visual Studio 2008.

I usually end up in the code with memory leaks.

Normally I find the memory leak by inspecting the code, but it is cumbersome and is not always a good approach.

Since I can't afford a paid memory leak detection tool, I wanted you guys to suggest the best possible ways to avoid memory leaks.

I want to the know how the programmer can find memory leaks.

Is there any standard or procedure one should follow to ensure there is no memory leak in the program?

答:
In addition to the tools and methodes provided in the other anwers, static code analysis tools can be used to detect memory leaks (and other issues as well).
A free an robust tool is Cppcheck. But there are a lot of other tools available. Wikipedia has a list of static code analysis tools.</p>


问:
Faster alternative to push_back(size is known)
I have a float vector. As I process certain data, I push it back.I always know what the size will be while declaring the vector.

For the largest case, it is 172,490,752 floats. This takes about eleven seconds just to push_back everything.

Is there a faster alternative, like a different data structure or something?

答:
If you know the final size, then reserve() that size after you declare the vector. That way it only has to allocate memory once.

Also, you may experiment with using emplace_back() although I doubt it will make any difference for a vector of float. But try it and benchmark it (with an optimized build of course - you are using an optimized build - right?).

Another option when you know the size in advance is to use std::array.

ContentLicense: CC BY-SA 4.0


问:
All build submissions in a build must use project instances originating from the same project collection
I am trying to publish a .NET project in VS-2017. When I publish I get the error:

All build submissions in a build must use project instances originating from the same project collection.

The project builds fine in both release and debug mode. The same thing happens when trying to publish as debug. Any ideas how I can get more information on what is wrong?

答: For me helped to delete the .xproj file from the project folder and set the platform target of the project to publish to x86</p>


问:
Cant run additional python script after calling run on flask app?
I was trying to do the following:

```<code>import webbrowser
app = Flask(__name__)
...

host = "0.0.0.0"
port = 9991
print "running app."
app.run(host=host, port=port)
print "about to open browser"
webbrowser.open("http://localhost:%s" % port)
</code>```

and when I do this, it will not carry out the print statement after the run so i never see the print statement, nor does the browser open.

What do i do to handle this?  Subprocess?

答:
Why not do something like:

```<code>print "Opening browser..."
webbrowser.open("http://localhost:%s" % port)
print "Running app..."
app.run(host=host, port=port)
</code>```

Flask servers usually start up quickly,
 so there should be no problem. However, if there is a "server not found" sort of problem reported by the browser, try the following:

```<code>import subprocess, time
print "Opening browser in 3 seconds..."

subprocess.Popen(['python', '-c', 'import time, webbrowser; time.sleep(3); webbrowser.open("http://localhost:%s")' % port])
print "Running app..."
app.run(host=host, port=port)
</code>```

Body:
I was trying to do the following:

import webbrowser
app = Flask(__name__)
...

host = "0.0.0.0"
port = 9991
print "running app."
app.run(host=host, port=port)
print "about to open browser"
webbrowser.open("http://localhost:%s" % port)

and when I do this, it will not carry out the print statement after the run so i never see the print statement, nor does the browser open.

What do i do to handle this?  Subprocess?

Body:
Why not do something like:

print "Opening browser..."
webbrowser.open("http://localhost:%s" % port)
print "Running app..."
app.run(host=host, port=port)

Flask servers usually start up quickly,
 so there should be no problem. However, if there is a "server not found" sort of problem reported by the browser, try the following:

import subprocess, time
print "Opening browser in 3 seconds..."

subprocess.Popen(['python', '-c', 'import time, webbrowser; time.sleep(3); webbrowser.open("http://localhost:%s")' % port])
print "Running app..."
app.run(host=host, port=port)


答: ::boost::container::stable_vector Notice that allocating a contiguous block of 172 *4 MB might easily fail and requires quite a lot page joggling. Stable vector is essentially a list of smaller vectors or arrays of reasonable size. You may also want to populate it in parallel.

Title: Faster alternative to push_back(size is known)

Body:
I have a float vector. As I process certain data, I push it back.I always know what the size will be while declaring the vector.

For the largest case, it is 172,490,752 floats. This takes about eleven seconds just to push_back everything.

Is there a faster alternative, like a different data structure or something?


问:
Get a whole column in a struct field in MATLAB
I have a struct in MATLAB with the size 46x6, the fields are:

```<code>name, folder, date, bytes, isdir, datenum
</code>```

Now I want all 46 entries of name. However, the MATLAB function getfield(structname, 'name') only returns the first entry.

How can I get all elements of the struct?

Name holds strings

答:
First I had to convert the Struct to a cell, and then access it with round brackets</p>

```<code>tmp = struct2cell(mystruct)
tmp(1,:)
</code>```

Body:
I have a struct in MATLAB with the size 46x6, the fields are:

name, folder, date, bytes, isdir, datenum

Now I want all 46 entries of name. However, the MATLAB function getfield(structname, 'name') only returns the first entry.

How can I get all elements of the struct?

Name holds strings

Body:
First I had to convert the Struct to a cell, and then access it with round brackets

tmp = struct2cell(mystruct)
tmp(1,:)


问:
Fluentd capture when a Kubernetes Pod terminates with the 'CrashLoopBackOff'?
I'm running a pod that write a simple message to the 'terminationMessagePath' then the pod exit with "CrashLoopBackOff".  I would like to be able to debug through Kibana instead of having to login to each Kubernetes nodes.  I queried Kibana to get the container last state value "CrashLoopBackOff" from the property reason & message and could not locate an entry.

I can see the fields for the pod in Kibana but the field that I'm looking for (in bold yaml format below) is empty.

What configuration is needed in fluentd to get the log from Kubernetes pod? or configuration need to be set from Kubernetes

$ kubectl get pod_name_1 -o=yaml

```<code>terminationMessagePath: /var/log/containers/dt.log
volumeMounts:
- mountPath: /var/log/containers
  name: data
- mountPath: /var/run/secrets/kubernetes.io/serviceaccount
  name: default-token-s0w2n
  readOnly: true
dnsPolicy: ClusterFirst
nodeName: dev-master-01
restartPolicy: Always
securityContext: {}
serviceAccount: default
serviceAccountName: default
terminationGracePeriodSeconds: 30
volumes:
- hostPath:
  path: /var/log/containers
  name: data
- name: default-token-s0w2n
secret:
  defaultMode: 420
  secretName: default-token-s0w2n
status:
conditions:
 - lastProbeTime: null
   lastTransitionTime: 2017-07-05T14:45:11Z
   status: "True"
   type: Initialized
 - lastProbeTime: null
   lastTransitionTime: 2017-07-05T17:00:22Z
   message: 'containers with unready status: [dt-termination-demo]'
   reason: ContainersNotReady
   status: "False"
   type: Ready
 - lastProbeTime: null
   lastTransitionTime: 2017-07-05T14:45:11Z
   status: "True"
   type: PodScheduled
   containerStatuses:
 - containerID:
   docker://9649c26527cf0e1cd3bd67ba9c606c0b78e6b4f08bacf96175627ddc7d250772
   image: debian
   imageID: docker pullable://docker.io/debian@sha256:
            7d067f77d2ae5a23fe6920f8fbc2936c4b0d417e9d01b26372561860750815f0
   lastState:
   terminated:
   containerID: docker://
   9649c26527cf0e1cd3bd67ba9c606c0b78e6b4f08bacf96175627ddc7d250772
   exitCode: 0
   finishedAt: 2017-07-05T17:00:22Z
   **message: |
    Sleep expired**
    reason: Completed
   startedAt: 2017-07-05T17:00:12Z
   name: dt-termination-demo
   ready: false
   restartCount: 30
   state:
     waiting:
     message: Back-off 5m0s restarting failed container=dt-termination-demo
              pod=dt-termination-demo-2814930607-8kshj_
              default(8c247b15-6190-11e7-acb7-00505691210d)
     **reason: CrashLoopBackOff**
   hostIP: 192.21.19.128
   phase: Running
   podIP: 10.0.0.8
   startTime: 2017-07-05T14:45:11Z
</code>```

答:
When Fluentd is deployed as a DaemonSet, it aims to collect all logs from the Node and Pods. As a guide to accomplish this please check the following Yaml file and further repository associated:

https://github.com/fluent/fluentd-kubernetes-daemonset/blob/master/fluentd-daemonset-elasticsearch.yaml

https://github.com/fluent/fluentd-kubernetes-daemonset

If you need additional assistance you can also join our Slack channel:

http://slack.fluentd.org

Body:
I'm running a pod that write a simple message to the 'terminationMessagePath' then the pod exit with "CrashLoopBackOff".  I would like to be able to debug through Kibana instead of having to login to each Kubernetes nodes.  I queried Kibana to get the container last state value "CrashLoopBackOff" from the property reason & message and could not locate an entry.

I can see the fields for the pod in Kibana but the field that I'm looking for (in bold yaml format below) is empty.

What configuration is needed in fluentd to get the log from Kubernetes pod? or configuration need to be set from Kubernetes

$ kubectl get pod_name_1 -o=yaml

terminationMessagePath: /var/log/containers/dt.log
volumeMounts:
- mountPath: /var/log/containers
  name: data
- mountPath: /var/run/secrets/kubernetes.io/serviceaccount
  name: default-token-s0w2n
  readOnly: true
dnsPolicy: ClusterFirst
nodeName: dev-master-01
restartPolicy: Always
securityContext: {}
serviceAccount: default
serviceAccountName: default
terminationGracePeriodSeconds: 30
volumes:
- hostPath:
  path: /var/log/containers
  name: data
- name: default-token-s0w2n
secret:
  defaultMode: 420
  secretName: default-token-s0w2n
status:
conditions:
 - lastProbeTime: null
   lastTransitionTime: 2017-07-05T14:45:11Z
   status: "True"
   type: Initialized
 - lastProbeTime: null
   lastTransitionTime: 2017-07-05T17:00:22Z
   message: 'containers with unready status: [dt-termination-demo]'
   reason: ContainersNotReady
   status: "False"
   type: Ready
 - lastProbeTime: null
   lastTransitionTime: 2017-07-05T14:45:11Z
   status: "True"
   type: PodScheduled
   containerStatuses:
 - containerID:
   docker://9649c26527cf0e1cd3bd67ba9c606c0b78e6b4f08bacf96175627ddc7d250772
   image: debian
   imageID: docker pullable://docker.io/debian@sha256:
            7d067f77d2ae5a23fe6920f8fbc2936c4b0d417e9d01b26372561860750815f0
   lastState:
   terminated:
   containerID: docker://
   9649c26527cf0e1cd3bd67ba9c606c0b78e6b4f08bacf96175627ddc7d250772
   exitCode: 0
   finishedAt: 2017-07-05T17:00:22Z
   **message: |
    Sleep expired**
    reason: Completed
   startedAt: 2017-07-05T17:00:12Z
   name: dt-termination-demo
   ready: false
   restartCount: 30
   state:
     waiting:
     message: Back-off 5m0s restarting failed container=dt-termination-demo
              pod=dt-termination-demo-2814930607-8kshj_
              default(8c247b15-6190-11e7-acb7-00505691210d)
     **reason: CrashLoopBackOff**
   hostIP: 192.21.19.128
   phase: Running
   podIP: 10.0.0.8
   startTime: 2017-07-05T14:45:11Z


问:
ticket machine in netbeans
I need some help in making this ticket machine code work. I can do it using if, else if and else, and I have seen it done with a while loop. However whenever I am trying to run it as an object I either get and error because of the print ticket at the bottom of the code, or build successful and no ticket. Here is my code</p>

```<code>package ticketmachine;

import javax.swing.JOptionPane;

public class TicketMachine {
    private int price;
    private int change;
    private int balance;

public int getPrice(){
    return price;
}

public int getBalance(){
    return balance;
}

public TicketMachine (int ticketCost) {
    price = ticketCost;
    change = 0;
    balance = 0;
}

public void insertMoney (int amount){
    balance = balance + amount;
}

public static void main(String[] args){

    String input1= JOptionPane.showInputDialog(null, " Insert a coin ");
    int ticketCost=Integer.parseInt(input1);

public void printTicket(){

    //Simulate the printing of a ticket
    System.out.println("##################");
    System.out.println("# Ticket");
    System.out.println("# " + price + " pence.");
    System.out.println("##################");
    System.out.println();
}
}
}
</code>```

答:
The closing braces are wrong on your last two methods. Try:</p>

```<code>    public static void main(String[] args){

        String input1= JOptionPane.showInputDialog(null, " Insert a coin ");
        int ticketCost=Integer.parseInt(input1);

    } //Here
    public void printTicket(){

        //Simulate the printing of a ticket
        System.out.println("##################");
        System.out.println("# Ticket");
        System.out.println("# " + price + " pence.");
        System.out.println("##################");
        System.out.println();
    }

  } //Closing of the class.
</code>```

Title: ticket machine in netbeans

Body:
I need some help in making this ticket machine code work. I can do it using if, else if and else, and I have seen it done with a while loop. However whenever I am trying to run it as an object I either get and error because of the print ticket at the bottom of the code, or build successful and no ticket. Here is my code

package ticketmachine;

import javax.swing.JOptionPane;

public class TicketMachine {
    private int price;
    private int change;
    private int balance;

public int getPrice(){
    return price;
}

public int getBalance(){
    return balance;
}

public TicketMachine (int ticketCost) {
    price = ticketCost;
    change = 0;
    balance = 0;
}

public void insertMoney (int amount){
    balance = balance + amount;
}

public static void main(String[] args){

    String input1= JOptionPane.showInputDialog(null, " Insert a coin ");
    int ticketCost=Integer.parseInt(input1);

public void printTicket(){

    //Simulate the printing of a ticket
    System.out.println("##################");
    System.out.println("# Ticket");
    System.out.println("# " + price + " pence.");
    System.out.println("##################");
    System.out.println();
}
}
}

Body:
The closing braces are wrong on your last two methods. Try:

    public static void main(String[] args){

        String input1= JOptionPane.showInputDialog(null, " Insert a coin ");
        int ticketCost=Integer.parseInt(input1);

    } //Here
    public void printTicket(){

        //Simulate the printing of a ticket
        System.out.println("##################");
        System.out.println("# Ticket");
        System.out.println("# " + price + " pence.");
        System.out.println("##################");
        System.out.println();
    }

  } //Closing of the class.


问:
How to squash all git commits into one?
How do you squash your entire repository down to the first commit?

I can rebase to the first commit, but that would leave me with 2 commits.
Is there a way to reference the commit before the first one?

答:
To squash using grafts

Add a file .git/info/grafts, put there the commit hash you want to become your root

git log will now start from that commit

To make it 'real' run git filter-branch

Title: How to squash all git commits into one?


问:
Saving arrays as columns with np.savetxt
I am trying to do something that is probable very simple. I  would like to save three arrays to a file as columns using 'np.savetxt' When I try this

```<code>x = [1,2,3,4]
y = [5,6,7,8]
z = [9,10,11,12]

np.savetxt('myfile.txt', (x,y,z), fmt='%.18g', delimiter=' ', newline=os.linesep)
</code>```

The arrays are saved like this

```<code>1 2 3 4
5 6 7 8
9 10 11 12
</code>```

But what I wold like is this

```<code>1 5 9
2 6 10
3 7 11
4 8 12
</code>```

答:
I find numpy.column_stack() most intuitive:

```<code>np.savetxt('myfile.txt', np.column_stack([x,y,z]))
</code>```

Body:
I am trying to do something that is probable very simple. I  would like to save three arrays to a file as columns using 'np.savetxt' When I try this

x = [1,2,3,4]
y = [5,6,7,8]
z = [9,10,11,12]

np.savetxt('myfile.txt', (x,y,z), fmt='%.18g', delimiter=' ', newline=os.linesep)

The arrays are saved like this

1 2 3 4
5 6 7 8
9 10 11 12

But what I wold like is this

1 5 9
2 6 10
3 7 11
4 8 12

Body:
I find numpy.column_stack() most intuitive:

np.savetxt('myfile.txt', np.column_stack([x,y,z]))


问:
Must I re-populate Zend_Form fields after the post back manually?
After a post back, suppose validation fails and I want to show the form again with errors, I find that the form is empty, must I repopulate the form fields manually?</p>

答:
In case you are using some custom isValid don't forget your form also has a populate() function.

So

```<code>$data = $this->getRequest()->getPost();
if(!$myForm->isValid($data)){
    $myForm->populate($data);
}
</code>```

No need to do it by hand thats for sure.

Of course dont forget to assign the same object you did the isValid - populate calls on

```<code>$this->view->form = $myForm;
</code>```

After the checks.

ContentLicense: CC BY-SA 2.5

Body:
In case you are using some custom isValid don't forget your form also has a populate() function.

So

$data = $this->getRequest()->getPost();
if(!$myForm->isValid($data)){
    $myForm->populate($data);
}

No need to do it by hand thats for sure.

Of course dont forget to assign the same object you did the isValid - populate calls on

$this->view->form = $myForm;

After the checks.


问:
About DB Relations And Indexes
I have three tables and they have a total of 2 million rows.

I'm creating a SQL query with inner join with two , sometimes three tables together. Sometimes I'm just creating a SQL query for one table.

I want to create index for it, but I'm not sure how can I create. How should I do it ? Three columns (all ID columns in tables) together or seperated. And which index will works fine ?

The last question is about DB relations. This three tables doesn't have a PF-FK relationship. Can it effect for my query time ?

If you can help me, thanks for it :)

答:
With so little data about your model I can suggest this:

Create an index for each column on each table that is used in a join

If you want more suggestions you need to give more information.

Title: About DB Relations And Indexes


问:
Exception while deserializing XML wtih DataContractSerializer in .NET Core
I have the following snippet written in .net core:

```<code>using System;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace BugTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var xml = @"<PingDataConfirmation  xmlns=""http://mycompany.com/MyProduct/Operations"">
        <SourceGuid>88c02aba-f78c-4749-8665-0caddee08b8a</SourceGuid>
        <Guid>88c02aba-f78c-4749-8665-0caddee08b8a</Guid>
        <CreationTime>0001-01-01T00:00:00</CreationTime>
      </PingDataConfirmation>";

            const int buffSize = 1000000;

            int bytes = 0;
            int chars = 0;
            byte[] result = new byte[buffSize];
            bool compl;
            Encoding.UTF8.GetEncoder().Convert(xml.ToCharArray(), 0, xml.Length, result, 0, buffSize, true, out chars, out bytes, out compl);

            var xmlReader = XmlDictionaryReader.CreateTextReader(result, 0, bytes, new XmlDictionaryReaderQuotas());
            var sr = new DataContractSerializer(typeof(PingDataConfirmation));
            var deserialized = sr.ReadObject(xmlReader);
        }
    }

    [DataContract(Namespace = "http://mycompany.com/MyProduct/Operations")]
    public class PingDataConfirmation
    {
        [DataMember(IsRequired = true)]
        public string SourceGuid { get; set; }

        [DataMember(IsRequired = true)]
        public string Guid { get; set; }

        [DataMember(IsRequired = true)]
        public DateTime CreationTime { get; set; }
    }
}
</code>```

It throws exception:

System.Runtime.Serialization.SerializationException: Error in line 1
  position 86. 'Element' 'SourceGuid' from namespace
  'http://mycompany.com/MyProduct/Operations' is not expected. Expecting
  element 'CreationTime'

So it looks like, DataContractSerialized has missed one of the properties.

So, may it be bug in .net core implementation of DataContractSerializer? Is there any possiblity to debug interior to see why it happens?

CSPROJ:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="System.ServiceModel.Primitives" Version="*" />
    <PackageReference Include="System.ServiceModel.Http" Version="*" />
  </ItemGroup>
</Project>
</code>```

.net core:

```<code>1.0.4
</code>```

答:
Your problem is that your data member order is inconsistent with the order of elements in the XML.

From Data Member Order:

If a data contract type is a part of an inheritance hierarchy, data members of its base types are always first in the order.

Next in order are the current type’s data members that do not have the Order property of the DataMemberAttribute attribute set, in
  alphabetical order.

Next are any data members that have the Order property of the DataMemberAttribute attribute set. These are ordered by the value of
  the Order property first and then alphabetically if there is more
  than one member of a certain Order value. Order values may be
  skipped.

And from Data Contract Equivalence: Data Member Order and Data Contract equivalence:

Keep in mind that the order of the data members must match and that
  base type members precede derived type members in the order.

Thus either the order of elements in the XML must be alphabetical, or DataMemberAttribute.Order values must be specified that are consistent with the actual order of elements in the XML:

```<code>[DataContract(Namespace = "http://mycompany.com/MyProduct/Operations")]
public class PingDataConfirmation
{
    [DataMember(IsRequired = true, Order = 1)]
    public string SourceGuid { get; set; }

    [DataMember(IsRequired = true, Order = 2)]
    public string Guid { get; set; }

    [DataMember(IsRequired = true, Order = 3)]
    public DateTime CreationTime { get; set; }
}
</code>```

Body:
I have the following snippet written in .net core:

using System;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace BugTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var xml = @"<PingDataConfirmation  xmlns=""http://mycompany.com/MyProduct/Operations"">
        <SourceGuid>88c02aba-f78c-4749-8665-0caddee08b8a</SourceGuid>
        <Guid>88c02aba-f78c-4749-8665-0caddee08b8a</Guid>
        <CreationTime>0001-01-01T00:00:00</CreationTime>
      </PingDataConfirmation>";

            const int buffSize = 1000000;

            int bytes = 0;
            int chars = 0;
            byte[] result = new byte[buffSize];
            bool compl;
            Encoding.UTF8.GetEncoder().Convert(xml.ToCharArray(), 0, xml.Length, result, 0, buffSize, true, out chars, out bytes, out compl);

            var xmlReader = XmlDictionaryReader.CreateTextReader(result, 0, bytes, new XmlDictionaryReaderQuotas());
            var sr = new DataContractSerializer(typeof(PingDataConfirmation));
            var deserialized = sr.ReadObject(xmlReader);
        }
    }

    [DataContract(Namespace = "http://mycompany.com/MyProduct/Operations")]
    public class PingDataConfirmation
    {
        [DataMember(IsRequired = true)]
        public string SourceGuid { get; set; }

        [DataMember(IsRequired = true)]
        public string Guid { get; set; }

        [DataMember(IsRequired = true)]
        public DateTime CreationTime { get; set; }
    }
}

It throws exception:

System.Runtime.Serialization.SerializationException: Error in line 1
  position 86. 'Element' 'SourceGuid' from namespace
  'http://mycompany.com/MyProduct/Operations' is not expected. Expecting
  element 'CreationTime'

So it looks like, DataContractSerialized has missed one of the properties.

So, may it be bug in .net core implementation of DataContractSerializer? Is there any possiblity to debug interior to see why it happens?

CSPROJ:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="System.ServiceModel.Primitives" Version="*" />
    <PackageReference Include="System.ServiceModel.Http" Version="*" />
  </ItemGroup>
</Project>

.net core:

1.0.4

Body:
Your problem is that your data member order is inconsistent with the order of elements in the XML.

From Data Member Order:

If a data contract type is a part of an inheritance hierarchy, data members of its base types are always first in the order.

Next in order are the current type’s data members that do not have the Order property of the DataMemberAttribute attribute set, in
  alphabetical order.

Next are any data members that have the Order property of the DataMemberAttribute attribute set. These are ordered by the value of
  the Order property first and then alphabetically if there is more
  than one member of a certain Order value. Order values may be
  skipped.

And from Data Contract Equivalence: Data Member Order and Data Contract equivalence:

Keep in mind that the order of the data members must match and that
  base type members precede derived type members in the order.

Thus either the order of elements in the XML must be alphabetical, or DataMemberAttribute.Order values must be specified that are consistent with the actual order of elements in the XML:

[DataContract(Namespace = "http://mycompany.com/MyProduct/Operations")]
public class PingDataConfirmation
{
    [DataMember(IsRequired = true, Order = 1)]
    public string SourceGuid { get; set; }

    [DataMember(IsRequired = true, Order = 2)]
    public string Guid { get; set; }

    [DataMember(IsRequired = true, Order = 3)]
    public DateTime CreationTime { get; set; }
}


问:
How do I delete a line from the table in index page when I press the delete button without deleting it from the database
How do I delete a line from the table in index page when I press the delete button without deleting it from the database.
i'm using asp.net mvc5 with visual studio 2017 and sql server 2016.

```<code>// GET: Information/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Information information = db.Informations.Find(id);
        if (information == null)
        {
            return HttpNotFound();
        }
        return View(information);
    }

    // POST: Information/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Information information = db.Informations.Find(id);
        db.Informations.Remove(information);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}
</code>```

}

this code delete the selected row from database. i want to delete it just from index page.
Please could anyone give me any hint.

答:
thank you everyone. i solve the problem when i write this code in the controller:
return View(db.Informations.Where(f=>f.show== true).ToList());
"show" is a checkbox. if a select it in the create page so the row will appears in the index page, if not it will appears just in the database.
so i need the delete button just to remove the selected row to be invisible in the index page.
I apologize for my weak English.
thank you</p>

Body:
How do I delete a line from the table in index page when I press the delete button without deleting it from the database.
i'm using asp.net mvc5 with visual studio 2017 and sql server 2016.

// GET: Information/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Information information = db.Informations.Find(id);
        if (information == null)
        {
            return HttpNotFound();
        }
        return View(information);
    }

    // POST: Information/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Information information = db.Informations.Find(id);
        db.Informations.Remove(information);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

}

this code delete the selected row from database. i want to delete it just from index page.
Please could anyone give me any hint.


问:
Python Path Issue (Anaconda - Spyder)
I have installed Anaconda and using Spyder Python.

I have installed latest Python and for some reason I can't use pip.

Searched the web and SoF and understood that this is something connected to the system path and env properties.

Here are my findings so far:

```<code>for p in sys.path: print(p)

C:\Users\user\Anaconda3\lib\site-packages\spyder\utils\site
C:\Users\user\Anaconda3\python36.zip
C:\Users\user\Anaconda3\DLLs
C:\Users\user\Anaconda3\lib
C:\Users\user\Anaconda3
C:\Users\user\Anaconda3\lib\site-packages
C:\Users\user\Anaconda3\lib\site-packages\Sphinx-1.5.6-py3.6.egg
C:\Users\user\Anaconda3\lib\site-packages\win32
C:\Users\user\Anaconda3\lib\site-packages\win32\lib
C:\Users\user\Anaconda3\lib\site-packages\Pythonwin
C:\Users\user\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg
C:\Users\user\Anaconda3\lib\site-packages\IPython\extensions
C:\Users\user\.ipython

 os.environ['PYTHONPATH'].split(os.pathsep)
Traceback (most recent call last):

  File "<ipython-input-25-6e97a5381293>", line 1, in <module>
    os.environ['PYTHONPATH'].split(os.pathsep)

  File "C:\Users\user\Anaconda3\lib\os.py", line 669, in __getitem__
    raise KeyError(key) from None

KeyError: 'PYTHONPATH'
</code>```

Please help me - what am I missing here? What path should I add?

Thanks in advance!

答:
Anaconda has its own package manager , invoked with conda install.

Read about it here: https://conda.io/docs/using/pkgs.html

as to your case, your Environment variable PYTHONPATH needs to point to your python installation. Depending on what OS you are on, the steps will vary.

IIRC , the PYTHONPATH on ubuntu for example should be /home/user/anaconda/bin/python

EDIT: Looks like you're on windows, so you have to go through the system dialogue to setup an environment variable pointing to anaconda

EDIT 2: Make sure you're typing these on the terminal, as some of the comments here are suggesting. Anaconda should have a script in the installation directory to launch the "right terminal" so as to speak, but if you're on windows 10 then just searching conda or anaconda on the start menu should bring it up. This version of cmd has all the environments correctly loaded and setup.

Title: Python Path Issue (Anaconda - Spyder)

Body:
I have installed Anaconda and using Spyder Python.

I have installed latest Python and for some reason I can't use pip.

Searched the web and SoF and understood that this is something connected to the system path and env properties.

Here are my findings so far:

for p in sys.path: print(p)

C:\Users\user\Anaconda3\lib\site-packages\spyder\utils\site
C:\Users\user\Anaconda3\python36.zip
C:\Users\user\Anaconda3\DLLs
C:\Users\user\Anaconda3\lib
C:\Users\user\Anaconda3
C:\Users\user\Anaconda3\lib\site-packages
C:\Users\user\Anaconda3\lib\site-packages\Sphinx-1.5.6-py3.6.egg
C:\Users\user\Anaconda3\lib\site-packages\win32
C:\Users\user\Anaconda3\lib\site-packages\win32\lib
C:\Users\user\Anaconda3\lib\site-packages\Pythonwin
C:\Users\user\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg
C:\Users\user\Anaconda3\lib\site-packages\IPython\extensions
C:\Users\user\.ipython

 os.environ['PYTHONPATH'].split(os.pathsep)
Traceback (most recent call last):

  File "<ipython-input-25-6e97a5381293>", line 1, in <module>
    os.environ['PYTHONPATH'].split(os.pathsep)

  File "C:\Users\user\Anaconda3\lib\os.py", line 669, in __getitem__
    raise KeyError(key) from None

KeyError: 'PYTHONPATH'

Please help me - what am I missing here? What path should I add?

Thanks in advance!


问:
Are there any example on how to write full-screen apps for Mac OS X in Objective-C with Cocoa?
Could someone point me to any examples on how to write full-screen apps for Mac OS X in Ojective-C with Cocoa?</p>

答:
Add the following code to the NSView you want to make fullscreen:

[view enterFullScreenMode:[NSScreen mainScreen] withOptions:nil];

It's exactly the same, the only thing you need to watch for is if you have any NSWindow specific code...

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/Reference/NSView.html


问:
Can't read the first word of an Arabic text file
I'm reading an Arabic file using Scanner and storing the text file in an ArrayList

and I have a Dictionary that contains some words, Positive and Negative words with thier rates.

for Example:
سعيد    +5
-4    سيء

then I check for each word in the text file with Dictionary if the word is negative rise the negative counter and if it is positive rise the positive counter and finally make a comparison to determine if the file is positive or negative

it works perfectly for English but not for Arabic, for some reason it skips the first word on the array even if its on Dictionary with exact match
and if I pressed Enter at the beginning of the text file (new line) it works perfectly
I tried to Add a new Line to ArrayList and files as alternate to the new line but it doesn't work It has to be added by pressing Enter Button

```<code> for (String word: wordsList) { // loop through user file

  try { // compare words with dictionary

   String line;
   // read from the Dictionary file
    File fileDir = new File("C:\\Users\\Ameera\\Desktop\\Dictionary.txt");
            BufferedReader inDict = new BufferedReader(new InputStreamReader(
                    new FileInputStream(fileDir), "utf-8"));

    while ((line = inDict()) != null) {

     String strSplit[] = line.split("\t"); // Split Dictionary line after each tab to get the word only without its rate
     // example will get (سعيد, سيد) only
     /* سعيد    +5
        سيء         -4
     */

     if (strSplit[0].equals(word)) {

      int rate2 = Integer.parseInt(strSplit[1]); // get word rate

      sent += rate2; // add word rate to file totoal rate

     }

    }
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
</code>```

答:
Thanks guys I really appreciate your responses I found the answer here (Removing BOM characters using Java)
MC Emperor Thanks a lot
the problem was because of  byte order mark.</p>

Body:
I'm reading an Arabic file using Scanner and storing the text file in an ArrayList

and I have a Dictionary that contains some words, Positive and Negative words with thier rates.

for Example:
سعيد    +5
-4    سيء

then I check for each word in the text file with Dictionary if the word is negative rise the negative counter and if it is positive rise the positive counter and finally make a comparison to determine if the file is positive or negative

it works perfectly for English but not for Arabic, for some reason it skips the first word on the array even if its on Dictionary with exact match
and if I pressed Enter at the beginning of the text file (new line) it works perfectly
I tried to Add a new Line to ArrayList and files as alternate to the new line but it doesn't work It has to be added by pressing Enter Button

 for (String word: wordsList) { // loop through user file

  try { // compare words with dictionary

   String line;
   // read from the Dictionary file
    File fileDir = new File("C:\\Users\\Ameera\\Desktop\\Dictionary.txt");
            BufferedReader inDict = new BufferedReader(new InputStreamReader(
                    new FileInputStream(fileDir), "utf-8"));

    while ((line = inDict()) != null) {

     String strSplit[] = line.split("\t"); // Split Dictionary line after each tab to get the word only without its rate
     // example will get (سعيد, سيد) only
     /* سعيد    +5
        سيء         -4
     */

     if (strSplit[0].equals(word)) {

      int rate2 = Integer.parseInt(strSplit[1]); // get word rate

      sent += rate2; // add word rate to file totoal rate

     }

    }
   } catch (Exception e) {
    e.printStackTrace();
   }
  }


问:
Firebase admin SDK Python - cannot verify custom tokens
I'm trying to play with the firebase admin sdk for python for making custom tokens and verify those while testing my app. Problem is that while I try to verify the token I always get such an error:

```<code>ValueError: Firebase ID token has incorrect "aud" (audience) claim. Expected "my_project_id" but got "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit". Make sure the ID token comes from the same Firebase project as the service account used to authenticate this SDK. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.
</code>```

I followed the guide to create the app and making the tokens:

```<code>import firebase_admin
from firebase_admin import auth, credentials

cred = credentials.Certificate('/path/to/file.json')
app = firebase_admin.initialize(cred)
custom_token = auth.create_custom_token('some-uid', app=app)
auth.verify_id_token(custom_token, app=app)
</code>```

and here I get the error. It seems that _TokenGenarator is initialised with the defaults that are coming back from the error. I thought when passing the app it should automatically change those but it's not happening. Am I missing something?

答:
verify_id_token() only accepts ID tokens. Custom tokens do not fall into that category. See this test case. Raising a ValueError is the expected behavior in this case.

ID tokens can be obtained from a client SDK. You can exchange a custom token for an ID token by calling one of the provided signInWithCustomToken() methods.

Body:
I'm trying to play with the firebase admin sdk for python for making custom tokens and verify those while testing my app. Problem is that while I try to verify the token I always get such an error:

ValueError: Firebase ID token has incorrect "aud" (audience) claim. Expected "my_project_id" but got "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit". Make sure the ID token comes from the same Firebase project as the service account used to authenticate this SDK. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.

I followed the guide to create the app and making the tokens:

import firebase_admin
from firebase_admin import auth, credentials

cred = credentials.Certificate('/path/to/file.json')
app = firebase_admin.initialize(cred)
custom_token = auth.create_custom_token('some-uid', app=app)
auth.verify_id_token(custom_token, app=app)

and here I get the error. It seems that _TokenGenarator is initialised with the defaults that are coming back from the error. I thought when passing the app it should automatically change those but it's not happening. Am I missing something?


问:
AWS S3 bucket access for role/users- Select Role Type
My intention is simple- to create a role that I can assign to a standard user of my AWS account so that they can read/write to one of my S3 buckets.

I've created a policy to apply to the role and I'm happy with that bit.

The thing I'm a bit confused about is the "Select Role type" screen in the management console (see attached image). I can't work out what I'm supposed to choose at this stage as none of the descriptions seem to apply to the simple thing I'm trying to achieve.
Does anyone have any idea?

答:
I think you are on the wrong path here. Roles are not ACLs for users, but for systems and services.

See: IAM Roles

If you want to grant a user access to some AWS resources you should have a look at the policy section. Either use a pre-build (like AmazonS3ReadOnlyAccess or AmazonS3FullAccess) or define a policy on your own.

You can then assign this policy to a user. If you want to manage multiple users this way, you can also use groups to assign policies to users.


问:
CSS and JQuery not working?
So the CSS on my site doesn't seem to be working, at least the updates I made. I want to create a height transition effect with the css transition property and the JQuery.css property but my applied changes aren't working on my site.</p>

```<code>.blog{
    transition: 1500ms ease-in-out !important;
    width: 100%;
    height: 0% !important;
    background-color: #8394EB;
    margin: 0;
    padding: 10px 40px;
    color: white !important;
}

$('.blog').css('height','100%');
</code>```

答:
Problem with this line:

```<code>height: 0% !important;
</code>```

Try remove attribute "important" and it will work.
If this modifier is necessary, use code like below:

```<code>$( '.blog' ).each(function () {
    this.style.setProperty( 'height', '10vh', 'important' );
});
</code>```

Hope I help you :)

Title: CSS and JQuery not working?

Body:
So the CSS on my site doesn't seem to be working, at least the updates I made. I want to create a height transition effect with the css transition property and the JQuery.css property but my applied changes aren't working on my site.

.blog{
    transition: 1500ms ease-in-out !important;
    width: 100%;
    height: 0% !important;
    background-color: #8394EB;
    margin: 0;
    padding: 10px 40px;
    color: white !important;
}

$('.blog').css('height','100%');

Body:
Problem with this line:

height: 0% !important;

Try remove attribute "important" and it will work.
If this modifier is necessary, use code like below:

$( '.blog' ).each(function () {
    this.style.setProperty( 'height', '10vh', 'important' );
});

Hope I help you :)


问:
Modify semantic UI column
I have a question, is it possible to modify the width of a 'div class=column' in semantic? I have a two column grid container, but I would wish that one column to have 70% width and the other one 30%. Semantic makes bot columns with equal width 50%. </p>

答:
```<code><div class="ui grid">
  <div class="five wide column"></div>
  <div class="eleven wide column"></div>
</div>
</code>```

see https://semantic-ui.com/collections/grid.html for more info.

Title: Modify semantic UI column

Body:
<div class="ui grid">
  <div class="five wide column"></div>
  <div class="eleven wide column"></div>
</div>

see https://semantic-ui.com/collections/grid.html for more info.


问:
Seaborn plot per column in a pandas dataframe?
I have a little dataframe that looks somewhat like this:

```<code>csv = [{"Oranges" : 12, "Apples" : 4, "Kiwis" : "Yes"}, {"Oranges" : 1, "Apples" : 8, "Kiwis" : "No"}, {"Oranges" : 1, "Apples" : 14, "Kiwis" : "Yes"}, {"Oranges" : 11, "Apples" : 3, "Kiwis" : "No"}, ]
df = pd.DataFrame(csv)
</code>```

Only, it has many more cols. I want to plot a seaborn violin plot per column. If I create the plot per column manually, it would look somewhat like this:

```<code>sns.violinplot(y="Oranges", x="Kiwis", data=df, split=True, inner="quart")
sns.violinplot(y="Apples", x="Kiwis", data=df, split=True, inner="quart")
</code>```

However, and given about 100 cols, I'd like to loop through the dataframe col by col.

I tried building a tiny function like follows:

```<code>def violin(col):
    sns.violinplot(y=col, x="Kiwis", data=df, split=True, inner="quart")
</code>```

My idea is to use apply() to use it for each column...but it doesent work this far.. Any ideas?

答:
I think you just need to slightly reformat your dataframe then you can do the whole plot in one call:

```<code>df = pd.melt(df, "Kiwis", var_name="Fruit", value_name="Value")
</code>```

Makes things look like

```<code>  Kiwis    Fruit  Value
0   Yes   Apples      4
1    No   Apples      8
2   Yes   Apples     14
3    No   Apples      3
4   Yes  Oranges     12
5    No  Oranges      1
6   Yes  Oranges      1
7    No  Oranges     11
</code>```

Which is simple to plot with

```<code>sns.violinplot(x="Fruit", y="Value", hue="Kiwis", data=df,
           split=True, inner="quart")
</code>```

Body:
I have a little dataframe that looks somewhat like this:

csv = [{"Oranges" : 12, "Apples" : 4, "Kiwis" : "Yes"}, {"Oranges" : 1, "Apples" : 8, "Kiwis" : "No"}, {"Oranges" : 1, "Apples" : 14, "Kiwis" : "Yes"}, {"Oranges" : 11, "Apples" : 3, "Kiwis" : "No"}, ]
df = pd.DataFrame(csv)

Only, it has many more cols. I want to plot a seaborn violin plot per column. If I create the plot per column manually, it would look somewhat like this:

sns.violinplot(y="Oranges", x="Kiwis", data=df, split=True, inner="quart")
sns.violinplot(y="Apples", x="Kiwis", data=df, split=True, inner="quart")

However, and given about 100 cols, I'd like to loop through the dataframe col by col.

I tried building a tiny function like follows:

def violin(col):
    sns.violinplot(y=col, x="Kiwis", data=df, split=True, inner="quart")

My idea is to use apply() to use it for each column...but it doesent work this far.. Any ideas?

Body:
I think you just need to slightly reformat your dataframe then you can do the whole plot in one call:

df = pd.melt(df, "Kiwis", var_name="Fruit", value_name="Value")

Makes things look like

  Kiwis    Fruit  Value
0   Yes   Apples      4
1    No   Apples      8
2   Yes   Apples     14
3    No   Apples      3
4   Yes  Oranges     12
5    No  Oranges      1
6   Yes  Oranges      1
7    No  Oranges     11

Which is simple to plot with

sns.violinplot(x="Fruit", y="Value", hue="Kiwis", data=df,
           split=True, inner="quart")


问:
Can't encrypt a string and insert it into sqlite
I'm trying to store an password into a sqlite database here's the error: </p>

```<code>Traceback (most recent call last):
  File "/media/luis/Vista/Users/Administrador/PycharmProjects/PNV/sqlitetesting.py", line 33, in <module>
    """, encriptado)
TypeError: function takes exactly 1 argument (2 given)
</code>```

<p>I'm using python 2.7, sqlite3 and hashlib. Here's the code: </p>

```<code>    print "Password nao definida"
passadefinir = raw_input("Insira a sua password:")
clear()
passadefinir2 = raw_input("Insira novamente a sua password")
if passadefinir == passadefinir2:
    maindb.execute("DELETE FROM Password WHERE ID = 'not'")
    maindb.execute("INSERT INTO Password(ID) VALUES ('set')")
    encriptacao = hashlib.sha1(passadefinir2.encode())
    encriptado = (encriptacao.hexdigest(),)
    print (encriptado)
    maindb.executescript("""
    UPDATE Password
    SET Password = ?
    WHERE ID = 'set';
    """, encriptado)
    conn.commit()
</code>```

答:
Use maindb.execute instead of maindb.executescript:

```<code>maindb.execute("""
UPDATE Password
SET Password = ?
WHERE ID = 'set';
""", encriptado)
</code>```

Body:
I'm trying to store an password into a sqlite database here's the error:

Traceback (most recent call last):
  File "/media/luis/Vista/Users/Administrador/PycharmProjects/PNV/sqlitetesting.py", line 33, in <module>
    """, encriptado)
TypeError: function takes exactly 1 argument (2 given)

I'm using python 2.7, sqlite3 and hashlib. Here's the code:

    print "Password nao definida"
passadefinir = raw_input("Insira a sua password:")
clear()
passadefinir2 = raw_input("Insira novamente a sua password")
if passadefinir == passadefinir2:
    maindb.execute("DELETE FROM Password WHERE ID = 'not'")
    maindb.execute("INSERT INTO Password(ID) VALUES ('set')")
    encriptacao = hashlib.sha1(passadefinir2.encode())
    encriptado = (encriptacao.hexdigest(),)
    print (encriptado)
    maindb.executescript("""
    UPDATE Password
    SET Password = ?
    WHERE ID = 'set';
    """, encriptado)
    conn.commit()

Body:
Use maindb.execute instead of maindb.executescript:

maindb.execute("""
UPDATE Password
SET Password = ?
WHERE ID = 'set';
""", encriptado)


问:
Maya Custom Push/Relax Script
I'm trying to make a custom script that replicates/imitates the Maya Sculpt Geometry Tool. Basically I have 2 radio buttons, Push and Relax[which imitates the push and relax from the sculpt parameters obviously], a value slider[replicates the max displacement slider]. The radio and reset button works perfectly however I'm having problems with coding the slider. Any help for this one? Thanks in advance.

Please see images for further clarification.
Click here for image

Here is my code:

```<code>import maya.cmds as cmds
import maya.mel as mel

if cmds.window("cusWin", exists = True):
    cmds.deleteUI("cusWin")

customwindow = cmds.window("cusWin",t= "Push/Relax", wh = (200, 117), s= False, mnb= False, mxb= False)
cmds.frameLayout( label='Push/Relax Modifier', borderStyle='in', cll= False)
cmds.columnLayout(adj = True, columnOffset= ("both", 3))

cmds.radioCollection()
cmds.radioButton(l = "Push", onc= "mel.eval('artUpdatePuttyOperation artPuttyCtx push ;')")
cmds.radioButton(l = "Relax", onc= "mel.eval('artUpdatePuttyOperation artPuttyCtx relax ;')")

cmds.separator(style= "none", h= 3)

DynFsgCol1 = 30
DynFsgCol2 = 50
DynFsgCol3 = 100

valSlider = cmds.floatSliderGrp(l = "Value", field = True, min = 0, max= 5, precision = 4, cw3= (DynFsgCol1, DynFsgCol2, DynFsgCol3 ))
cmds.separator(style= "none", h= 3)

cmds.rowColumnLayout(numberOfColumns=2, columnWidth=[(1,98),(2,100)], columnOffset=[(1,'left',1),(2,'right',95)])
cmds.button(l = "Apply", w= 92, c= 'slider()')
cmds.button(l = "Reset", w= 91, c= 'resetButton()')

cmds.showWindow( customwindow )

def slider():
    valueSlider = cmds.floatSliderGrp(valSlider, q= True, value= True)
    mel.eval('artPuttyCtx -e -maxdisp valueSlider `currentCtx`;')

def resetButton():
    mel.eval('resetTool artPuttyContext;')
</code>```

答:
There's two different things going on here.

First, by using the string form of the callbacks you lose control over the scope of your functions.  It's better to pass the python objects directly.  This version does what it looks like your's is intended to do using the callbacks:
    import maya.cmds as cmds
    import maya.mel as mel

```<code>if cmds.window("cusWin", exists = True):
    cmds.deleteUI("cusWin")

customwindow = cmds.window("cusWin",t= "Push/Relax", wh = (200, 117), s= False, mnb= False, mxb= False)
cmds.frameLayout( label='Push/Relax Modifier', cll= False)
cmds.columnLayout(adj = True, columnOffset= ("both", 3))

cmds.radioCollection()
push = lambda _: cmds.artPuttyCtx(cmds.currentCtx(), e = True,  mtm='push')
relax = lambda _: cmds.artPuttyCtx(cmds.currentCtx(), e = True, mtm='relax')

cmds.radioButton(l = "Push", onc= push)
cmds.radioButton(l = "Relax", onc=relax)

cmds.separator(style= "none", h= 3)

DynFsgCol1 = 30
DynFsgCol2 = 50
DynFsgCol3 = 100

valSlider = cmds.floatSliderGrp(l = "Value", field = True, min = 0, max= 5, precision = 4, cw3= (DynFsgCol1, DynFsgCol2, DynFsgCol3 ))
cmds.separator(style= "none", h= 3)
cmds.rowColumnLayout(numberOfColumns=2, columnWidth=[(1,98),(2,100)], columnOffset=[(1,'left',1),(2,'right',95)])

# put the defs here, where the names of the slider are known
def slider(*_):
    valueSlider = cmds.floatSliderGrp(valSlider, q = True, value = True)
    cmds.artPuttyCtx(cmds.currentCtx(), e = True,  maxdisp = valueSlider)

def resetButton(*_):
    cmds.resetTool(cmds.currentCtx())

cmds.button(l = "Apply", w= 92, c= slider)
cmds.button(l = "Reset", w= 91, c= resetButton)

cmds.showWindow( customwindow )
</code>```

The thing to note is that order in which things are defined allows you to reference the names of controls you've made. (As an aside, you need to handle the nonsense arguments Maya passes on the button and slider callbacks).  It's also a good idea to clean up dangling Mel scripts where you can, if you want to make this tool more complex in future it's much harder if you have to work in two languages at once. In this case artUpdatePuttyOperation looks like it's defined when the sculpt tool UI opens, so if you ran this script without the UI I don't think it would work correctly.

The second issue is that you're not explicitly setting an artPuttyCtx with setTool, so this won't work unless the user has already created the right context and activated it.

Title: Maya Custom Push/Relax Script

Body:
I'm trying to make a custom script that replicates/imitates the Maya Sculpt Geometry Tool. Basically I have 2 radio buttons, Push and Relax[which imitates the push and relax from the sculpt parameters obviously], a value slider[replicates the max displacement slider]. The radio and reset button works perfectly however I'm having problems with coding the slider. Any help for this one? Thanks in advance.

Please see images for further clarification.
Click here for image

Here is my code:

import maya.cmds as cmds
import maya.mel as mel

if cmds.window("cusWin", exists = True):
    cmds.deleteUI("cusWin")

customwindow = cmds.window("cusWin",t= "Push/Relax", wh = (200, 117), s= False, mnb= False, mxb= False)
cmds.frameLayout( label='Push/Relax Modifier', borderStyle='in', cll= False)
cmds.columnLayout(adj = True, columnOffset= ("both", 3))

cmds.radioCollection()
cmds.radioButton(l = "Push", onc= "mel.eval('artUpdatePuttyOperation artPuttyCtx push ;')")
cmds.radioButton(l = "Relax", onc= "mel.eval('artUpdatePuttyOperation artPuttyCtx relax ;')")

cmds.separator(style= "none", h= 3)

DynFsgCol1 = 30
DynFsgCol2 = 50
DynFsgCol3 = 100

valSlider = cmds.floatSliderGrp(l = "Value", field = True, min = 0, max= 5, precision = 4, cw3= (DynFsgCol1, DynFsgCol2, DynFsgCol3 ))
cmds.separator(style= "none", h= 3)

cmds.rowColumnLayout(numberOfColumns=2, columnWidth=[(1,98),(2,100)], columnOffset=[(1,'left',1),(2,'right',95)])
cmds.button(l = "Apply", w= 92, c= 'slider()')
cmds.button(l = "Reset", w= 91, c= 'resetButton()')

cmds.showWindow( customwindow )

def slider():
    valueSlider = cmds.floatSliderGrp(valSlider, q= True, value= True)
    mel.eval('artPuttyCtx -e -maxdisp valueSlider `currentCtx`;')

def resetButton():
    mel.eval('resetTool artPuttyContext;')

Body:
There's two different things going on here.

First, by using the string form of the callbacks you lose control over the scope of your functions.  It's better to pass the python objects directly.  This version does what it looks like your's is intended to do using the callbacks:
    import maya.cmds as cmds
    import maya.mel as mel

if cmds.window("cusWin", exists = True):
    cmds.deleteUI("cusWin")

customwindow = cmds.window("cusWin",t= "Push/Relax", wh = (200, 117), s= False, mnb= False, mxb= False)
cmds.frameLayout( label='Push/Relax Modifier', cll= False)
cmds.columnLayout(adj = True, columnOffset= ("both", 3))

cmds.radioCollection()
push = lambda _: cmds.artPuttyCtx(cmds.currentCtx(), e = True,  mtm='push')
relax = lambda _: cmds.artPuttyCtx(cmds.currentCtx(), e = True, mtm='relax')

cmds.radioButton(l = "Push", onc= push)
cmds.radioButton(l = "Relax", onc=relax)

cmds.separator(style= "none", h= 3)

DynFsgCol1 = 30
DynFsgCol2 = 50
DynFsgCol3 = 100

valSlider = cmds.floatSliderGrp(l = "Value", field = True, min = 0, max= 5, precision = 4, cw3= (DynFsgCol1, DynFsgCol2, DynFsgCol3 ))
cmds.separator(style= "none", h= 3)
cmds.rowColumnLayout(numberOfColumns=2, columnWidth=[(1,98),(2,100)], columnOffset=[(1,'left',1),(2,'right',95)])

# put the defs here, where the names of the slider are known
def slider(*_):
    valueSlider = cmds.floatSliderGrp(valSlider, q = True, value = True)
    cmds.artPuttyCtx(cmds.currentCtx(), e = True,  maxdisp = valueSlider)

def resetButton(*_):
    cmds.resetTool(cmds.currentCtx())

cmds.button(l = "Apply", w= 92, c= slider)
cmds.button(l = "Reset", w= 91, c= resetButton)

cmds.showWindow( customwindow )

The thing to note is that order in which things are defined allows you to reference the names of controls you've made. (As an aside, you need to handle the nonsense arguments Maya passes on the button and slider callbacks).  It's also a good idea to clean up dangling Mel scripts where you can, if you want to make this tool more complex in future it's much harder if you have to work in two languages at once. In this case artUpdatePuttyOperation looks like it's defined when the sculpt tool UI opens, so if you ran this script without the UI I don't think it would work correctly.

The second issue is that you're not explicitly setting an artPuttyCtx with setTool, so this won't work unless the user has already created the right context and activated it.


问:
Group of variables vs dictionary
So, I was looking at how to create an array in batch, and noticed that one way of going about it could allow an associative array like structure. Which made me wonder, would a bunch of variables give the same access time and perform the same as a dictionary, but without the hashing?

For example, would:

```<code>a=1
b=2
c=3
d=4
e=5
</code>```

have the same lookup time as a dictionary with the same values? However, wouldn't a group of variables get around the issue of having to use a hash function to determine the storage location of the variable? Would this be dependent on the language and how it deals with variables and objects?

Okay, so to try to be clearer, say you have the following code:

```<code>a = 1
b = 2
c = 3
d = 4
e = 5
f = 6
g = 7
h = 8

dictionary = {
    "a":1,
    "b":2,
    "c":3,
    "d":4,
    "e":5,
    "f":6,
    "g":7,
    "h":8
}

print a + b
print dictionary["a"] + dictionary["b"]
</code>```

making the dictionary object would require the use of a hashing function to determine the location for the stored variables. The would further require lookup time to access those variables. Thus, wouldn't it take marginally longer and use more storage to store the dictionary vs the 8 variables? Another related question: do storage locations for variables themselves use hashing?

答:
Lookup times on hashed dictionaries are longer than straight variable lookup.

However, they are still pretty fast and are most welcomed for dynamically structured objects.

In the case of batch scripting, this would not really matter. Both are quite slow in comparison of other languages.

Title: Group of variables vs dictionary

Body:
So, I was looking at how to create an array in batch, and noticed that one way of going about it could allow an associative array like structure. Which made me wonder, would a bunch of variables give the same access time and perform the same as a dictionary, but without the hashing?

For example, would:

a=1
b=2
c=3
d=4
e=5

have the same lookup time as a dictionary with the same values? However, wouldn't a group of variables get around the issue of having to use a hash function to determine the storage location of the variable? Would this be dependent on the language and how it deals with variables and objects?

Okay, so to try to be clearer, say you have the following code:

a = 1
b = 2
c = 3
d = 4
e = 5
f = 6
g = 7
h = 8

dictionary = {
    "a":1,
    "b":2,
    "c":3,
    "d":4,
    "e":5,
    "f":6,
    "g":7,
    "h":8
}

print a + b
print dictionary["a"] + dictionary["b"]

making the dictionary object would require the use of a hashing function to determine the location for the stored variables. The would further require lookup time to access those variables. Thus, wouldn't it take marginally longer and use more storage to store the dictionary vs the 8 variables? Another related question: do storage locations for variables themselves use hashing?


问:
How to use Local storage in Angular
I need to store data in the browser's session and retrieve the data until the session exits. How do you use local and session storage in Angular 2?</p>

答: As said above, should be: localStorageService.set('key', 'value'); and localStorageService.get('key');

Title: How to use Local storage in Angular


问:
Uncaught Error: Class not found - Laravel
I am trying to run a script within my laravel project when I am having difficulty with the model class not found error.

My model class is located at :

App\UserLoginAudit;

I am calling my class like this :

```<code><?php

namespace App\Scripts;

use App\UserLoginAudit as user_login_audit;
use Illuminate\Support\Facades\DB;

class UserSignOut {
private $currentDate;
private $report;
public function __construct() {
    $this->currentDate = date('Y-m-d H:i:s');
    $this->doQuery();
}

private function doQuery () {
    $this->report = new user_login_audit();

    //die(print_r($this->report,true));

    $this->report->select(
        DB::raw('TIMEDIFF(NOW(),user_login_audit.last_accessed) as time_difference'),
        'user.user_id',
        'user_login_audit.ip_address'
    )
    ->join(
        'tutor_times.user',
        'user.user_id',
        '=',
        'user_login_audit.user_id'
    )
    ->whereNull('user_login_audit.time_out_type')
    ->where('last_accessed','<=',$this->currentDate)
    ->get()
    ->toArray();

    die(print_r($this->report,true));

    $this->processQuery();
}

private function processQuery () {
    foreach ($this->report as $record) {
        if ($record['time_difference'] > 5) {
            $lookup = user_login_audit
                ::where('user_id','=',$record['user_id'])
                ->where('ip_address','=',$record['ip_address'])
                ->whereNull('time_out_type')
                ->first();

            if (!empty($lookup)) {
                $lookup->time_out_type = "system";
                $lookup->save();
            }
        }
    }
}
}
$obj = new UserSignOut();
</code>```

Have I missed something out ? please can someone help me with this issue

When I run the script this is the error I get:

Uncaught Error: Class 'App\UserLoginAudit' not found in /home/public/TutorTimes/app/Scripts/user_sign_out.php:17

答:
try this </p>

```<code> use \App\UserLoginAudit as user_login_audit;
</code>```

Body:
I am trying to run a script within my laravel project when I am having difficulty with the model class not found error.

My model class is located at :

App\UserLoginAudit;

I am calling my class like this :

<?php

namespace App\Scripts;

use App\UserLoginAudit as user_login_audit;
use Illuminate\Support\Facades\DB;

class UserSignOut {
private $currentDate;
private $report;
public function __construct() {
    $this->currentDate = date('Y-m-d H:i:s');
    $this->doQuery();
}

private function doQuery () {
    $this->report = new user_login_audit();

    //die(print_r($this->report,true));

    $this->report->select(
        DB::raw('TIMEDIFF(NOW(),user_login_audit.last_accessed) as time_difference'),
        'user.user_id',
        'user_login_audit.ip_address'
    )
    ->join(
        'tutor_times.user',
        'user.user_id',
        '=',
        'user_login_audit.user_id'
    )
    ->whereNull('user_login_audit.time_out_type')
    ->where('last_accessed','<=',$this->currentDate)
    ->get()
    ->toArray();

    die(print_r($this->report,true));

    $this->processQuery();
}

private function processQuery () {
    foreach ($this->report as $record) {
        if ($record['time_difference'] > 5) {
            $lookup = user_login_audit
                ::where('user_id','=',$record['user_id'])
                ->where('ip_address','=',$record['ip_address'])
                ->whereNull('time_out_type')
                ->first();

            if (!empty($lookup)) {
                $lookup->time_out_type = "system";
                $lookup->save();
            }
        }
    }
}
}
$obj = new UserSignOut();

Have I missed something out ? please can someone help me with this issue

When I run the script this is the error I get:

Uncaught Error: Class 'App\UserLoginAudit' not found in /home/public/TutorTimes/app/Scripts/user_sign_out.php:17

Body:
try this

 use \App\UserLoginAudit as user_login_audit;