问:
Force derived class to override at least one virtual function
Imagine this simple base class:

```<code>struct simple_http_service
{
  virtual reply http_get(…);
  virtual reply http_post(…);
  virtual reply http_delete(…);
  // etc.
};
</code>```

I'd like to prevent the user from deriving from this class without overriding at least one of these and prevent them from instantiang simple_http_service

Is there some nice way to do this?

答:
I don't not quite understand why do you want to provide default implementation for other two functions but require at least one of them to be user-defined in the case of http requests.
It's clear if all functions are using each other to implement some functionality using existing code.
Imagine the example with that class:

class Cls
{
  public:
    virtual std::string toString()=0;
    virtual std::string serialize()=0;
};
```

<p>There is a class that is string-convertible and string-serializable. But if one of these is not implemented, you want to call the second instead, so that would be an option:</p>

<pre class="lang-cpp prettyprint-override"><code>class Cls
{
  public:
    virtual std::string toString() //calls serialize() by default
    {
      return this->serialize();
    }
    virtual std::string serialize() //calls toString()
    {
      return this->toString();
    }
    virtual ~Cls()=0; //force the class to be abstract
};  Cls::~Cls(){}
</code>```

But now there is the problem with deriving from Cls but not overriding at least one of the functions. If no overriding is made, at runtime you just enter infinite recursion. If this is one of your problems, there is a run-time solution, the code below is just not doing anything if such a problem occurs.

class Cls
{
  public:
    virtual std::string toString()
    {
      if ((void*)(this->*(&Cls::serialize)) != (void*)(&Cls::serialize))
      {//checks if the current implemetation is not equal to the default one
        return this->serialize();
      }
      else
      {
        return ""; //default return value
      }
    }

    virtual std::string serialize()
    {
      if ((void*)(this->*(&Cls::toString))!=(void*)((&Cls::toString)))
      {
        return this->toString();
      }
      else
      {
        return "";
      }
    }
    virtual ~Cls()=0;
};  Cls::~Cls(){}
```

<p>This compiles on GCC, but fills your screen with warnings about strange convertion from funcptr to void*. At least it works as intended. There may be some metaprogramming compile-time solutions, need to think about it.</p>

<p><strong>Appendix1</strong>, testing comparison between member funcs:</p>

<p>It is really weird</p>

<pre class="lang-cpp prettyprint-override"><code>#include <iostream>

class Base
{
    public:
        virtual int test()
        {
            //default imp
            return 0;
        }
};

class Der : public Base
{
    public:
        int test() override
        {
            //custom imp
            return 1;
        }
};

int main()
{
    Der a;
    Base b;
    std::cout << ((&Der::test) == (&Base::test)) << std::endl;//1: wrong
    //they are not equal
    //but for some reason the output is "true"
    //so direct comparisons do not work
    //however
    //if you convert that pointer to void*
    //everything works
    std::cout << ((void*)(&Der::test) == (void*)(&Base::test) ) << std::endl;      //0:right
    std::cout << ((void*)(a.*(&Base::test)) == (void*)(&Base::test) ) << std::endl;//0:right
    std::cout << ((void*)(b.*(&Base::test)) == (void*)(&Base::test) ) << std::endl;//1:right
    std::cout << ((void*)(&(a.test)) == (void*)(&(b.test)) ) << std::endl;         //0:right
    //so if you want to compare two functions
    //cast them to void*
    //works in any cases
    //'-Wno-pmf-conversions' compiler flag to inhibit warnings about casting
    system("pause");
    return 0;
}
</code>```

Appendix2, steps of getting real address of the function:

Cls::serialize; //the function object itself
&Cls::serialize; //its member pointer
(void*)(&Cls::serialize); //extracting real address of the function for the comparison
(this->*&Cls::serialize); //again, a member pointer
(void*)(this->*&Cls::serialize); //extracting real address
//  │        │  └── Getting "pointer" to a member function of the class
//  │        └───── Then binding 'this' to that function, recall that if the function is virtual, '->*' returns a mamber pointer to it's custom implementation, not the default one.
//  └────────────── Then getting the real address

// it looks like 'this->*&Cls::serialize' does the same as '&this->serialize'
// but in practice it's not quite right
// '&this->serialize' returns the function pointer based on 'this' type
// therefore, comparison breaks, as inside of a base class 'this' always has the base type
// so you always receive the default implementation pointer
// 'this->*&Cls::serialize' does the same
// but now if 'serialize' is virtual
// it takes it into account and sends back its' custom implementation pointer

// (void*) casting is required because you need to compare functions' real addresses
// if you compare member pointers of a single virtual function
// they seem to be equal while they are, in fact, not
```

The issue of checking if the derived class has implemented some of the base class virtual functions is here

Body:
Imagine this simple base class:

struct simple_http_service
{
  virtual reply http_get(…);
  virtual reply http_post(…);
  virtual reply http_delete(…);
  // etc.
};

I'd like to prevent the user from deriving from this class without overriding at least one of these and prevent them from instantiang simple_http_service

Is there some nice way to do this?

Body:
I don't not quite understand why do you want to provide default implementation for other two functions but require at least one of them to be user-defined in the case of http requests.
It's clear if all functions are using each other to implement some functionality using existing code.
Imagine the example with that class:

class Cls
{
  public:
    virtual std::string toString()=0;
    virtual std::string serialize()=0;
};

There is a class that is string-convertible and string-serializable. But if one of these is not implemented, you want to call the second instead, so that would be an option:

class Cls
{
  public:
    virtual std::string toString() //calls serialize() by default
    {
      return this->serialize();
    }
    virtual std::string serialize() //calls toString()
    {
      return this->toString();
    }
    virtual ~Cls()=0; //force the class to be abstract
};  Cls::~Cls(){}

But now there is the problem with deriving from Cls but not overriding at least one of the functions. If no overriding is made, at runtime you just enter infinite recursion. If this is one of your problems, there is a run-time solution, the code below is just not doing anything if such a problem occurs.

class Cls
{
  public:
    virtual std::string toString()
    {
      if ((void*)(this->*(&Cls::serialize)) != (void*)(&Cls::serialize))
      {//checks if the current implemetation is not equal to the default one
        return this->serialize();
      }
      else
      {
        return ""; //default return value
      }
    }

    virtual std::string serialize()
    {
      if ((void*)(this->*(&Cls::toString))!=(void*)((&Cls::toString)))
      {
        return this->toString();
      }
      else
      {
        return "";
      }
    }
    virtual ~Cls()=0;
};  Cls::~Cls(){}

This compiles on GCC, but fills your screen with warnings about strange convertion from funcptr to void*. At least it works as intended. There may be some metaprogramming compile-time solutions, need to think about it.

Appendix1, testing comparison between member funcs:

It is really weird

#include <iostream>

class Base
{
    public:
        virtual int test()
        {
            //default imp
            return 0;
        }
};

class Der : public Base
{
    public:
        int test() override
        {
            //custom imp
            return 1;
        }
};

int main()
{
    Der a;
    Base b;
    std::cout << ((&Der::test) == (&Base::test)) << std::endl;//1: wrong
    //they are not equal
    //but for some reason the output is "true"
    //so direct comparisons do not work
    //however
    //if you convert that pointer to void*
    //everything works
    std::cout << ((void*)(&Der::test) == (void*)(&Base::test) ) << std::endl;      //0:right
    std::cout << ((void*)(a.*(&Base::test)) == (void*)(&Base::test) ) << std::endl;//0:right
    std::cout << ((void*)(b.*(&Base::test)) == (void*)(&Base::test) ) << std::endl;//1:right
    std::cout << ((void*)(&(a.test)) == (void*)(&(b.test)) ) << std::endl;         //0:right
    //so if you want to compare two functions
    //cast them to void*
    //works in any cases
    //'-Wno-pmf-conversions' compiler flag to inhibit warnings about casting
    system("pause");
    return 0;
}

Appendix2, steps of getting real address of the function:

Cls::serialize; //the function object itself
&Cls::serialize; //its member pointer
(void*)(&Cls::serialize); //extracting real address of the function for the comparison
(this->*&Cls::serialize); //again, a member pointer
(void*)(this->*&Cls::serialize); //extracting real address
//  │        │  └── Getting "pointer" to a member function of the class
//  │        └───── Then binding 'this' to that function, recall that if the function is virtual, '->*' returns a mamber pointer to it's custom implementation, not the default one.
//  └────────────── Then getting the real address

// it looks like 'this->*&Cls::serialize' does the same as '&this->serialize'
// but in practice it's not quite right
// '&this->serialize' returns the function pointer based on 'this' type
// therefore, comparison breaks, as inside of a base class 'this' always has the base type
// so you always receive the default implementation pointer
// 'this->*&Cls::serialize' does the same
// but now if 'serialize' is virtual
// it takes it into account and sends back its' custom implementation pointer

// (void*) casting is required because you need to compare functions' real addresses
// if you compare member pointers of a single virtual function
// they seem to be equal while they are, in fact, not

The issue of checking if the derived class has implemented some of the base class virtual functions is here


来源: stackexchange

问:
Calling the same endpoint more than once in Cherrypy
I have created a simple web server with Cherrypy and my resources are only available the first time I make the call.

For example:

When I put the following on the browser http://127.0.0.1:8080/catalog/about - it displays the Cherrypy version as{"version": "18.1.1"} - which is correct.

However, If I hit enter one more time I get the following "404 Not Found"

Is this a safety feature and how do I change this settings? I don't understand

server.py:

```<code>import os
import os.path
import random
import string
import json
import cherrypy
from controller import Catalog

class Server(object):

  @cherrypy.expose
  def index(self):
    return open('../cococlient/build/index.html')

def cors():
  cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"

if __name__ == '__main__':
    conf = {
        '/': {
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/catalog': {
            'tools.CORS.on': True,
            'tools.response_headers.on': True
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '../cococlient/build/static'
        }
    }

    server = Server()
    server.catalog = Catalog()
    cherrypy.tools.CORS = cherrypy.Tool('before_handler', cors)

    # cherrypy.tree.mount(server, '/', conf)
    # cherrypy.engine.start()
    # cherrypy.engine.block()

    cherrypy.quickstart(server, '/', conf)
</code>```

controller.py:

```<code>import cherrypy

class Catalog(object):

  @cherrypy.expose
  @cherrypy.tools.json_out()
  def about(self):
    self.about = {
        "version": cherrypy.__version__
    }
    return self.about
</code>```

答:
Found the issue - the problem is that I am using the same name for the method and variable inside. I am used to Java where I have no such issues.

So, instead of

```<code>  @cherrypy.expose
  @cherrypy.tools.json_out()
  def about(self):
    self.about = {
        "version": cherrypy.__version__
    }
    return self.about
</code>```

change to

```<code>  @cherrypy.expose
  @cherrypy.tools.json_out()
  def about(self):
    self.someOtherName = {
        "version": cherrypy.__version__
    }
    return self.someOtherName
</code>```

Success!

ContentLicense: CC BY-SA 4.0

Body:
I have created a simple web server with Cherrypy and my resources are only available the first time I make the call.

For example:

When I put the following on the browser http://127.0.0.1:8080/catalog/about - it displays the Cherrypy version as{"version": "18.1.1"} - which is correct.

However, If I hit enter one more time I get the following "404 Not Found"

Is this a safety feature and how do I change this settings? I don't understand

server.py:

import os
import os.path
import random
import string
import json
import cherrypy
from controller import Catalog

class Server(object):

  @cherrypy.expose
  def index(self):
    return open('../cococlient/build/index.html')

def cors():
  cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"

if __name__ == '__main__':
    conf = {
        '/': {
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/catalog': {
            'tools.CORS.on': True,
            'tools.response_headers.on': True
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '../cococlient/build/static'
        }
    }

    server = Server()
    server.catalog = Catalog()
    cherrypy.tools.CORS = cherrypy.Tool('before_handler', cors)

    # cherrypy.tree.mount(server, '/', conf)
    # cherrypy.engine.start()
    # cherrypy.engine.block()

    cherrypy.quickstart(server, '/', conf)

controller.py:

import cherrypy

class Catalog(object):

  @cherrypy.expose
  @cherrypy.tools.json_out()
  def about(self):
    self.about = {
        "version": cherrypy.__version__
    }
    return self.about

Body:
Found the issue - the problem is that I am using the same name for the method and variable inside. I am used to Java where I have no such issues.

So, instead of

  @cherrypy.expose
  @cherrypy.tools.json_out()
  def about(self):
    self.about = {
        "version": cherrypy.__version__
    }
    return self.about

change to

  @cherrypy.expose
  @cherrypy.tools.json_out()
  def about(self):
    self.someOtherName = {
        "version": cherrypy.__version__
    }
    return self.someOtherName

Success!


问:
How to remove &nbsp from TextView
I need to substitute &nbps in TextView. I can simply use String.replace(), but there might be better solution?

答:
Try to use this function:</p>

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mDescription.setText(Html.fromHtml("Your Text", Html.FROM_HTML_MODE_LEGACY));
        } else {
            mDescription.setText(Html.fromHtml("Your Text"));
        }
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to remove &nbsp from TextView

Body:
Try to use this function:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mDescription.setText(Html.fromHtml("Your Text", Html.FROM_HTML_MODE_LEGACY));
        } else {
            mDescription.setText(Html.fromHtml("Your Text"));
        }


问:
No idea why my border-bottom not working can someone please solve it
I created a nav bar but my border-bottom not working , it is working as a border-top instead. I am trying to create a nav bar like twitter for learning. It will be a great help if someone helps me to solve it

*{
 margin: 0px;
 padding: 0px;
}

.header{
 width: 100%;
 height: auto;
 border-bottom:  1px solid #dae0e4;
}
.container{
 width: 90%;
 margin: 10px auto;
}
.main-nav{
 width: 50%;
 float: left;
}
.second-nav{
 float: right;
}
ul {
  list-style-type: none;
  overflow: hidden;
}
li {
  float: left;
  font-size: 120%;
}
li a {
 color: #6f7d87;
 display: block;
 text-align: center;
 padding: 14px 16px;
 text-decoration: none;
}
.body{
 clear: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <title>Twitter</title>
 <link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
 <div class="page">
  <div class="header">
   <div class="container">
    <div class="main-nav">
     <ul>
      <li>Home</li>
      <li>Notification</li>
      <li>Messages</li>
     </ul>
    </div>
    <div class="second-nav">
     <ul>
      <li>Search Bar</li>
      <li>Profile</li>
      <li>Tweet</li>
     </ul>
    </div>
   </div>
  </div>
  <div class="body">
   <p>Something</p>
  </div>
 </div>
</body>
</html></code>```

I expect the border to show the lining downside but it is showing it upside, I couldn't find the solution anywhere on the web and also I was unable to fix it.

答:
The border did appear, but visually on top of the header.

This is because the child elements of .header are floated and hence the height of .header becomes zero. To avoid this, add a clearfix to .header. Here I've used overflow:auto to fix it.

* {
  margin: 0px;
  padding: 0px;
}

.header {
  width: 100%;
  height: auto;
  border-bottom: 1px solid #000;
}

.container {
  width: 90%;
  margin: 10px auto;
  overflow: auto;
}

.main-nav {
  width: 50%;
  float: left;
}

.second-nav {
  float: right;
}

ul {
  list-style-type: none;
  overflow: hidden;
}

li {
  float: left;
  font-size: 120%;
}

li a {
  color: #6f7d87;
  display: block;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.body {
  clear: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page">
  <div class="header">
    <div class="container">
      <div class="main-nav">
        <ul>
          <li>Home</li>
          <li>Notification</li>
          <li>Messages</li>
        </ul>
      </div>
      <div class="second-nav">
        <ul>
          <li>Search Bar</li>
          <li>Profile</li>
          <li>Tweet</li>
        </ul>
      </div>
    </div>
  </div>
  <div class="body">
    <p>Something</p>
  </div>
</div></code>```

Body:
I created a nav bar but my border-bottom not working , it is working as a border-top instead. I am trying to create a nav bar like twitter for learning. It will be a great help if someone helps me to solve it

*{
 margin: 0px;
 padding: 0px;
}

.header{
 width: 100%;
 height: auto;
 border-bottom:  1px solid #dae0e4;
}
.container{
 width: 90%;
 margin: 10px auto;
}
.main-nav{
 width: 50%;
 float: left;
}
.second-nav{
 float: right;
}
ul {
  list-style-type: none;
  overflow: hidden;
}
li {
  float: left;
  font-size: 120%;
}
li a {
 color: #6f7d87;
 display: block;
 text-align: center;
 padding: 14px 16px;
 text-decoration: none;
}
.body{
 clear: both;
}

<!DOCTYPE html>

 <title>Twitter</title>
 <link rel="stylesheet" type="text/css" href="css.css">

Home

Notification

Messages

Search Bar

Profile

Tweet

Something

I expect the border to show the lining downside but it is showing it upside, I couldn't find the solution anywhere on the web and also I was unable to fix it.

Body:
The border did appear, but visually on top of the header.

This is because the child elements of .header are floated and hence the height of .header becomes zero. To avoid this, add a clearfix to .header. Here I've used overflow:auto to fix it.

* {
  margin: 0px;
  padding: 0px;
}

.header {
  width: 100%;
  height: auto;
  border-bottom: 1px solid #000;
}

.container {
  width: 90%;
  margin: 10px auto;
  overflow: auto;
}

.main-nav {
  width: 50%;
  float: left;
}

.second-nav {
  float: right;
}

ul {
  list-style-type: none;
  overflow: hidden;
}

li {
  float: left;
  font-size: 120%;
}

li a {
  color: #6f7d87;
  display: block;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.body {
  clear: both;
}

<div class="page">
  <div class="header">
    <div class="container">
      <div class="main-nav">
        <ul>
          <li><a href="">Home</a></li>
          <li><a href="">Notification</a></li>
          <li><a href="">Messages</a></li>
        </ul>
      </div>
      <div class="second-nav">
        <ul>
          <li><a href="">Search Bar</a></li>
          <li><a href="">Profile</a></li>
          <li><a href="">Tweet</a></li>
        </ul>
      </div>
    </div>
  </div>
  <div class="body">
    <p>Something</p>
  </div>
</div>


问:
Templates and dependency injection
I have a class template ResourceManager and it is intended to be used something like this:

```<code>ResourceManager<Image>* rm =
    ResourceManager<Image>::Instance();

Image* img = rm->acquire("picture.jpg");
rm->release(img);
</code>```

I'd like to use dependency injection (pass the ResourceManager as a parameter to functions that are supposed to use it instead of having it used globally), however given that it's a template I don't know how to do this. Do you have any suggestions?

My game is only at the beginning of the development and I already have four resource types (Image, Font, Animation and Sound) so making a single ResourceManager (i.e. not a template) with an acquire function for each type of resource is not an option.

Edit: Some clarifications.

What I'm looking for is not how to do dependency injection for one type of ResourceManager, but for all of them at once.

My GameState objects need to load resources when they are initialized/opened; they do so through the ResourceManagers. However, GameStates may need to load any number of types of resources: animations, fonts, images, sounds, etc — that's a lot of function parameters for each kind of ResourceManager! What do you suggest I do?

答:
An example using constructor injection:

```<code>template<typename T>
struct ResourceManager
{
  virtual T* acquire(std::string const& resourceName)
  { return ...; }
  ... etc ...
};

class ImageUser
{
  ResourceManager<Image>* rm_;

  public:
  explicit ImageUser(ResourceManager<Image>* rm)
    : rm_(rm)
  {}

  ImageUser()
    : rm_(ResourceManager<Image>::Instance())
  {}

  void UseImage()
  {
    Image* img = rm_->acquire("picture.jpg");
    rm_->release(img);
  }
};

struct ImageResourceManagerFake : ResourceManager<Image>
{
  virtual Image* acquire(std::string const& resourceName) // override
  { return <whatever-you-want>; }
  ... etc ...
};

void test_imageuser()
{
  ImageResourceManagerFake* rm = new ImageResourceManagerFake;
  ImageUser iu(rm);
  ... test away ...
}
</code>```

Note that I've left out all resource management; use smart pointers etc wherever applicable.

Title: Templates and dependency injection

Body:
I have a class template ResourceManager and it is intended to be used something like this:

ResourceManager<Image>* rm =
    ResourceManager<Image>::Instance();

Image* img = rm->acquire("picture.jpg");
rm->release(img);

I'd like to use dependency injection (pass the ResourceManager as a parameter to functions that are supposed to use it instead of having it used globally), however given that it's a template I don't know how to do this. Do you have any suggestions?

My game is only at the beginning of the development and I already have four resource types (Image, Font, Animation and Sound) so making a single ResourceManager (i.e. not a template) with an acquire function for each type of resource is not an option.

Edit: Some clarifications.

What I'm looking for is not how to do dependency injection for one type of ResourceManager, but for all of them at once.

My GameState objects need to load resources when they are initialized/opened; they do so through the ResourceManagers. However, GameStates may need to load any number of types of resources: animations, fonts, images, sounds, etc — that's a lot of function parameters for each kind of ResourceManager! What do you suggest I do?

Body:
An example using constructor injection:

template<typename T>
struct ResourceManager
{
  virtual T* acquire(std::string const& resourceName)
  { return ...; }
  ... etc ...
};

class ImageUser
{
  ResourceManager<Image>* rm_;

  public:
  explicit ImageUser(ResourceManager<Image>* rm)
    : rm_(rm)
  {}

  ImageUser()
    : rm_(ResourceManager<Image>::Instance())
  {}

  void UseImage()
  {
    Image* img = rm_->acquire("picture.jpg");
    rm_->release(img);
  }
};

struct ImageResourceManagerFake : ResourceManager<Image>
{
  virtual Image* acquire(std::string const& resourceName) // override
  { return <whatever-you-want>; }
  ... etc ...
};

void test_imageuser()
{
  ImageResourceManagerFake* rm = new ImageResourceManagerFake;
  ImageUser iu(rm);
  ... test away ...
}

Note that I've left out all resource management; use smart pointers etc wherever applicable.


问:
Add login screen infront of TabBar in IOS
I have an application containing a tab bar view and I have a login xib(login.xib) and its corresponding class files(LoginController) in the same application. I want that when my application launches, the login file should be loaded first and then once I click on the login button, my TabBar View should be launched.

Tried a lot many ways, but nothing worked. :(

Latest one is I tried putting the following code in the AppDelegate file at the end of application didFinishLaunchingWithOptions but facing an error:

```<code>loginController = [[LoginController alloc] init];
[window addSubview:tabcontroller.view];
[window addSubview:loginController.view];
[window makeKeyAndVisible];
return YES;
</code>```

Error is "loginController" is undeclared.

Am I missing something. Please let me know if there are any other ways through which I can fulfill my requirement.

Also, on clickButton() inside the login, I am using event Touch Up Inside.

答:
Just try using:

```<code>- (void)applicationDidFinishLaunching:(UIApplication *)application
{

     UIView *indicatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
     UIImageView *splashV=[[UIImageView alloc]initWithFrame:CGRectMake(0, 20, 320, 460)];
     [splashV setImage:[UIImage imageNamed:@"Default.png"]];
     [indicatorView setBackgroundColor:[UIColor clearColor]];

     [indicatorView addSubview:splashV];
     [self.window addSubview:indicatorView];

     //Take button check credentials on successful login call  StopViewOnsuccessfullogin

}

-(void)StopViewOnsuccessfullogin
{
    [indicatorView removeFromSuperview];
    [splashV release];
        [window addSubview:tabcontroller.view];
        [window makeKeyAndVisible];

}
</code>```

Hope that will work .....

Body:
I have an application containing a tab bar view and I have a login xib(login.xib) and its corresponding class files(LoginController) in the same application. I want that when my application launches, the login file should be loaded first and then once I click on the login button, my TabBar View should be launched.

Tried a lot many ways, but nothing worked. :(

Latest one is I tried putting the following code in the AppDelegate file at the end of application didFinishLaunchingWithOptions but facing an error:

loginController = [[LoginController alloc] init];
[window addSubview:tabcontroller.view];
[window addSubview:loginController.view];
[window makeKeyAndVisible];
return YES;

Error is "loginController" is undeclared.

Am I missing something. Please let me know if there are any other ways through which I can fulfill my requirement.

Also, on clickButton() inside the login, I am using event Touch Up Inside.

Body:
Just try using:

- (void)applicationDidFinishLaunching:(UIApplication *)application
{

     UIView *indicatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
     UIImageView *splashV=[[UIImageView alloc]initWithFrame:CGRectMake(0, 20, 320, 460)];
     [splashV setImage:[UIImage imageNamed:@"Default.png"]];
     [indicatorView setBackgroundColor:[UIColor clearColor]];

     [indicatorView addSubview:splashV];
     [self.window addSubview:indicatorView];

     //Take button check credentials on successful login call  StopViewOnsuccessfullogin

}

-(void)StopViewOnsuccessfullogin
{
    [indicatorView removeFromSuperview];
    [splashV release];
        [window addSubview:tabcontroller.view];
        [window makeKeyAndVisible];

}

Hope that will work .....


问:
How to tie radio button with input text fields?
This is a sign up form for an employee. The employee has to check in a radio button if he is temporary or permament. If temporary he should fill the input contract number and if permament the hiring date. How can I bind the radio button with the input so that he cannot "cross-complete" , for example fill the hiring date if he is temporary. I want to enable him to fill out each input only if he has pressed that specific radio button.

php code :

```<code><?php include 'dbconfig.php';?>
<?php header('Content-Type: text/html; charset=utf-8');?>
<!DOCTYPE HTML PUCLIC "-//W3C//DTDHTML
4.0 Transitional//EN"><HTML>
  <HEAD>
      <link rel="stylesheet" type="text/css" href="logintest.css">
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  </HEAD>
  <button class="btn" TYPE="submit" name="goback" onclick="window.location.href='login.php'">Go Back </button>

      <?php
      error_reporting(E_ALL); ini_set('display_errors', 1);
      if(isset($_POST['submit']))
      {
        $sql = "INSERT INTO employee (empID,EFirst,ELast,username, passcode)
        VALUES ('".$_POST["empID"]."','".$_POST["EFirst"]."','".$_POST["ELast"]."','".$_POST["username"]."','".$_POST["passcode"]."')";

        $result = mysqli_query($conn,$sql);
        $answer=$_POST['kind'];
        if($answer='permament'){
          $sql1 = "INSERT INTO permament_employee (empID,Hiring_Date) VALUES ('".$_POST["empID"]."','".$_POST["date"]."')";
          $result1 = mysqli_query($conn,$sql1);
        }

        if ($answer='temporary'){
          $sql2= "INSERT INTO temporary_employee(empID) VALUES ('".$_POST["empID"]."')";
          $result2 = mysqli_query($conn,$sql2);
        }
        echo "<script> location.replace('login.php') </script>";
      }
      ?>

    <FORM METHOD="post" ACTION="">
        <div class="input-group">
        <label>id</label>
           <INPUT TYPE="text" name="empID" SIZE="30" required>
        </div>
        <div class="input-group">
           <label>First Name</label>
           <INPUT TYPE="text" name="EFirst" SIZE="30" required>
        </div>
        <div class="input-group">
           <label>Last Name</label>
           <INPUT TYPE="text" name="ELast" SIZE="30" required>
        </div>
        <div class="input-group">
            <label>username</label>
            <INPUT TYPE="text" name="username" SIZE="30" required>
        </div>
        <div class="input-group">
             <label>password</label>
             <INPUT TYPE="password" name="passcode" SIZE="30" required>
        </div>
        <div class="input-group">
          <div class="some-class">
          <label> Permament  <input type="radio" name="kind" value="permament" id="permament" required>  <br>   <input type="date" name="date" value="date" id="date" required>  <br> </label>
          <label> Temporary  <input type="radio" name="kind" value="temporary" id="temporary" required>  <br>  <input type="number" name="ContractNr" value="ContractNr" id="ContractNr" placeholder="Contract Number" required>  <br>     </label>
          </div>
        </div>
        <br>
        <br>
        <br>
        <br>

        <button class="btn" TYPE="submit" name="submit">Submit Info </button>
        <button class="btn" TYPE="reset" name="Reset">Reset </button>
    </FORM>

</HTML>
</code>```

答:
You need javascript.
You have to bind a 'change' event on your radio buttons, and set visibility of your inputs according to radio button selected value.</p>

Body:
This is a sign up form for an employee. The employee has to check in a radio button if he is temporary or permament. If temporary he should fill the input contract number and if permament the hiring date. How can I bind the radio button with the input so that he cannot "cross-complete" , for example fill the hiring date if he is temporary. I want to enable him to fill out each input only if he has pressed that specific radio button.

php code :

<?php include 'dbconfig.php';?>
<?php header('Content-Type: text/html; charset=utf-8');?>
<!DOCTYPE HTML PUCLIC "-//W3C//DTDHTML
4.0 Transitional//EN">

      <link rel="stylesheet" type="text/css" href="logintest.css">
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">

  <button class="btn" TYPE="submit" name="goback" onclick="window.location.href='login.php'">Go Back </button>

      <?php
      error_reporting(E_ALL); ini_set('display_errors', 1);
      if(isset($_POST['submit']))
      {
        $sql = "INSERT INTO employee (empID,EFirst,ELast,username, passcode)
        VALUES ('".$_POST["empID"]."','".$_POST["EFirst"]."','".$_POST["ELast"]."','".$_POST["username"]."','".$_POST["passcode"]."')";

        $result = mysqli_query($conn,$sql);
        $answer=$_POST['kind'];
        if($answer='permament'){
          $sql1 = "INSERT INTO permament_employee (empID,Hiring_Date) VALUES ('".$_POST["empID"]."','".$_POST["date"]."')";
          $result1 = mysqli_query($conn,$sql1);
        }

        if ($answer='temporary'){
          $sql2= "INSERT INTO temporary_employee(empID) VALUES ('".$_POST["empID"]."')";
          $result2 = mysqli_query($conn,$sql2);
        }
        echo "";
      }
      ?>

    <FORM METHOD="post" ACTION="">

        id
           <INPUT TYPE="text" name="empID" SIZE="30" required>

           First Name
           <INPUT TYPE="text" name="EFirst" SIZE="30" required>

           Last Name
           <INPUT TYPE="text" name="ELast" SIZE="30" required>

            username
            <INPUT TYPE="text" name="username" SIZE="30" required>

             password
             <INPUT TYPE="password" name="passcode" SIZE="30" required>

           Permament  <input type="radio" name="kind" value="permament" id="permament" required>
   <input type="date" name="date" value="date" id="date" required>

           Temporary  <input type="radio" name="kind" value="temporary" id="temporary" required>
  <input type="number" name="ContractNr" value="ContractNr" id="ContractNr" placeholder="Contract Number" required>

        <button class="btn" TYPE="submit" name="submit">Submit Info </button>
        <button class="btn" TYPE="reset" name="Reset">Reset </button>
    </FORM>


问:
Cannot open any more tables - OleDbException was unhandled
Good Day,

     My question is how to handle the exception or get rid of the error pertaining to "Cannot open any more tables". For an overview to the program I was creating, I pull out the record of subject in ms access 2007, I loop to that record to randomly assign a schedule and one by one I insert the newly record with assigned schedule in the table.

My program flow of inserting the record work only for a certain number of times, like almost 200 and at some point it stop and pop-up the oledbexception

Thanks in advance for your time on answering my question.

here is my code for more detailed overview of my program,

```<code>Private Sub Assignsched(ByVal rType As String, ByVal subjectCode As String, ByVal SecID As String, ByVal CourseCode As String)
    If shrdcon.con.State = ConnectionState.Closed Then
        shrdcon.con.Open()
    End If
    Dim RoomNum As Integer
    dtARoom.Clear()
    Dim stoploop As Boolean

    Dim count As Integer = 0

    Dim rm1 As String
    RoomAssign = ""
    rm1 = "SELECT * FROM tblRoom WHERE RoomType = '" & rType & "'"
    Dim dat As New OleDbDataAdapter(rm1, shrdcon.con)
    dat.Fill(ds, "ARoom")

        stoploop = False
        count = 0
        Do Until stoploop = "True"
        RoomNum = rndm.Next(0, ds.Tables("ARoom").Rows.Count)
        RoomAssign = ds.Tables("ARoom").Rows(RoomNum).Item(1)

            ScheduleGeneration()

        If checkExisting(sTime, eTime, RoomAssign, daypick) = False Then

            RoomA = RoomAssign

            GenerateOfferingID()
            Dim cmd1 As New OleDbCommand()
            cmd1.CommandText = "INSERT INTO [tblSubjectOffer]([SubjectOID],[SubjectCode],[SectionID],[Day],[sTime],[eTime],[RoomName],[CourseCode]) VALUES('" & _
                                myId & "','" & subjectCode & "','" & SecID & "','" & daypick & "'," & sTime & "," & eTime & ",'" & RoomA & "','" & CourseCode & "')"
            cmd1.Connection = shrdcon.con
            cmd1.ExecuteNonQuery()
            cmd1.Dispose()

            Dim pipz As New OleDbCommand("Update tblGenerator Set NextNo='" & myId & "' where TableName ='" & "tblSubjectOffer" & "'", shrdcon.con)
            pipz.ExecuteNonQuery()
            pipz.Dispose()
            stoploop = True
        Else
            stoploop = False
        End If
            If stoploop = False Then

            If count = 30 Then
                stoploop = True
            Else

                count = count + 1

            End If
            End If
        Loop
End Sub
</code>```

答:
I got this exception in my C# application and the cause was using OleDbDataReader instances without closing them:</p>

```<code>OleDbDataReader reader = cmd.ExecuteReader();
bool result = reader.Read();
reader.Close(); // <= Problem went away after adding this
return result;
</code>```

Body:
Good Day,

     My question is how to handle the exception or get rid of the error pertaining to "Cannot open any more tables". For an overview to the program I was creating, I pull out the record of subject in ms access 2007, I loop to that record to randomly assign a schedule and one by one I insert the newly record with assigned schedule in the table.

My program flow of inserting the record work only for a certain number of times, like almost 200 and at some point it stop and pop-up the oledbexception

Thanks in advance for your time on answering my question.

here is my code for more detailed overview of my program,

Private Sub Assignsched(ByVal rType As String, ByVal subjectCode As String, ByVal SecID As String, ByVal CourseCode As String)
    If shrdcon.con.State = ConnectionState.Closed Then
        shrdcon.con.Open()
    End If
    Dim RoomNum As Integer
    dtARoom.Clear()
    Dim stoploop As Boolean

    Dim count As Integer = 0

    Dim rm1 As String
    RoomAssign = ""
    rm1 = "SELECT * FROM tblRoom WHERE RoomType = '" & rType & "'"
    Dim dat As New OleDbDataAdapter(rm1, shrdcon.con)
    dat.Fill(ds, "ARoom")

        stoploop = False
        count = 0
        Do Until stoploop = "True"
        RoomNum = rndm.Next(0, ds.Tables("ARoom").Rows.Count)
        RoomAssign = ds.Tables("ARoom").Rows(RoomNum).Item(1)

            ScheduleGeneration()

        If checkExisting(sTime, eTime, RoomAssign, daypick) = False Then

            RoomA = RoomAssign

            GenerateOfferingID()
            Dim cmd1 As New OleDbCommand()
            cmd1.CommandText = "INSERT INTO [tblSubjectOffer]([SubjectOID],[SubjectCode],[SectionID],[Day],[sTime],[eTime],[RoomName],[CourseCode]) VALUES('" & _
                                myId & "','" & subjectCode & "','" & SecID & "','" & daypick & "'," & sTime & "," & eTime & ",'" & RoomA & "','" & CourseCode & "')"
            cmd1.Connection = shrdcon.con
            cmd1.ExecuteNonQuery()
            cmd1.Dispose()

            Dim pipz As New OleDbCommand("Update tblGenerator Set NextNo='" & myId & "' where TableName ='" & "tblSubjectOffer" & "'", shrdcon.con)
            pipz.ExecuteNonQuery()
            pipz.Dispose()
            stoploop = True
        Else
            stoploop = False
        End If
            If stoploop = False Then

            If count = 30 Then
                stoploop = True
            Else

                count = count + 1

            End If
            End If
        Loop
End Sub

Body:
I got this exception in my C# application and the cause was using OleDbDataReader instances without closing them:

OleDbDataReader reader = cmd.ExecuteReader();
bool result = reader.Read();
reader.Close(); // <= Problem went away after adding this
return result;


问:
How does StringBuilder reverse work in Java?
I am trying to solve this leetcode question
https://leetcode.com/problems/palindrome-linked-list/ , but running into trouble with strings and string builders. For some reason, "12".equals"21" -> returns true.

I tried converting from string builder to string, and just using stringbuilder.

```<code>class Solution {
public boolean isPalindrome(ListNode head) {
    StringBuilder s = new StringBuilder();
    while (head != null) {
        s.append(head.val);
        head = head.next;
    }
    String a = s.reverse().toString();
    String b = s.toString();
    return a.equals(b);
}
}
</code>```

It fails on "12" test case, and returns true.

答:
Here's one using only 2 StringBuilders instead of 3 and doesn't use the built-in reversed method. Instead, the while loop traverses through the linked list, appends the current node to the original StringBuilder, and inserts the current node at the front of the reversed StringBuilder. So the built-in insert method helps with reversing the order of the nodes values :

```<code>public boolean isPalindrome(ListNode head) {
     StringBuilder original = new StringBuilder(), reversed = new StringBuilder();
     ListNode curr = head;
     while (curr != null) {
         original.append(curr.val);
         reversed.insert(0, curr.val);
         curr = curr.next;
     }
     return original.toString().equals(reversed.toString()) ? true : false;
}
</code>```

Body:
I am trying to solve this leetcode question
https://leetcode.com/problems/palindrome-linked-list/ , but running into trouble with strings and string builders. For some reason, "12".equals"21" -> returns true.

I tried converting from string builder to string, and just using stringbuilder.

class Solution {
public boolean isPalindrome(ListNode head) {
    StringBuilder s = new StringBuilder();
    while (head != null) {
        s.append(head.val);
        head = head.next;
    }
    String a = s.reverse().toString();
    String b = s.toString();
    return a.equals(b);
}
}

It fails on "12" test case, and returns true.

Body:
Here's one using only 2 StringBuilders instead of 3 and doesn't use the built-in reversed method. Instead, the while loop traverses through the linked list, appends the current node to the original StringBuilder, and inserts the current node at the front of the reversed StringBuilder. So the built-in insert method helps with reversing the order of the nodes values :

public boolean isPalindrome(ListNode head) {
     StringBuilder original = new StringBuilder(), reversed = new StringBuilder();
     ListNode curr = head;
     while (curr != null) {
         original.append(curr.val);
         reversed.insert(0, curr.val);
         curr = curr.next;
     }
     return original.toString().equals(reversed.toString()) ? true : false;
}


问:
How to communicate between pods of the same service on the same k8s cluster using k8s-java-client?
I have a kubernetes cluster that has many services on it. How can I make one pod publish a message, and receive it from another siblings pods (pods of the same service), using kubernetes-java-client.

Until now, I didn't find a way to do the job done.

Example:
1 Service -> 4 pod (4/4 replicaSet)

Invoke Api in the service, load balance takes the request to 1 Pod, so other pods need to do a reaction because a specific Api in another pod has been activated.

So, the pod publish an event, and other sibling pods consumes the event, an do the reaction. Or the pod communicates directly with its siblings to tell them to do the reaction.

Is this possible, and what is the right way to a similar scenario?

答: Other than using the Kubernetes API to discover the peer pods (usually via the endpoints API), it doesn’t provide anything in particular for the actual comms, that would be up to your code.</p>


问:
Get the Content value of the WPF button using one event handler
Say, I have this WPF Grid. How do I get the Content value of the WPF button using one event handler?</p>

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Content="A" Grid.Row="0" />
    <Button Content="B" Grid.Row="0" Grid.Column="1" />
    <Button Content="C" Grid.Row="0" Grid.Column="2" />
    <Button Content="D" Grid.Row="0" Grid.Column="3" />
    <Button Content="E" Grid.Row="1" />
    <Button Content="F" Grid.Row="1" Grid.Column="1" />
    <Button Content="G" Grid.Row="1" Grid.Column="2" />
    <Button Content="H" Grid.Row="1" Grid.Column="3" />
    <Button Content="I" Grid.Row="2" />
    <Button Content="B" Grid.Row="2" Grid.Column="1" />
    <Button Content="J" Grid.Row="2" Grid.Column="2" />
    <Button Content="K" Grid.Row="2" Grid.Column="3" />
</Grid>
</code>```

答:
Xaml

```<code> <Button Content="abc" Click="ButtonBase_OnClick"></Button>
</code>```

Event

```<code>private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        var senderBtn = sender as Button;
        MessageBox.Show(senderBtn.Content.ToString());
    }
</code>```

Body:
Say, I have this WPF Grid. How do I get the Content value of the WPF button using one event handler?

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Content="A" Grid.Row="0" />
    <Button Content="B" Grid.Row="0" Grid.Column="1" />
    <Button Content="C" Grid.Row="0" Grid.Column="2" />
    <Button Content="D" Grid.Row="0" Grid.Column="3" />
    <Button Content="E" Grid.Row="1" />
    <Button Content="F" Grid.Row="1" Grid.Column="1" />
    <Button Content="G" Grid.Row="1" Grid.Column="2" />
    <Button Content="H" Grid.Row="1" Grid.Column="3" />
    <Button Content="I" Grid.Row="2" />
    <Button Content="B" Grid.Row="2" Grid.Column="1" />
    <Button Content="J" Grid.Row="2" Grid.Column="2" />
    <Button Content="K" Grid.Row="2" Grid.Column="3" />
</Grid>

Body:
Xaml

 <Button Content="abc" Click="ButtonBase_OnClick"></Button>

Event

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        var senderBtn = sender as Button;
        MessageBox.Show(senderBtn.Content.ToString());
    }


问:
Adding the last two elements of a list
In Mathematica, what is the cleanest way of taking a list

```<code>{r1, r2, r3, ..., rn, a, b}
</code>```

and returning

```<code>{r1, r2, r3, ..., rn, a + b}
</code>```

or more generally

```<code>{r1, r2, r3, ..., rn, f[a, b]}
</code>```

for some function f?

Title: Adding the last two elements of a list

Body:
In Mathematica, what is the cleanest way of taking a list

{r1, r2, r3, ..., rn, a, b}

and returning

{r1, r2, r3, ..., rn, a + b}

or more generally

{r1, r2, r3, ..., rn, f[a, b]}

for some function f?

Body:
lst = {a[1], a[2], a[3], a[4], a[5], a[6], a[7], a, b};
lst /. {a___, b_, c_} -> {a, f[b, c]}

 ==> {a[1], a[2], a[3], a[4], a[5], a[6], a[7], f[a, b]}

or (ugly):

Append[Take[lst, {1, -3}], f @@ lst[[{-2, -1}]]]


问:
How to optimize the linear coefficients for numpy arrays in a maximization function?
I have to optimize the coefficients for three numpy arrays which maximizes my evaluation function.
I have a target array called train['target'] and three predictions arrays named array1, array2 and array3.

I want to put the best linear coefficients i.e., x,y,z for these three arrays which will maximize the function

roc_aoc_curve(train['target'], xarray1 + yarray2 +z*array3)

the above function would be maximum when prediction is closer to the target.
i.e, xarray1 + yarray2 + z*array3 should be closer to train['target'].

The range of x,y,z >=0 and x,y,z <= 1

Basically I am trying to put the weights x,y,z for each of the three arrays which would make the function

xarray1 + yarray2 +z*array3 closer to the  train['target']

Any help in getting this would be appreciated.

I used pulp.LpProblem('Giapetto', pulp.LpMaximize) to do the maximization. It works for normal numbers, integers etc, however failing while trying to do with arrays.

```<code>import numpy as np
import pulp

# create the LP object, set up as a maximization problem
prob = pulp.LpProblem('Giapetto', pulp.LpMaximize)

# set up decision variables
x = pulp.LpVariable('x', lowBound=0)
y = pulp.LpVariable('y', lowBound=0)
z = pulp.LpVariable('z', lowBound=0)

score =  roc_auc_score(train['target'],x*array1+ y*array2 + z*array3)

prob += score

coef = x+y+z

prob += (coef==1)

# solve the LP using the default solver
optimization_result = prob.solve()

# make sure we got an optimal solution
assert optimization_result == pulp.LpStatusOptimal

# display the results
for var in (x, y,z):
    print('Optimal weekly number of {} to produce: {:1.0f}'.format(var.name, var.value()))
</code>```

Getting error at the line

```<code>score =  roc_auc_score(train['target'],x*array1+ y*array2 + z*array3)
</code>```

TypeError: unsupported operand type(s) for /: 'int' and 'LpVariable'

Can't progress beyond this line when using arrays. Not sure if my approach is correct. Any help in optimizing the function would be appreciated.

答:
When you add sums of array elements to a PuLP model, you have to use built-in PuLP constructs like lpSum to do it -- you can't just add arrays together (as you discovered).

So your score definition should look something like this:

```<code>score = pulp.lpSum([train['target'][i] - (x * array1[i] + y * array2[i] + z * array3[i]) for i in arr_ind])
</code>```

A few notes about this:

[+] You didn't provide the definition of roc_auc_score so I just pretended that it equals the sum of the element-wise difference between the target array and the weighted sum of the other 3 arrays.

[+] I suspect your actual calculation for roc_auc_score is nonlinear; more on this below.

[+] arr_ind is a list of the indices of the arrays, which I created like this:

```<code># build array index
arr_ind = range(len(array1))
</code>```

[+] You also didn't include the arrays, so I created them like this:

```<code>array1 = np.random.rand(10, 1)
array2 = np.random.rand(10, 1)
array3 = np.random.rand(10, 1)

train = {}
train['target'] = np.ones((10, 1))
</code>```

Here is my complete code, which compiles and executes, though I'm sure it doesn't give you the result you are hoping for, since I just guessed about target and roc_auc_score:

```<code>import numpy as np
import pulp

# create the LP object, set up as a maximization problem
prob = pulp.LpProblem('Giapetto', pulp.LpMaximize)

# dummy arrays since arrays weren't in OP code
array1 = np.random.rand(10, 1)
array2 = np.random.rand(10, 1)
array3 = np.random.rand(10, 1)

# build array index
arr_ind = range(len(array1))

# set up decision variables
x = pulp.LpVariable('x', lowBound=0)
y = pulp.LpVariable('y', lowBound=0)
z = pulp.LpVariable('z', lowBound=0)

# dummy roc_auc_score since roc_auc_score wasn't in OP code
train = {}
train['target'] = np.ones((10, 1))
score = pulp.lpSum([train['target'][i] - (x * array1[i] + y * array2[i] + z * array3[i]) for i in arr_ind])

prob += score

coef = x + y + z

prob += coef == 1

# solve the LP using the default solver
optimization_result = prob.solve()

# make sure we got an optimal solution
assert optimization_result == pulp.LpStatusOptimal

# display the results
for var in (x, y,z):
    print('Optimal weekly number of {} to produce: {:1.0f}'.format(var.name, var.value()))
</code>```

Output:

```<code>Optimal weekly number of x to produce: 0
Optimal weekly number of y to produce: 0
Optimal weekly number of z to produce: 1

Process finished with exit code 0
</code>```

Now, if your roc_auc_score function is nonlinear, you will have additional troubles. I would encourage you to try to formulate the score in a way that is linear, possibly using additional variables (for example, if you want the score to be an absolute value).

Body:
I have to optimize the coefficients for three numpy arrays which maximizes my evaluation function.
I have a target array called train['target'] and three predictions arrays named array1, array2 and array3.

I want to put the best linear coefficients i.e., x,y,z for these three arrays which will maximize the function

roc_aoc_curve(train['target'], xarray1 + yarray2 +z*array3)

the above function would be maximum when prediction is closer to the target.
i.e, xarray1 + yarray2 + z*array3 should be closer to train['target'].

The range of x,y,z >=0 and x,y,z <= 1

Basically I am trying to put the weights x,y,z for each of the three arrays which would make the function

xarray1 + yarray2 +z*array3 closer to the  train['target']

Any help in getting this would be appreciated.

I used pulp.LpProblem('Giapetto', pulp.LpMaximize) to do the maximization. It works for normal numbers, integers etc, however failing while trying to do with arrays.

import numpy as np
import pulp

# create the LP object, set up as a maximization problem
prob = pulp.LpProblem('Giapetto', pulp.LpMaximize)

# set up decision variables
x = pulp.LpVariable('x', lowBound=0)
y = pulp.LpVariable('y', lowBound=0)
z = pulp.LpVariable('z', lowBound=0)

score =  roc_auc_score(train['target'],x*array1+ y*array2 + z*array3)

prob += score

coef = x+y+z

prob += (coef==1)

# solve the LP using the default solver
optimization_result = prob.solve()

# make sure we got an optimal solution
assert optimization_result == pulp.LpStatusOptimal

# display the results
for var in (x, y,z):
    print('Optimal weekly number of {} to produce: {:1.0f}'.format(var.name, var.value()))

Getting error at the line

score =  roc_auc_score(train['target'],x*array1+ y*array2 + z*array3)

TypeError: unsupported operand type(s) for /: 'int' and 'LpVariable'

Can't progress beyond this line when using arrays. Not sure if my approach is correct. Any help in optimizing the function would be appreciated.

Body:
When you add sums of array elements to a PuLP model, you have to use built-in PuLP constructs like lpSum to do it -- you can't just add arrays together (as you discovered).

So your score definition should look something like this:

score = pulp.lpSum([train['target'][i] - (x * array1[i] + y * array2[i] + z * array3[i]) for i in arr_ind])

A few notes about this:

[+] You didn't provide the definition of roc_auc_score so I just pretended that it equals the sum of the element-wise difference between the target array and the weighted sum of the other 3 arrays.

[+] I suspect your actual calculation for roc_auc_score is nonlinear; more on this below.

[+] arr_ind is a list of the indices of the arrays, which I created like this:

# build array index
arr_ind = range(len(array1))

[+] You also didn't include the arrays, so I created them like this:

array1 = np.random.rand(10, 1)
array2 = np.random.rand(10, 1)
array3 = np.random.rand(10, 1)

train = {}
train['target'] = np.ones((10, 1))

Here is my complete code, which compiles and executes, though I'm sure it doesn't give you the result you are hoping for, since I just guessed about target and roc_auc_score:

import numpy as np
import pulp

# create the LP object, set up as a maximization problem
prob = pulp.LpProblem('Giapetto', pulp.LpMaximize)

# dummy arrays since arrays weren't in OP code
array1 = np.random.rand(10, 1)
array2 = np.random.rand(10, 1)
array3 = np.random.rand(10, 1)

# build array index
arr_ind = range(len(array1))

# set up decision variables
x = pulp.LpVariable('x', lowBound=0)
y = pulp.LpVariable('y', lowBound=0)
z = pulp.LpVariable('z', lowBound=0)

# dummy roc_auc_score since roc_auc_score wasn't in OP code
train = {}
train['target'] = np.ones((10, 1))
score = pulp.lpSum([train['target'][i] - (x * array1[i] + y * array2[i] + z * array3[i]) for i in arr_ind])

prob += score

coef = x + y + z

prob += coef == 1

# solve the LP using the default solver
optimization_result = prob.solve()

# make sure we got an optimal solution
assert optimization_result == pulp.LpStatusOptimal

# display the results
for var in (x, y,z):
    print('Optimal weekly number of {} to produce: {:1.0f}'.format(var.name, var.value()))

Output:

Optimal weekly number of x to produce: 0
Optimal weekly number of y to produce: 0
Optimal weekly number of z to produce: 1

Process finished with exit code 0

Now, if your roc_auc_score function is nonlinear, you will have additional troubles. I would encourage you to try to formulate the score in a way that is linear, possibly using additional variables (for example, if you want the score to be an absolute value).


问:
Clear Column Data except first Headers |Excel|VBA|
I want to Delete the Column Data of "A" and "B" on button click => except the First Cell of both the Columns A and B which are headers

My Sheet :

```<code>    Private Sub CommandButton1_Click()

        Dim myRange As Range
        Set myRange = ThisWorkbook.Worksheets("Sheet2").Range("A:B")
        myRange.Clear

   End Sub
</code>```

Clear only Data [except the first Headers of A:B]

答:
Here:</p>

```<code>Option Explicit
Private Sub CommandButton1_Click()

    Dim myRange As Range
    Dim LastRow As Long 'declare a long variable to find the last row

    With ThisWorkbook.Sheets("Sheet2")
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'last row on column A
        Set myRange = .Range("A2:B" & LastRow) 'this way you avoid headers and clear everything
        myRange.Clear
    End With

End Sub
</code>```

Body:
I want to Delete the Column Data of "A" and "B" on button click => except the First Cell of both the Columns A and B which are headers

My Sheet :

    Private Sub CommandButton1_Click()

        Dim myRange As Range
        Set myRange = ThisWorkbook.Worksheets("Sheet2").Range("A:B")
        myRange.Clear

   End Sub

Clear only Data [except the first Headers of A:B]

Body:
Here:

Option Explicit
Private Sub CommandButton1_Click()

    Dim myRange As Range
    Dim LastRow As Long 'declare a long variable to find the last row

    With ThisWorkbook.Sheets("Sheet2")
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'last row on column A
        Set myRange = .Range("A2:B" & LastRow) 'this way you avoid headers and clear everything
        myRange.Clear
    End With

End Sub


问:
Python 3 - Nested loops
i have created 4 loop to loop into 4 different lists
put the last for is the only one that going in loop

```<code>ID =['2098','116','121']
major=['Electrical', 'Accounting', 'Commerce']
dgree=['Diploma', 'Diploma','Bachelor']
uni=['Institute', 'British careers training college', 'University Bharatidarsan']
for u in uni:
    for d in dgree:
        for m in major:
            for x in ID:
</code>```

it should go the first for then the second for then the 3rd for then the 4th for and back again to the first and so on

答:
To clarify for yourself what is happening, you can add print(u,d,m,x) inside the inner loop.

Then you will see, that first uni[0], dgree[0], major[0] followed by ID [0], then ID[1] and ID[2] is printed. We looped over all three IDs, so next there will be uni[0], dgree[0], major[1] followed again by ID[0] etc.

As explained in your comment, you want to loop over the four lists simultaneously. You can use one for loop and zip to do so:

```<code>for (u,d,m,x) in zip(uni,dgree,major,ID):
    print(u,d,m,x)
</code>```

Title: Python 3 - Nested loops

Body:
i have created 4 loop to loop into 4 different lists
put the last for is the only one that going in loop

ID =['2098','116','121']
major=['Electrical', 'Accounting', 'Commerce']
dgree=['Diploma', 'Diploma','Bachelor']
uni=['Institute', 'British careers training college', 'University Bharatidarsan']
for u in uni:
    for d in dgree:
        for m in major:
            for x in ID:

it should go the first for then the second for then the 3rd for then the 4th for and back again to the first and so on

Body:
To clarify for yourself what is happening, you can add print(u,d,m,x) inside the inner loop.

Then you will see, that first uni[0], dgree[0], major[0] followed by ID [0], then ID[1] and ID[2] is printed. We looped over all three IDs, so next there will be uni[0], dgree[0], major[1] followed again by ID[0] etc.

As explained in your comment, you want to loop over the four lists simultaneously. You can use one for loop and zip to do so:

for (u,d,m,x) in zip(uni,dgree,major,ID):
    print(u,d,m,x)


问:
Center checkbox using CSS
I have used CSS grid in my React.js app to locate elements precisely in my page.
I have split in grids but I have trouble to locate checkbox.
I would like checkboxes to be centered under the button, but they stay at the left of their grid.

Do you know how to center them ? I have read posts and tried things text-align, align-items, ... but it stays at the left.

.wrapperUA{
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-template-rows: 5vh 10vh 5vh 15vh 10vh 5vh 15vh 10vh 25vh;
  grid-gap: 5px;
  grid-template-areas:
  ". . . . ."
  ". . UA1 . ."
  ". UA21 UA22 UA23 ."
  ". . . . ."
  " . . UA3 . ."
  ". UA41 UA42 UA43 ."
  ". . . . ."
  ". . UA5 . ."
  ". . . . .";
  text-align: center;
  align-items: center;
  vertical-align: middle;
  align-content: center;
}

.UA1{
  grid-area: UA1;
}

.UA21{
  grid-area: UA21;
}

.UA22{
  grid-area: UA22;
}

.UA23{
  grid-area: UA23;
}

.UA3{
  grid-area: UA3;
}

.UA41{
  grid-area: UA41;
}

.UA42{
  grid-area: UA42;
}

.UA43{
  grid-area: UA43;
}

.UA5{
  grid-area: UA5;
}

.UA1, .UA3, .UA5{
    padding: 5px 10px;
    font-size: 10px;
    border-radius: 50px;
    border: 2px solid blue;
    color: blue;
    background-color: transparent;
    font-weight: bold
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>      <div class="wrapperUA" >
          <Button
                class="UA1"
                variant="primary">
                Read Manual
          </Button>
          text other language
          <input class="UA22" type="checkbox" onChange={this.handleCheckManual} defaultChecked={this.state.Manual}/>
          I agree with User manual
          <Button
                class="UA3"
                variant="primary">
                Read User Agreement
          </Button>

            text other language
            <input class="UA42" type="checkbox" onChange={this.handleCheckUCond} defaultChecked={this.state.UCond}/>
            I agree with user conditions

          <Button
              class="UA5"
              variant="primary">
              Pay
          </Button>
      </div></code>```

答:
Wrap a div tag around each checkbox with an inline style attribute:</p>

```<code><div style="text-align: center;">
  <input class="UA22" type="checkbox" onChange={this.handleCheckManual} defaultChecked {this.state.Manual}/>
</div>
</code>```

Title: Center checkbox using CSS

Body:
I have used CSS grid in my React.js app to locate elements precisely in my page.
I have split in grids but I have trouble to locate checkbox.
I would like checkboxes to be centered under the button, but they stay at the left of their grid.

Do you know how to center them ? I have read posts and tried things text-align, align-items, ... but it stays at the left.

.wrapperUA{
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-template-rows: 5vh 10vh 5vh 15vh 10vh 5vh 15vh 10vh 25vh;
  grid-gap: 5px;
  grid-template-areas:
  ". . . . ."
  ". . UA1 . ."
  ". UA21 UA22 UA23 ."
  ". . . . ."
  " . . UA3 . ."
  ". UA41 UA42 UA43 ."
  ". . . . ."
  ". . UA5 . ."
  ". . . . .";
  text-align: center;
  align-items: center;
  vertical-align: middle;
  align-content: center;
}

.UA1{
  grid-area: UA1;
}

.UA21{
  grid-area: UA21;
}

.UA22{
  grid-area: UA22;
}

.UA23{
  grid-area: UA23;
}

.UA3{
  grid-area: UA3;
}

.UA41{
  grid-area: UA41;
}

.UA42{
  grid-area: UA42;
}

.UA43{
  grid-area: UA43;
}

.UA5{
  grid-area: UA5;
}

.UA1, .UA3, .UA5{
    padding: 5px 10px;
    font-size: 10px;
    border-radius: 50px;
    border: 2px solid blue;
    color: blue;
    background-color: transparent;
    font-weight: bold
}

          <Button
                class="UA1"
                variant="primary">
                Read Manual
          </Button>
          text other language
          <input class="UA22" type="checkbox" onChange={this.handleCheckManual} defaultChecked={this.state.Manual}/>
          I agree with User manual
          <Button
                class="UA3"
                variant="primary">
                Read User Agreement
          </Button>

            text other language
            <input class="UA42" type="checkbox" onChange={this.handleCheckUCond} defaultChecked={this.state.UCond}/>
            I agree with user conditions

          <Button
              class="UA5"
              variant="primary">
              Pay
          </Button>

Body:
Wrap a div tag around each checkbox with an inline style attribute:

<div style="text-align: center;">
  <input class="UA22" type="checkbox" onChange={this.handleCheckManual} defaultChecked {this.state.Manual}/>
</div>


问:
Angular re-renders list of components when state is changed without mutation
I am coming from React and I've been working with Angular for a few months now. A React component updates only the necessary HTML when is re-rendered, while an Angular component seems to re-render completely when the state is not mutated. If I mutate the state directly seems to work just fine.

Here's my very basic example:

I have the main component which holds the state:

```<code>items = [{ name: "John", age: 8 }, { name: "Jane", age: 20 }];
</code>```

and in its view it renders a list of items:

<item *ngFor="let item of items" [item]="item"></item>
```

<p>the <strong>item</strong> component looks like this:</p>

```@Component({
  selector: "item",
  template: `

      {{ item.name }}, {{ item.age }}
      <input type="checkbox" />

  `
})
export class ItemComponent {
  @Input() item: any;
}
```

<p>I added that checkbox in the item component just to notice when the component is fully re-rendered.</p>

<p>So what I do is tick the checkboxes and increment the <code>age</code> for each user in the state.</p>

<p>If I increment it by mutating the state the view is updated as expected and the checkboxes remain checked:</p>

```this.items.forEach(item => {
  item.age++;
});
```

<p>But if I change the <code>age</code> without directly mutating the state the entire list is re-rendered and the checkbox is not checked anymore:</p>

```this.items = this.items.map(item => ({
  ...item,
  age: item.age + 1
}));
```

Here's a full example in a CodeSandbox.

Can anyone please explain why is this happening and how can I make the list to not fully re-render when I don't mutate the state?

答:
NgForOf directive which Angular uses to render list of items checks if there are any changes in array we pass to it.

If you mutate property in items then Angular knows that there is no changes since references to objects in array remain the same.

On the other hand, if you completely replace the previous object with new one then it is signal for ngForOf to rerender that object.

To determine if an object changes ngForOf directive use DefaultIterableDiffer that looks at trackByFn function if we provided it. If we don't provide it then the default function looks like:

```<code>var trackByIdentity = function (index, item) {
  return item;
};
</code>```

And then Angular compares result of this function with previous value in collection.

You can think about trackByFn like key in React.

So your solution might look like:

```<code>*ngFor="let item of items; trackBy: trackByFn"

trackByFn(i) {
    return i;
}
</code>```

https://codesandbox.io/s/angular-67vo6

Body:
I am coming from React and I've been working with Angular for a few months now. A React component updates only the necessary HTML when is re-rendered, while an Angular component seems to re-render completely when the state is not mutated. If I mutate the state directly seems to work just fine.

Here's my very basic example:

I have the main component which holds the state:

items = [{ name: "John", age: 8 }, { name: "Jane", age: 20 }];

and in its view it renders a list of items:

<item *ngFor="let item of items" [item]="item"></item>

the item component looks like this:

@Component({
  selector: "item",
  template: `

      {{ item.name }}, {{ item.age }}
      <input type="checkbox" />

  `
})
export class ItemComponent {
  @Input() item: any;
}

I added that checkbox in the item component just to notice when the component is fully re-rendered.

So what I do is tick the checkboxes and increment the age for each user in the state.

If I increment it by mutating the state the view is updated as expected and the checkboxes remain checked:

this.items.forEach(item => {
  item.age++;
});

But if I change the age without directly mutating the state the entire list is re-rendered and the checkbox is not checked anymore:

this.items = this.items.map(item => ({
  ...item,
  age: item.age + 1
}));

Here's a full example in a CodeSandbox.

Can anyone please explain why is this happening and how can I make the list to not fully re-render when I don't mutate the state?

Body:
NgForOf directive which Angular uses to render list of items checks if there are any changes in array we pass to it.

If you mutate property in items then Angular knows that there is no changes since references to objects in array remain the same.

On the other hand, if you completely replace the previous object with new one then it is signal for ngForOf to rerender that object.

To determine if an object changes ngForOf directive use DefaultIterableDiffer that looks at trackByFn function if we provided it. If we don't provide it then the default function looks like:

var trackByIdentity = function (index, item) {
  return item;
};

And then Angular compares result of this function with previous value in collection.

You can think about trackByFn like key in React.

So your solution might look like:

*ngFor="let item of items; trackBy: trackByFn"

trackByFn(i) {
    return i;
}

https://codesandbox.io/s/angular-67vo6


问:
Disable a Button
I want to disable a button (UIButton) on iOS after it is clicked. I am new to developing for iOS but I think the equivalent code on objective - C is this:

```<code>button.enabled = NO;
</code>```

But I couldn't do that on swift.

答:
For those who Googled "disable a button" but may have more nuanced use cases:

Disable with visual effect: As others have said, this will prevent the button from being pressed and the system will automatically make it look disabled:

```<code>yourButton.isEnabled = false
</code>```

Disable without visual effect: Are you using a button in a case where it should look normal but not behave likes button by reacting to touches? Try this!

```<code>yourButton.userInteractionEnabled = false
</code>```

Hide without disabling: This approach hides the button without disabling it (invisible but can still be tapped):

```<code> yourButton.alpha = 0.0
</code>```

Remove: This will remove the view entirely:

```<code> yourButton.removeFromSuperView()
</code>```

Tap something behind a button: Have two buttons stacked and you want the top button to temporarily act like it's not there? If you won't need the top button again, remove it. If you will need it again, try condensing its height or width to 0!

Title: Disable a Button

Body:
I want to disable a button (UIButton) on iOS after it is clicked. I am new to developing for iOS but I think the equivalent code on objective - C is this:

button.enabled = NO;

But I couldn't do that on swift.

Body:
For those who Googled "disable a button" but may have more nuanced use cases:

Disable with visual effect: As others have said, this will prevent the button from being pressed and the system will automatically make it look disabled:

yourButton.isEnabled = false

Disable without visual effect: Are you using a button in a case where it should look normal but not behave likes button by reacting to touches? Try this!

yourButton.userInteractionEnabled = false

Hide without disabling: This approach hides the button without disabling it (invisible but can still be tapped):

 yourButton.alpha = 0.0

Remove: This will remove the view entirely:

 yourButton.removeFromSuperView()

Tap something behind a button: Have two buttons stacked and you want the top button to temporarily act like it's not there? If you won't need the top button again, remove it. If you will need it again, try condensing its height or width to 0!


问:
Can I check built-in type at runtime?
For example,

If I write:

```<code>char c = CHAR_MAX;
c++;
</code>```

Can I know if 'c++' results in int or char so I know for sure if its not an overflow?

答:
Can I know if 'c++' results in int or char

As per standard quote in L.F.'s answer, you can know that it results in char.

so I know for sure if its not an overflow?

You can know for sure that it is an overflow. On systems where char is a signed type, the behaviour of the program will be undefined as far as I can tell.

Can I check built-in type at runtime?

You cannot check built-in types at runtime, but you can check them already at compiletime. For example:

```<code>static_assert(std::is_same_v<decltype(c++), char>);
</code>```

when I say: signed char c = CHAR_MAX + 1 then CHAR_MAX + 1 becomes int result and then in is assigned to c which is implementation-defined.

Indeed. Except on exotic systems where sizeof(signed char) == sizeof(int) in which case there is no promotion, and the arithmetic causes overflow which is undefined behaviour.

And only until C++20. Since C++20, signed initialisation with unrepresentable value is defined by the standard.

Can I ever make signed char overflow?

Yes. Using the increment operator. As far as I can tell, the standard says nothing about promotion within the increment operator. However, this may be open to interpretation.

Title: Can I check built-in type at runtime?

Body:
For example,

If I write:

char c = CHAR_MAX;
c++;

Can I know if 'c++' results in int or char so I know for sure if its not an overflow?

Body:
Can I know if 'c++' results in int or char

As per standard quote in L.F.'s answer, you can know that it results in char.

so I know for sure if its not an overflow?

You can know for sure that it is an overflow. On systems where char is a signed type, the behaviour of the program will be undefined as far as I can tell.

Can I check built-in type at runtime?

You cannot check built-in types at runtime, but you can check them already at compiletime. For example:

static_assert(std::is_same_v<decltype(c++), char>);

when I say: signed char c = CHAR_MAX + 1 then CHAR_MAX + 1 becomes int result and then in is assigned to c which is implementation-defined.

Indeed. Except on exotic systems where sizeof(signed char) == sizeof(int) in which case there is no promotion, and the arithmetic causes overflow which is undefined behaviour.

And only until C++20. Since C++20, signed initialisation with unrepresentable value is defined by the standard.

Can I ever make signed char overflow?

Yes. Using the increment operator. As far as I can tell, the standard says nothing about promotion within the increment operator. However, this may be open to interpretation.


问:
Basic rename statements's unusal behaviour in c
I am working on a inventory management project in c. In the project I need to delete records.

I have found out that to do this delete record work I have to search the specific record and write the other records to a temp file and the rename it to the original filename just after deleting the original file. But in my project code somehow the rename statement is skipping.

This is my project code:

```<code>#include<stdio.h>
#include <string.h>
#include <stdlib.h>
#include<inttypes.h>
#include<windows.h>
struct record_stu
{
    unsigned long long int id;
    int gm;
    char subject[255],s[255],y[255];

};
main()
{
    struct record_stu st;
    FILE *fp,*fp_tmp;
    char c,subject[255],year[255],semester[255];
    unsigned long long int id;
    int gm,j,z;
    int records=0;
    const char* charString1 = "Student_ID";
    const char* charString2 = "Subject";
    const char* charString3 = "Year";
    const char* charString4 = "Semester";
    const char* charString5 = "Gained_Marks";
    const char* charString6 = "Yes";
    const char* charString7 = "No";
    //const char* charString8 = "CSE-4year1.dat";

    fp = fopen("CSE-4Year1.dat","r");
    if(!(fp))
    {
      printf("An Error has occurred.Department can't be Found\n");
    }
    else
    {
      printf("Department Found.\n");
      printf("Select a Specific Record to Delete!");
      printf("\nEnter Student ID\n");
      scanf("%"PRIu64"",&id);
      printf("\nEnter subject\n");
      scanf("%s",subject);
      printf("\nEnter Year\n");
      scanf("%s",year);
      printf("\nEnter Semester\n");
      scanf("%s",semester);
      printf("%s\t%s\t%s\t%s\t%s\n",charString1,charString2,charString3,charString4,charString5);
      rewind(fp);
      while (!feof(fp))
      {
        fscanf(fp,"%11"PRIu64"\t%3s\t%3s\t%3s\t%10d", &st.id, &st.subject, &st.y, &st.s,&st.gm);
        records++;
        fp_tmp = fopen("temp.dat","a");
        if(st.id==id)
        {
          if(strcmp(st.subject,subject)==0)
          {
            if(strcmp(st.y,year)==0)
            {
              if(strcmp(st.s,semester)==0)
              {
                printf("%11"PRIu64"\t%3s\t%3s\t%3s\t%10d\n", st.id,st.subject, st.y, st.s, st.gm);
                printf("Are Sure You Want This Record to be Deleted?(Yes(1)/No(2))\n");
                scanf("%d",&z);
                if(z==1)
                {
                  printf("%11"PRIu64"\t%3s\t%3s\t%3s\t%10d\n", st.id,st.subject, st.y, st.s, st.gm);
                }
                else if(z==2)
                {
                  break;
                }
                else
                {
                  printf("Wrong Input.Pleas check case of your input.\n");
                  break;
                }
              }
            }
          }
         }
         else
         {
           fprintf(fp_tmp,"%11"PRIu64"\t%3s\t%3s\t%3s\t%10d\n", st.id, st.subject, st.y, st.s,st.gm);
         }
        }
       }
       fclose(fp);
       fclose(fp_tmp);
       remove("CSE-4Year1.dat");
       if (rename("temp.dat","CSE-4Year1.dat") == 0)
       printf("Renamed successfully");
       else
       printf("Unable to rename the file");
       break;
</code>```

The funny thing is I have a small code to rename that's working fine. Although the small code and project code has basically the same syntax.

The small code is here:

```<code>#include<stdio.h>
main()
{
 //remove("b.txt");
 rename("temp.dat","CSE-4Year1.dat");
}
</code>```

答:
Here is the complete code. The renaming problem is gone. The renaming problem occurs if the the file is open or doesn't exists in the directory.</p>

```<code>#include<stdio.h>
#include <string.h>
#include <stdlib.h>
#include<inttypes.h>
#include<windows.h>

//Variable Declarations
struct record_stu st;
FILE *fp,*fp_tmp,*fp1,*f,*f1;
unsigned long long int id;
char Selected_Exam[255],subject[255],Exam[255],year[255];
char semester[255],Dept_name[255],username[55],username_log[55], pass1[8];
char pass2[8],pasword[10],usrname[10],ch,pasword1[10];
char usrname1[10],Course_Code[255],ss[255],s1[255] = "";
char s2[255] = "",Gained_Letter_Grade[255],filename,lg,ct[255],cc[255],ct1[255];
int Course_Code_Number,i,gm,j=0,z,n=0,i,cs=0;
int flag=0,records=0,x[12],Dept_code,Gained_Mark,p=0;
float Gained_Grade_Point,Credit_Completed,gp,cd,tgp=0,tcd=0,cgpa=0,sgpa,pgp,ccr;

const char* charString1 = "Exam";
const char* charString2 = "Student_ID";
const char* charString3 = "Department Name";
const char* charString4 = "Course Code";
const char* charString5 = "Year";
const char* charString6 = "Semester";
const char* charString7 = "Letter Grade";
const char* charString8 = "Gained Mark";
const char* charString9 = "Grade Point";
const char* charString10 = "Credit Completed";
const char* charString11 = "Course Title";
const char* charString12 = "Yes";
const char* charString13 = "No";

struct record_stu
{
 unsigned long long int id;
 float sgpa;
 int gm;
 float gp,cd,ccr;
 char Exam[255],subject[255],semester[255],year[255];
 char Dept_name[255],Exam1[255],lg[255],ct[255],cc[255],ct1[255];
};
//Variable Declarations
main()
{
 //File open command
 fp = fopen("Student - Copy.txt","r");
 fp_tmp = fopen("temp.txt","w");
 //File Open Command

 if(!(fp)) //File Open Error Detection
 {
   printf("An Error has occurred.File can't be Found\n");
 }
 else //Searching for the record to delete
 {
   fclose(fp_tmp);
   fclose(fp);
   printf("File Found.\n");
   rewind(fp);
   printf("\nEnter Student ID: ");
   scanf("%"PRIu64"",&id);
   printf("\nEnter Course Code:");
   scanf("%s",subject);

   fp = fopen("Student - Copy.txt","r");
   fp_tmp = fopen("temp.txt","w");
   while (fscanf(fp,"%s %"PRIu64"%s%s%s%s%s%d%f%f%s\n",st.Exam1,&st.id,st.Dept_name,st.subject,st.year,st.semester,&st.lg,&st.gm,&st.gp,&ccr,&st.ct1) != EOF)
      {
        records++;
        if(st.id==id && strcmp(st.subject,subject)==0)
        {
          printf("Do you want to delete the record?(Yes(1)/No(2))\nEnter Your Choice: ");
          scanf("%d",&z);
          printf("Confirmation Code = %d\n",z);
          if(z==1)
          {
             printf("Do you want to confirm deletion of the record?(Yes(1)/No(2))\nEnter Your Choice: ");
              scanf("%d",&p);
          }
        }
        else
        {
             fprintf(fp_tmp,"%s %11"PRIu64"\t%s\t%s\t%3s\t%3s\t%s\t%d\t%3.2f\t%f\t%s\n",st.Exam1,st.id,st.Dept_name,st.subject,st.year,st.semester,st.lg,st.gm,st.gp,ccr,st.ct1);
        }
        }

    }//Searching for the record to delete

    //Actual Delete operation by renaming the temporary file to the source file name
    if(p==1)
    {
        printf("Confirmation Code = %d\n",p);
        fclose(fp_tmp);
        fclose(fp);
        remove("Student - Copy.txt");
        if(rename("temp.txt","Student - Copy.txt")==0)
            printf("Delete Successful");
    }
    else
    {
        fclose(fp_tmp);
        fclose(fp);
        printf("Delete Unsuccessful");
        remove("temp.txt");
    }
    //Actual Delete operation by renaming the temporary file to the source file name
}
</code>```

Body:
I am working on a inventory management project in c. In the project I need to delete records.

I have found out that to do this delete record work I have to search the specific record and write the other records to a temp file and the rename it to the original filename just after deleting the original file. But in my project code somehow the rename statement is skipping.

This is my project code:

#include<stdio.h>
#include <string.h>
#include <stdlib.h>
#include<inttypes.h>
#include<windows.h>
struct record_stu
{
    unsigned long long int id;
    int gm;
    char subject[255],s[255],y[255];

};
main()
{
    struct record_stu st;
    FILE *fp,*fp_tmp;
    char c,subject[255],year[255],semester[255];
    unsigned long long int id;
    int gm,j,z;
    int records=0;
    const char* charString1 = "Student_ID";
    const char* charString2 = "Subject";
    const char* charString3 = "Year";
    const char* charString4 = "Semester";
    const char* charString5 = "Gained_Marks";
    const char* charString6 = "Yes";
    const char* charString7 = "No";
    //const char* charString8 = "CSE-4year1.dat";

    fp = fopen("CSE-4Year1.dat","r");
    if(!(fp))
    {
      printf("An Error has occurred.Department can't be Found\n");
    }
    else
    {
      printf("Department Found.\n");
      printf("Select a Specific Record to Delete!");
      printf("\nEnter Student ID\n");
      scanf("%"PRIu64"",&id);
      printf("\nEnter subject\n");
      scanf("%s",subject);
      printf("\nEnter Year\n");
      scanf("%s",year);
      printf("\nEnter Semester\n");
      scanf("%s",semester);
      printf("%s\t%s\t%s\t%s\t%s\n",charString1,charString2,charString3,charString4,charString5);
      rewind(fp);
      while (!feof(fp))
      {
        fscanf(fp,"%11"PRIu64"\t%3s\t%3s\t%3s\t%10d", &st.id, &st.subject, &st.y, &st.s,&st.gm);
        records++;
        fp_tmp = fopen("temp.dat","a");
        if(st.id==id)
        {
          if(strcmp(st.subject,subject)==0)
          {
            if(strcmp(st.y,year)==0)
            {
              if(strcmp(st.s,semester)==0)
              {
                printf("%11"PRIu64"\t%3s\t%3s\t%3s\t%10d\n", st.id,st.subject, st.y, st.s, st.gm);
                printf("Are Sure You Want This Record to be Deleted?(Yes(1)/No(2))\n");
                scanf("%d",&z);
                if(z==1)
                {
                  printf("%11"PRIu64"\t%3s\t%3s\t%3s\t%10d\n", st.id,st.subject, st.y, st.s, st.gm);
                }
                else if(z==2)
                {
                  break;
                }
                else
                {
                  printf("Wrong Input.Pleas check case of your input.\n");
                  break;
                }
              }
            }
          }
         }
         else
         {
           fprintf(fp_tmp,"%11"PRIu64"\t%3s\t%3s\t%3s\t%10d\n", st.id, st.subject, st.y, st.s,st.gm);
         }
        }
       }
       fclose(fp);
       fclose(fp_tmp);
       remove("CSE-4Year1.dat");
       if (rename("temp.dat","CSE-4Year1.dat") == 0)
       printf("Renamed successfully");
       else
       printf("Unable to rename the file");
       break;

The funny thing is I have a small code to rename that's working fine. Although the small code and project code has basically the same syntax.

The small code is here:

#include<stdio.h>
main()
{
 //remove("b.txt");
 rename("temp.dat","CSE-4Year1.dat");
}

Body:
Here is the complete code. The renaming problem is gone. The renaming problem occurs if the the file is open or doesn't exists in the directory.

#include<stdio.h>
#include <string.h>
#include <stdlib.h>
#include<inttypes.h>
#include<windows.h>

//Variable Declarations
struct record_stu st;
FILE *fp,*fp_tmp,*fp1,*f,*f1;
unsigned long long int id;
char Selected_Exam[255],subject[255],Exam[255],year[255];
char semester[255],Dept_name[255],username[55],username_log[55], pass1[8];
char pass2[8],pasword[10],usrname[10],ch,pasword1[10];
char usrname1[10],Course_Code[255],ss[255],s1[255] = "";
char s2[255] = "",Gained_Letter_Grade[255],filename,lg,ct[255],cc[255],ct1[255];
int Course_Code_Number,i,gm,j=0,z,n=0,i,cs=0;
int flag=0,records=0,x[12],Dept_code,Gained_Mark,p=0;
float Gained_Grade_Point,Credit_Completed,gp,cd,tgp=0,tcd=0,cgpa=0,sgpa,pgp,ccr;

const char* charString1 = "Exam";
const char* charString2 = "Student_ID";
const char* charString3 = "Department Name";
const char* charString4 = "Course Code";
const char* charString5 = "Year";
const char* charString6 = "Semester";
const char* charString7 = "Letter Grade";
const char* charString8 = "Gained Mark";
const char* charString9 = "Grade Point";
const char* charString10 = "Credit Completed";
const char* charString11 = "Course Title";
const char* charString12 = "Yes";
const char* charString13 = "No";

struct record_stu
{
 unsigned long long int id;
 float sgpa;
 int gm;
 float gp,cd,ccr;
 char Exam[255],subject[255],semester[255],year[255];
 char Dept_name[255],Exam1[255],lg[255],ct[255],cc[255],ct1[255];
};
//Variable Declarations
main()
{
 //File open command
 fp = fopen("Student - Copy.txt","r");
 fp_tmp = fopen("temp.txt","w");
 //File Open Command

 if(!(fp)) //File Open Error Detection
 {
   printf("An Error has occurred.File can't be Found\n");
 }
 else //Searching for the record to delete
 {
   fclose(fp_tmp);
   fclose(fp);
   printf("File Found.\n");
   rewind(fp);
   printf("\nEnter Student ID: ");
   scanf("%"PRIu64"",&id);
   printf("\nEnter Course Code:");
   scanf("%s",subject);

   fp = fopen("Student - Copy.txt","r");
   fp_tmp = fopen("temp.txt","w");
   while (fscanf(fp,"%s %"PRIu64"%s%s%s%s%s%d%f%f%s\n",st.Exam1,&st.id,st.Dept_name,st.subject,st.year,st.semester,&st.lg,&st.gm,&st.gp,&ccr,&st.ct1) != EOF)
      {
        records++;
        if(st.id==id && strcmp(st.subject,subject)==0)
        {
          printf("Do you want to delete the record?(Yes(1)/No(2))\nEnter Your Choice: ");
          scanf("%d",&z);
          printf("Confirmation Code = %d\n",z);
          if(z==1)
          {
             printf("Do you want to confirm deletion of the record?(Yes(1)/No(2))\nEnter Your Choice: ");
              scanf("%d",&p);
          }
        }
        else
        {
             fprintf(fp_tmp,"%s %11"PRIu64"\t%s\t%s\t%3s\t%3s\t%s\t%d\t%3.2f\t%f\t%s\n",st.Exam1,st.id,st.Dept_name,st.subject,st.year,st.semester,st.lg,st.gm,st.gp,ccr,st.ct1);
        }
        }

    }//Searching for the record to delete

    //Actual Delete operation by renaming the temporary file to the source file name
    if(p==1)
    {
        printf("Confirmation Code = %d\n",p);
        fclose(fp_tmp);
        fclose(fp);
        remove("Student - Copy.txt");
        if(rename("temp.txt","Student - Copy.txt")==0)
            printf("Delete Successful");
    }
    else
    {
        fclose(fp_tmp);
        fclose(fp);
        printf("Delete Unsuccessful");
        remove("temp.txt");
    }
    //Actual Delete operation by renaming the temporary file to the source file name
}


问:
How to pass value in input tag?
normally, i am trying passing value in p,div and pre tag and values are show in above tag now i am passing country name in input tag. but value are not show in input tag. Here is my code:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Get browser and ip address </title>
</head>
<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>
<input type="text" name="country_name" id="country_name" value="">
<p id="country_name"></p>
<div id="ip"></div>
<div id="city"></div>
<pre id="response">```

```

Thanks.

答:
Only one item can have a specific id. Try using classes if you want them to share something.
Since both the
 and  have the same id it will not work
Note that you can getElementSByClassName but you can only getElementById with the class allowing multiple and ID only allowing for one

Title: How to pass value in input tag?

Body:
normally, i am trying passing value in p,div and pre tag and values are show in above tag now i am passing country name in input tag. but value are not show in input tag. Here is my code:

<!DOCTYPE html>

    <title>Get browser and ip address </title>

ipdata.co - IP geolocation API

<input type="text" name="country_name" id="country_name" value="">

Thanks.


问:
shuffle card deck issues in language agnostic
Not so long ago I was in an interview, that required solving two very interesting problems. I'm curious how would you approach the solutions.

Problem 1 :

Product of everything except current

Write a function that takes as input two integer arrays of length len, input and index, and generates a third array, result, such that:
result[i] = product of everything in input except input[index[i]]

For instance, if the function is called with len=4, input={2,3,4,5}, and index={1,3,2,0}, then result will be set to {40,24,30,60}.

IMPORTANT: Your algorithm must run in linear time.

Problem 2 : ( the topic was in one of Jeff posts )

Shuffle card deck evenly

Design (either in C++ or in C#) a class Deck to represent an ordered deck of cards, where a deck contains 52 cards, divided in 13 ranks (A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K) of the four suits: spades (?), hearts (?), diamonds (?) and clubs (?).

Based on this class, devise and implement an efficient algorithm to shuffle a deck of cards. The cards must be evenly shuffled, that is, every card in the original deck must have the same probability to end up in any possible position in the shuffled deck.
The algorithm should be implemented in a method shuffle() of the class Deck:
void shuffle()

What is the complexity of your algorithm (as a function of the number n of cards in the deck)?

Explain how you would test that the cards are evenly shuffled by your method (black box testing).

P.S. I had two hours to code the solutions

答:
Tnilsson, I agree that YXJuLnphcnQ solution is arguably faster, but the idee is the same. I forgot to add, that the language is optional in the first problem, as well as int the second.

You're right, that calculationg zeroes, and the product int the same loop is better. Maybe that was the thing.

OwnerDisplayName: Kociub

LastEditorDisplayName: John Nolan

ContentLicense: CC BY-SA 2.5


问:
Quicksort with Python
I am totally new to python and I am trying to implement quicksort in it.
Could someone please help me complete my code?

I do not know how to concatenate the three arrays and print them.

```<code>def sort(array=[12,4,5,6,7,3,1,15]):
    less = []
    equal = []
    greater = []

    if len(array) > 1:
        pivot = array[0]
        for x in array:
            if x < pivot:
                less.append(x)
            if x == pivot:
                equal.append(x)
            if x > pivot:
                greater.append(x)
            sort(less)
            sort(pivot)
            sort(greater)
</code>```

答:
Easy implementation from grokking algorithms</p>

```<code>def quicksort(arr):
    if len(arr) < 2:
        return arr #base case
    else:
        pivot = arr[0]
        less = [i for i in arr[1:] if i <= pivot]
        more = [i for i in arr[1:] if i > pivot]
        return quicksort(less) + [pivot] + quicksort(more)
</code>```

Title: Quicksort with Python

Body:
I am totally new to python and I am trying to implement quicksort in it.
Could someone please help me complete my code?

I do not know how to concatenate the three arrays and print them.

def sort(array=[12,4,5,6,7,3,1,15]):
    less = []
    equal = []
    greater = []

    if len(array) > 1:
        pivot = array[0]
        for x in array:
            if x < pivot:
                less.append(x)
            if x == pivot:
                equal.append(x)
            if x > pivot:
                greater.append(x)
            sort(less)
            sort(pivot)
            sort(greater)

Body:
Easy implementation from grokking algorithms

def quicksort(arr):
    if len(arr) < 2:
        return arr #base case
    else:
        pivot = arr[0]
        less = [i for i in arr[1:] if i <= pivot]
        more = [i for i in arr[1:] if i > pivot]
        return quicksort(less) + [pivot] + quicksort(more)


问:
How do I pass a variable defined as (Entry.get()) from one function to another?
How do I pass the (Answer) variable from creatLabels function to check function?

def createLabels(Ques):

    AnswerINP = Entry(root)

    AnswerINP.grid(column=3, sticky=W )

    Answer = AnswerINP.get()

    Checkbutton = tk.Button(root, text="CHECK", command= check)

    Checkbutton.grid()

def check ():

       r=requests.get('https://opentdb.com/api.phpamount='+TextINP1.get()+'&difficul)
        res = r.json ()

        for data in res ['results']:

                if Answer.title()== data["correct_answer"]:

                        print("Correct")
```

I get that variable Answer is not defined when I write it in this way

答:
You can pass a variable to your check function with the use of a Lambda Expression. Lambda expressions are basically one line, anonymous(unnamed), functions.

To do this you just have to change you Checkbuttons command option to a lambda expression, as well as add the argument to your check(), function like so:

def createLabels(Ques):
    AnswerINP = Entry(root)
    AnswerINP.grid(column=3, sticky=W )
    Answer = AnswerINP.get()

    Checkbutton = tk.Button(root, text="CHECK", command=lambda a=Answer: check(a))

    Checkbutton.grid()

def check (answer):
    ...
```

This should give you the outcome you want.

Body:
How do I pass the (Answer) variable from creatLabels function to check function?

def createLabels(Ques):

    AnswerINP = Entry(root)

    AnswerINP.grid(column=3, sticky=W )

    Answer = AnswerINP.get()

    Checkbutton = tk.Button(root, text="CHECK", command= check)

    Checkbutton.grid()

def check ():

       r=requests.get('https://opentdb.com/api.phpamount='+TextINP1.get()+'&difficul)
        res = r.json ()

        for data in res ['results']:

                if Answer.title()== data["correct_answer"]:

                        print("Correct")

I get that variable Answer is not defined when I write it in this way

Body:
You can pass a variable to your check function with the use of a Lambda Expression. Lambda expressions are basically one line, anonymous(unnamed), functions.

To do this you just have to change you Checkbuttons command option to a lambda expression, as well as add the argument to your check(), function like so:

def createLabels(Ques):
    AnswerINP = Entry(root)
    AnswerINP.grid(column=3, sticky=W )
    Answer = AnswerINP.get()

    Checkbutton = tk.Button(root, text="CHECK", command=lambda a=Answer: check(a))

    Checkbutton.grid()

def check (answer):
    ...

This should give you the outcome you want.


问:
WordPress navbar links wont work after i migrated from localhost to a live server
I migrated my WordPress site from localhost to a live server and my navigation links don't work.

I have tried the velvet blues update url plugin and nothing has changed.

I also can't find the .htaccess file on my server in the file manager. My links keep redirect me to localhost rather than the live site.

How do I update all of my localhost URLs to point to the live URLs?

答:
I've had such a problem before and now use Duplicator plugin for migration. If you migrated manually, then go to your online database (once imported) table wp_options and change the links to your new domain.

You can reveal the .htaccess file from your cPanel settings as below
setings change

Go to File Manager (Files Section)

Click the top-right Settings button.

Then on the Preferences window, check the option Show Hidden Files (dotfiles)

Confirm the action by clicking the Save button.

Now you will see all hidden files (including .htaccess files) in File Manager.

Hope this helps