text:
Q: python import a method that depends on a imported class So if I have 2 files that look like this:
File 1
import class1
import method1

def method2(something):
    result = method1(classname=class1)

File 2
def method1(classname):
    some_result = classname.resultfinder
    return some_result

Will this work?
I mean, since I am not importing class1 in the file where method1 lives, but method1 still ends up using class1.
Will method1 have access to class1 via the import made in File 1 where method 1 is imported to?

A: What happened when you tried it?
Note that your import of method1 is wrong. Apart from that --- yes, you do not need to import everything. Do you think the standard library imports your stuff whenever you use it? ;-)

A: I think that should be fine - imagine having to import every possible type that could be passed to a function at runtime.  I don't think a "dynamic" language like that would last very long.

A: It doesn't quite look right--you don't exactly "import class1", you more import a module (in a file) that contains class1, or a module that contains method1. So I'd expect to see more like
from file2 import method1
from file3 import class1

Also, method1 doesn't so much take a class name as a class object. Or should that be a class instance object? Sorry if I'm being picky, but hopefully it's educational to consider the distinction.


text:
Q: Validation failed: Password digest can't be blank I have seen other threads with similar problems but they don't seem to fix my problem. I am following along with with the tutorial on http://ruby.railstutorial.org/ to get a basic user sign up and login or a different project then that sample one.
Basically when I run rspec I keep getting this error. I have run all my migrations and test prepare. Really stumped with this.
1) User should reject duplicate email addresses
 Failure/Error: User.create!(@attr)
 ActiveRecord::RecordInvalid:
   Validation failed: Password digest can't be blank, Password can't be blank, Password is too short (minimum is 6 characters), Password confirmation can't be blank
 # ./spec/models/user_spec.rb:60:in `block (2 levels) in <top (required)>'

2) User should accept valid email addresses
 Failure/Error: valid_email_user.should be_valid end
   expected #<User id: nil, name: "Example User", email: "user@foo.com", created_at: nil, updated_at: nil, password_digest: nil> to be valid, but got errors: Password digest can't be blank, Password can't be blank, Password is too short (minimum is 6 characters), Password confirmation can't be blank
 # ./spec/models/user_spec.rb:48:in `block (3 levels) in <top (required)>'
 # ./spec/models/user_spec.rb:46:in `each'
 # ./spec/models/user_spec.rb:46:in `block (2 levels) in <top (required)>'

3) User should create a new instance given valid attributes
 Failure/Error: User.create!(@attr)
 ActiveRecord::RecordInvalid:
   Validation failed: Password digest can't be blank, Password can't be blank, Password is too short (minimum is 6 characters), Password confirmation can't be blank
 # ./spec/models/user_spec.rb:25:in `block (2 levels) in <top (required)>'

4) User should reject email addresses identical up to case
 Failure/Error: User.create!(@attr.merge(:email => upcased_email))
 ActiveRecord::RecordInvalid:
   Validation failed: Password digest can't be blank, Password can't be blank, Password is too short (minimum is 6 characters), Password confirmation can't be blank
 # ./spec/models/user_spec.rb:67:in `block (2 levels) in <top (required)>'

Here is my user_spec
require 'spec_helper'

describe User do
  before(:each) do
    @attr = { :name => "Example User", :email => "user@example.com" }
  end

  before do
    @user = User.new(name: "Example User", email: "user@example.com",
                     password: "foobar", password_confirmation: "foobar")
  end

  subject { @user }

  it { should respond_to(:name) }
  it { should respond_to(:email) }
  it { should respond_to(:password_digest) }
  it { should respond_to(:password) }
  it { should respond_to(:password_confirmation) }
  it { should respond_to(:authenticate) }

  it { should be_valid }

  it "should create a new instance given valid attributes" do
    User.create!(@attr)
  end

  it "should require a name"  do
    no_name_user = User.new(@attr.merge(:name => ""))
    no_name_user.should_not be_valid
  end

  it "should require an email address" do
    no_email_user = User.new(@attr.merge(:email => ""))
    no_email_user.should_not be_valid
  end

  it "should reject names that are too long" do
    long_name = "a" * 51
    long_name_user = User.new(@attr.merge(:name => long_name))
    long_name_user.should_not be_valid
  end

  it "should accept valid email addresses" do
    addresses = %w[user@foo.com THE_USER@foo.bar.org first.last@foo.jp]
    addresses.each do |address|
      valid_email_user = User.new(@attr.merge(:email => address))
      valid_email_user.should be_valid end
  end

  it "should reject invalid email addresses" do
    addresses = %w[user@foo,com user_at_foo.org example.user@foo.]
    addresses.each do |address|
      invalid_email_user = User.new(@attr.merge(:email => address))
      invalid_email_user.should_not be_valid end
  end

  it "should reject duplicate email addresses" do
    # Put a user with given email address into the database.
    User.create!(@attr)
    user_with_duplicate_email = User.new(@attr)
    user_with_duplicate_email.should_not be_valid
  end

  it "should reject email addresses identical up to case" do
    upcased_email = @attr[:email].upcase
    User.create!(@attr.merge(:email => upcased_email))
    user_with_duplicate_email = User.new(@attr)
    user_with_duplicate_email.should_not be_valid
  end

  describe "when password is not present" do
    before { @user.password = @user.password_confirmation = " " }
    it { should_not be_valid }
  end

  describe "when password doesn't match confirmation" do
    before { @user.password_confirmation = "mismatch" }
    it { should_not be_valid }
  end

  describe "when password confirmation is nil" do
    before { @user.password_confirmation = nil }
    it { should_not be_valid }
  end

  describe "with a password that's too short" do
    before { @user.password = @user.password_confirmation = "a" * 5 }
    it { should be_invalid }
  end

  describe "return value of authenticate method" do
    before { @user.save }
    let(:found_user) { User.find_by_email(@user.email) }

    describe "with valid password" do
      it { should == found_user.authenticate(@user.password) }
    end

    describe "with invalid password" do
      let(:user_for_invalid_password) { found_user.authenticate("invalid") }

      it { should_not == user_for_invalid_password }
      specify { user_for_invalid_password.should be_false }
    end
  end

end

here is my user model
class User < ActiveRecord::Base

  attr_accessible :name, :email, :password, :password_confirmation
  has_secure_password

  before_save { |user| user.email = email.downcase }

  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence:   true,
            format:     { with: VALID_EMAIL_REGEX },
            uniqueness: { case_sensitive: false }
  validates :password, presence: true, length: { minimum: 6 }
  validates :password_confirmation, presence: true
end

A: your validation is broken too, a password and password_confirmation should be required if the user is created but not thereafter
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true

you will run into problems if you try to update the user later on, say changing its Name, because then it will check for both password and password_confirmation but the user already has a password set stored usually in the password_digist field encrypted by bcrypt but not stored along with password and confirmation in plain text.
I recommend this only to be validated for new records:
validates :password, presence: true, length: { minimum: 6 } if new?
validates :password_confirmation, presence: true if new?

A: In all the failing tests, you use @attr = { :name => "Example User", :email => "user@example.com" } to create a new user. But to create a new user, you MUST set password and password_confirmation. Add these attributes to the @attr hash. The password_digest field should then be set automatically and it should be possible to save the user.

A: delete this line
attr_accessible :name, :email, :password, :password_confirmation

It should work now.
This preventes the method rails method password= from being called. (also see secure_password.rb)

redpajama_set_name: RedPajamaStackExchange


text:
Q: c++ how to create public and protected accessors to same member In case I have two methods - one public, one protected that return the reference to same member, I get following compilation error:
'Server::getManager': cannot access protected member declared in class 'Server'

When I comment out protected function, code works. Could you please advise why this is happening?  Why the compiler cannot find the public function to same member?
class Manager
    {
    };

class Server
{
public:
    const Manager & getManager() const { return m_man; }
protected:
    Manager & getManager() { return m_man;  } // <-- after removing this method I get no compilation error

private:

    Manager m_man;
};

int main()
{

    Server s;
    const Manager& m = s.getManager();
    return 0;
}

A:
Why the compiler cannot find the public function to same member?

That's not the issue. The compiler finds both functions and performs overload resolution to determine which is the best viable candidate. The two candidates are:
Manager&       getManager()        // protected
Manager const& getManager() const  // public

For member functions, there is an implicit first object parameter that is the instance of the class itself. In this case, the two functions become:
getManager(Server& )         // protected
getManager(Server const& )   // public

We're invoking it on an object (s) that is not const. Both candidates are viable, but the public candidate takes a reference to a more cv-qualified object than the protected candidate - so it's less preferred. The standardese is in [over.ics.rank]:

Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence
  S2 if
  — S1 and S2 are reference bindings (8.5.3), and the types to which the references refer are the same
  type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers
  is more cv-qualified than the type to which the reference initialized by S1 refers.

As a result, the protected candidate is preferred - so that's the one that's called.
Unfortunately, it's protected, so calling it is ill-formed. The access control is checked after overload resolution. So you'll have to restructure your program somehow. You could simply cast s to const:
const Manager& m = const_cast<Server const&>(s).getManager();

This would make the protected candidate non-viable.


text:
Q: при нажатии на елемент, activom появлялось сразу два Доброго времени суток. У нас есть форма, с двумя инпутами, и нужно чтобы при нажатии на кнопку поиска появлялся второй инпут с полем ввода текста. Т.е. первый инпут мы выделяем фокусом, он меняется, и нужно чтобы еще одновременно менялся и второй.  Подскажите, пожалуйста, как такое сделать?

.search_form>input:nth-child(1) {
  width: 52px;
  height: 52px;
  background: url(../images/search.png) no-repeat center top 2px;
  display: inline-block;
  border: none;
  outline: none;
  float: right;
  cursor: pointer;
  margin: 33px 53px 0 0;
}

.search_form>input:focus {
  width: 52px;
  height: 52px;
  background: url(../images/search.png) #535353 no-repeat center;
  padding: 0;
  margin: 24px 53px 24px 0;
}
`
<form class="search_form" method="get">
  <input type="submit" name="request" value="">
  <input type="search" name="#" value="" placeholder="Найти информацию ...">
</form>`

A: стили думаю сами исправите

var input = document.querySelector('input');

input.addEventListener('click', function(event) {
  event = event || window.event;
  if (event.offsetX < 51) {
    input.value = '';
  }

})
input.addEventListener('input', function(event) {
  if (input.value !== '') {
    document.querySelector('button').className = 'button';
  }
})
input.addEventListener('mousemove', function(event) {
  event = event || window.event;
  if (event.offsetX < 51) {
    input.style.cursor = 'pointer';
  } else {
    input.style.cursor = 'text';
  }
})
@import "http://fonts.fontstorage.com/import/adventpro.css";
* {
  margin: 0;
  padding: 0;
}

html,
body {
  width: 100%;
  height: 100%;
  background-color: #065b79;
  overflow: auto;
}

input {
  position: absolute;
  top: 100px;
  left: 0px;
  height: 50px;
  width: 1px;
  padding-left: 55px;
  background-color: transparent;
  background-image: url(http://www.countryporch.com/icons/search.gif);
  background-repeat: no-repeat;
  outline: none;
  color: #fff;
  text-align: left;
  font-size: 35px;
  font-family: 'Advent';
  border: 0;
  border-bottom: 0 solid #fff;
  transition: all .4s;
}

input:focus {
  position: absolute;
  top: 100px;
  left: 100px;
  height: 50px;
  width: 400px;
  padding-left: 55px;
  background-color: grya;
  background-image: url(http://nouveal.com/wp-content/themes/html5blank-stable-nouveal/img/croix@2x.png);
  background-repeat: no-repeat;
  outline: none;
  color: #fff;
  text-align: left;
  font-size: 35px;
  font-family: 'Advent';
  border: 0;
  border-bottom: .1px solid #fff;
  transition: all .4s;
}

input::placeholder {
  color: #fff;
  text-align: center;
}

button {
  opacity: 0;
  position: absolute;
  top: 100px;
  left: 500px;
  height: 50px;
  width: 150px;
  padding-left: 55px;
  background-color: grya;
  outline: none;
  color: #fff;
  text-align: left;
  font-size: 35px;
  font-family: 'Advent';
  border: 0;
  border-bottom: .1px solid #fff;
  transition: all .4s;
}

button.button {
  opacity: 1;
  position: absolute;
  top: 100px;
  left: 500px;
  height: 50px;
  width: 150px;
  padding-left: 55px;
  background-color: grya;
  outline: none;
  color: #fff;
  text-align: left;
  font-size: 35px;
  font-family: 'Advent';
  border: 0;
  border-bottom: .1px solid #fff;
  transition: all .4s;
}
`
<form class="search_form" method="get">
  <input type="text" name="#" value="" placeholder="Найти информацию ...">
  <button>Жми</button>
</form>`


text:
Q: Is there such a concept as "modular sets" and their properties? I have a question. Using the Chinese Remainder Theorem, it's easy to find the (lowest) solution to a series of modulus statements. For instance, given:
x mod 5 = 3.
x mod 7 = 2.
x mod 11 = 9.
the solution (163) is fairly straightforward to find. However, suppose rather than one set of possibilities, we have a group, such as:
x mod 11 = 2,3,4,7,9, or 10.
x mod 13 = 0,1,6,7,8, or 9.
x mod 17 = 4,5,6,9,10, or 12.
x mod 19 = 2,4,6,10,14, or 16.
The set of solutions has 6*6*6*6 = 1,296 members, but I can't find anything about these types of sets. Do they have a name, or is much known about them? (For instance, if I wanted to find the lowest member of the set, or the two closest members, is an efficient way of doing so known?)


text:
Q: Is it possible to run ios apps developed using react-native in linux to real iphone I am having a react-native app. I would like to generate an iOS app from my linux/windows machine. Is it possbile? Some friends has suggested me about BuddyBuild. is there any alternative solutions for me?? I have the following physical devices

*

*Laptop running windows & linux (running node.js,python,java,npm,and lot more)

*iPhone 5S

*Internet Connection

A: Try Expo. It's built on top of React Native and it makes developing a lot easier because you can see what you code instantly on a real phone. You can send links to people or even use a QR code to share your projects as you work on them.
Expo


text:
Q: Issues setting up discord oauth in ASP.NET Core MVC I am (currently) setting up OAuth2 for Discord with https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
and having troubles.
It functions well until I click 'authorize' in the authorization window of discord. It should supposedly return to my action with route discord-signin which is also defined in the bots OAuth2 settings. But it does not, instead it redirects without error to my Index-Action.
Here is what I define when adding the discord authentication in Program.cs
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie()
    .AddDiscord(o =>
    {
        o.ClientId = DiscordDefaults.ClientId;
        o.ClientSecret = DiscordDefaults.ClientSecret;
        o.CallbackPath = new PathString("/signin-discord");
        o.AuthorizationEndpoint = DiscordDefaults.AuthorizationEndpoint;
        o.TokenEndpoint = DiscordDefaults.TokenEndpoint;
        o.UserInformationEndpoint = DiscordDefaults.UserInformationEndpoint;
        o.Scope.Add("identify");

        o.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id", ClaimValueTypes.UInteger64);
        o.ClaimActions.MapJsonKey(ClaimTypes.Name, "username", ClaimValueTypes.String);
        o.ClaimActions.MapJsonKey(ClaimTypes.Email, "email", ClaimValueTypes.Email);
    });

And here is my controller:
public async Task<IActionResult> Index()
        {
            return View(await HttpContext.GetExternalProvidersAsync());
        }

        [HttpPost("~/signin")]
        public async Task<IActionResult> Index([FromForm] string provider)
        {
            // Note: the "provider" parameter corresponds to the external
            // authentication provider choosen by the user agent.
            if (string.IsNullOrWhiteSpace(provider))
            {
                return BadRequest();
            }

            if (!await HttpContext.IsProviderSupportedAsync(provider))
            {
                return BadRequest();
            }

            // Instruct the middleware corresponding to the requested external identity
            // provider to redirect the user agent to its own authorization endpoint.
            // Note: the authenticationScheme parameter must match the value configured in Startup.cs
            var challengeResult = Challenge(new AuthenticationProperties { RedirectUri = "/" }, provider);
            return challengeResult;
        }

        [Route("signin-discord")]
        public async Task<IActionResult> DiscordSignIn(string code)
        {
            Debug.WriteLine(code);
            return RedirectToAction(nameof(LoginSuccess));
        }

Any ideas why it fails?


text:
Q: How to factor out data layer in nopCommerce and replace MS SQL with RavenDB? I am new to nopCommerce and ecommerce in general but I am involved in an ecommerce project. Now from my past experiences with RavenDB (which mostly were absolutely pleasant) and based on the needs of the business (fast changes with awkward business workflows) It seemed to be an appealing option to have RavenDB handling all sort of things related to the database.
I do not understand design and architecture of nopCommerce fully so I did not reach to a conclusion on how to factor data parts, since it seems the services layer actually does not abstract data-layer concepts away; like bringing in EF working model to other layers.
I have found another project which used NuDB as it's database as a nopCommerce fork. But it did not help because NuDB still has the feeling of a RDBMS and is not as different as RavenDB.
Now first how can I learn about the internals of nopCommerce (other than investigating the code)? It's workflows? It's conventions?
Second has anyone tried something similar before with a NoSQL database (say like MongoDB or RavenDB)? Is it possible to achieve this in a 1 (~2) month time frame?
Thanks in advance;

A: I have worked with both, and while it is possible it is certainly not recommended.
Systems that are designed around relational databases rarely can just be converted directly over to non-relational databases.  There are many different patterns to use in order to achieve efficiency.
For example, in a relational database, you might have two tables that are joined with a one-to-many relationship, such as an Order and its OrderLineItems.  This is very common in relational database design.  However, it is completely undesired in a document database like RavenDB.  Instead, you would model an entire document with all of it's children as a single "Aggregate Root".  An Order and all of its OrderLineItems would be in one document.
Switching out storage engines via a repository interface may sound like a good idea, but in practice one usually finds it to be impractical.

A: Now first how can I learn about the internals of nopCommerce (other than investigating the code)? It's workflows? It's conventions?
Well, there's always the documentation, but there's really no better way than reading the source code. The nopCommerce source code is organized fairly well, so it shouldn't be too hard.
Second has anyone tried something similar before with a NoSQL database (say like MongoDB or RavenDB)? Is it possible to achieve this in a 1 (~2) month time frame?
I have not tried this, nor do I know anybody who has. However, just a cursory look at the code shows that the data access strategy is pretty strongly structured around the Repository pattern using Entity Framework.
http://www.nopcommerce.com/docs/71/source-code-organization-architecture-of-nopcommerce.aspx

The Nop.Data project contains a set of classes and functions for reading from and writing to a database or other data store. It helps separate data-access logic from your business objects. nopCommerce uses the Entity Framework (EF) Code-First approach. It allows you to define entities in the source code (all core entities are defined into Nop.Core project), and then get EF to generate the database from that. That's why it's called Code-First. You can then query your objects using LINQ, which gets translated to SQL behind the scenes and executed against the database.

I would say that converting to a NoSQL back-end would probably require some significant effort. There have been other SO posts discussing using RavenDb with the repository pattern. Can it be done? Sure. Can it be done in a month or two? Maybe, but it's impossible to say without knowing a lot of your specific situation's details.

A: I've tried both MongoDB and RavenDB for NopCommerce's DB. However, as Matt said, it's not a good idea. Here are some reasons:

*

*The shortest way is repository pattern, an anti-fan of RavenDB. It took me about 2 weeks.

*The search function of Nop is optimized for SQL. Raven can do it better and more beautiful, but you must change many methods of Nop.

*All paging and sorting functions will be rewritten.
To change the data layer, you'll have to change a half of the business layer, too!

A: Whoa, slow down, you never just swap out a database. That is extremely risky especially if the database is already in production. And converting from relational to nosql can be time consuming as things won't match up exactly. Your reason seems to be that you prefer the one you are used to which is a horribly invalid reason for the amount of risk you are taking by converting the database.
Nor is this a question for strangers on the Internet, if you propose to do such a thing, your business leaders need to know in advance and with much discussion as to the time and the risk and the benefits. It is NOT your call, it is a management decision.
But further, you will need to determine if you need to convert existing data and look for any existing other things which might use the database backend besides your application such as reporting applications or data imports. It might even be set up specifically to follow rules which are required by auditors or credit card processors and which may preclude teh use of nosql.
I wouldn't even want to take on converting an Oracle database to SQl server or vice versa without at least a year in the project plan let alone convert from relational to nonrelational.
However, consider that new functionality could use the nosql approach if it is approved in advance, for things that cannot easily be defined in advance.  There is no rule that a project can't use both nosql when appropriate and relational when appropriate.


text:
Q: Simple HTML directory/index.html issue I feel like a baby for having to do this but bear with me.  I'm trying to set up webpage structures on my desktop in a folder.  It's got an index.html and a couple folders of its own.  One folder, "research", has its own index.html.  I'm trying to link to this page from the higher index.html with  but instead of taking me to research/index.html it takes me to a 'file-directory view' (for lack of knowing what to call it) of the directory research/
Clearly I could fix this by doing  but that's annoying.  Thoughts?

A: if you want to browse locally, you will have to include the file name. in other words:
research

The reason it works on remote servers is because replacement is done by the web server so if you want research/ to work then you will need a local web server such as wamp on windows or mamp on mac.


text:
Q: What do 'no_text' and '500' mean as a response code to my Slack Webhook attempt? My code below gives a status_code of 500 and a response of "no_text". What am I doing wrong?
url = 'https://hooks.slack.com/services/REDACTED'
    payload = {
            "server":socket.gethostname(),
            "files":str(files)
            }
    headers = {'Content-Type': 'application/json'}
    r = requests.post(url,data=json.dumps(payload),headers=headers)

A: Payload should be like this:
 payload = {
            "server":socket.gethostname(),
            "files":str(files),
            "text": "Some text"
            }


text:
Q: Gapi auth2 is undefined I'm useing this code
gpLogIn() {;
window['gapi'].auth2.authorize({
  client_id: 'xxxxxxxx.apps.googleusercontent.com',
  scope: [
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/gmail.send'
  ].join(' '),
  response_type: 'id_token permission',
  'prompt': 'select_account',
}, function(response) {
  console.log(response);
});

}
But my auth2 is undefined. Should I call something more, before calling my signIn method?

A: If its not finding google then i would guess you have forgotten to include the library.
<script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>

 /**
 * Callback after Google Identity Services are loaded.
 */
function gisLoaded() {
    tokenClient = google.accounts.oauth2.initTokenClient({
        client_id: CLIENT_ID,
        scope: SCOPES,
        callback: '', // defined later
    });
    gisInited = true;
    maybeEnableButtons();
}


text:
Q: Cannot read property 'property' of null I have a question regarding vanilla JavaScript, and what is the best practice to get rid of an error in console, saying that certain element doesn't exist on a page.
To be more precise, I made a custom slider, for my Homepage. And that slider only exists in index.html. And, whenever I go to other pages, I get an error, saying "Uncaught TypeError: Cannot read property 'style' of null".
Now, I know what the problem is, JS is looking for a certain class, and the class doesn't exist on that page. So, my question is, what is the best practice to overcome this problem?
Do I put it in a "for" loop, and if so, over what do I loop?

A: I would add an if condition to search for the slider and only run the code if that is found.
Something like this:
if(document.getElementById("slider") != null)
{
 //Do your stuff
}

A: The most basic way to handle this kind of issue is to wrap the relevant block of code in a try catch and then handle the error however you want in the catch.
You could also wrap the code that tries to read the style in an if block to check that the element exists.
These are both just good practices in your code in general when dealing with things that are potentially unknown, but really best practice is to only load in the script that handles the slider when your's on index.html and not other pages.


text:
Q: Passive voice with ditransitive verb, which is the patient? If I were to make the following constructions, how would I label the parts of the sentence using passive voice terminology? Alice seems to be the agent in both these constructions, but which is the patient, and is there a term for the third argument?

*

*"The book was given to Bob by Alice."

*"Bob was given the book by Alice."

I would like to know both the terminology that is used traditionally in English grammar as well as a general term that can be applied to other languages, since I want to compare it to other languages that may have different syntax or structures.


text:
Q: How could I different the subjunctive mood from wrong tense or singular from in third personal? Here is the example, which is right?
It's important he know this.
It's important he knows this.
It's important he has known this.
or, those above all right, but express different meaning.

A: The third form of the sentence could be grammatically correct but expresses an unlikely thought, implying he no longer knows this, but it is currently important that he knew it some time in the past. It seems to be motivating the listener to take some action to ensure that the person who currently may not know it, did know it in the past. This is impossible without time travel.
The final "s" in "knows" is third person not plural, mainly because plurality applies to nouns not verbs I suppose.
As for the subjunctive: I can't do better than point you at Wikipedia's article
Grammar Monster suggests "Through common usage, the non-subjunctive forms of verbs are gradually replacing the subjunctive forms."


text:
Q: Symfony Route Doesn't Show in debug:router I can't for the life of me get this route to work:
/***
 * @Route("/load_base_data/{projectId}", name="load_base_data", methods={"GET"})
 * @return Response
 */
public function loadBaseMeasures(int $projectId, DataLoadService $dataLoadService, ApiService $apiService)
{
    $response = $apiService->initResponse();
    $dataLoadService->generateFiles($projectId);

    return new JsonResponse($response);
}

I've tried php bin/console debug:router and it doesn't show up on the list.
I've tried php bin/console cache:clear
This is the only route I'm having trouble with.

A: Cerad was right, the problem was the /***. Changed to /** and it worked. Thanks!


text:
Q: Rectangles with side lengths proportional to transcendental numbers BESIDES $\varphi$ A rectangle with side lengths proportional to $\varphi$ is a "golden rectangle". If we perform a procedure of subtracting the shorter side length from the longer side length, a golden rectangle keeps the same proportions.
We can represent this procedure mathematically. If the old rectangle's sides are of length $A$ and $B$, with $A$ shorter, then the new rectangle will have side lengths $A$ and $B-A$. Hence, we have a golden rectangle when $\frac A B = \frac{B-A}B$, or $A^2-B^2+AB = 0$, and we define the golden ratio $\varphi$ as $\frac B A$ in this case. $A$ and $B$ clearly cannot themselves be rational numbers. They must, I'm guessing, likewise be transcendental numbers.
The second key point is that if you have a rectangle with side lengths that are rational numbers, repeating the procedure of subtracting the shorter side length always leads to generating a square after a finite number of steps. Repeating this procedure on the square gives the ratio $\frac 0 0$, which is undefined.
So we have two interesting properties of the golden rectangle. More generally, it does not converge on a square when we iterate the procedure of subtracting the shortest side length from the longer side length. More specifically, it keeps the same proportions as we do this.
It seems to me that if a rectangle can have proportions of $\varphi$, then it can have proportions of other transcendental numbers as well. And it also seems intuitively like iterating this procedure would also not converge on a square.
What interests me is what it would converge on. Would it approximate a square? Jump around indefinitely with any range of proportions?
I don't quite know how to think about this, so I thought I'd ask Stack Exchange and see if anybody can point me to some work in this area. I'm sure there must be something out there...
Thanks for any suggestions!

A: First of all, φ is not actually a transcendental number, but it is an algebraic irrational one. This is because φ can be expressed as the solution to an algebraic equation (specifically the one derived from the cutting rectangles), $x^2 - x - 1$. Assuming you were referring to irrational numbers, there is no other ratio that doesn't result in a square after truncation. This is because the golden ratio is the ONLY ratio of the side lengths that results in self-similarity, as it is the only positive solution to the equation above. It is easy to prove that the ratio cannot be rational; the Euclidean algorithm would guarantee that the sides would be the same length at some point. Regarding irrationals, the simplest argument would be that a lack of self similarity from one step to the next would imply that an infinite number of rectangles would be created, which would mean that at some point, the rectangle would be square. jjagmath's comments on the original post would be helpful for you to revise.


text:
Q: Simple Authentication for On premise Sharepoint 2013 Xamarin.Android app without using Windows Azure Being a beginner to mobile development I am trying to build an xamarin.android app which has to retrieve contents namely lists, news feeds, libraries and all the sites from an On premise Sharepoint 2013 Internet website.
After refering to forums and couple of  websites I understand we can fetch all these data by using REST Api calls. But before that I need to authenticate to the sharepoint site. According to my understanding we need to authenticate using OAuth which needs Windows Azure or any third party identity provider. Is there any other simple way of authenticating (For example just pass user name and password) and connect to the sharepoint site?
Thank you for your patience to read such lengthly post. Could anyone help me with any samples or reference? Appreciate your help


text:
Q: Limiting the set of "constructible" properties, and loosening comprehension axiom My historical understanding (which may very well be wrong) is that initially there was naive comprehension for set construction, which required no superset.  Russell's Paradox came along and blew that out of the water, and the current definition of comprehension was established for consistency.
I've recently been trying to understand the liar's paradox (this sentence is false) and I'm not at a comfortable place with it.  It seems to me to be related to Russell's paradox in its self referential nature, so I've been curious about duality between sets and statements or predicates.  I'm sure there is some good treatment of their relationship out there but I haven't researched that much yet (this is not my job).
What I was wondering is this...  The curtailing of naive comprehension seems to me to be an unbalanced choice.  Could one arrive at a similarly consistent set of axioms by restricting the class of constructible predicates and allow for comprehension without a superset?
If this question belongs in a different SE feel free to move it.  Thanks!

A: Yes, Quine's New Foundations only allows comprehension of stratified formulas, which is some way of saying that the variables can be assigned various "levels" or "types", and a variable can only be said to be an element (or not) of something of higher types.
In particular, $x\notin x$ is not a stratified formula, so it does not define a set.
Surprisingly, $x=x$ is a stratified formula, so the set of all sets exists just fine in $\sf NF$.


text:
Q: How to store an html file in a SQLite db? I am a newbie in android studio and I've been stuck to this problem.
I am developing an application that allows the user to import an html file to the database and i still cannot find as anwer to this. Or maybe I did not research more but I hope u guys can help me.

A: First you need to parse that HTML file and convert it to String. After that you have to individually parse data from tags and store them in database. It will be length answer, so you need to look into some tutorials online and take help of this website. Go step by step. All the best.
Also, welcome to Stack Overflow. Here is the Code of Conduct.

A: If I understand the problem, what you should do is first download all the html and save it in a string. Then, you will be able to save it to the sqlite db.
So what you should do is:

*

*Download the html and convert it to an string. You can use HTTPClient to do this task:
HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
    str.append(line);
}
in.close();
html = str.toString();

*Create the structure of the sqlite db. I don't know if you already have done this, but there are many tutorials you can find in google like tutorialSQLITE

*After steps 1 and 2, you just have to add a new entry to your database.


text:
Q: How to notify users about an Android app update? I've built an Android app which is now on Play Market. From time to time, I make updates to it, and I'd like to let users know that a new version is available.
How can I send an update notification to the users of the app?

A: I know this is an old question but still if people are coming here to check this question, Google is now providing official support for in-app notification for application update the full documentation can be found here

A: You do not need to do anything specific for this. Since you mentioned that you are using Google Play, the update notification is taken care of by Google Play.
You just need to update the APK with a higher versionCode and Google Play should do the rest.

A: Use this : https://www.push-link.com/

A: Google Play will notify your users that the app has an update via the notification bar.
If you set up a notification system yourself, the likely result would be that, although the user is notified of an update sooner, when he/she goes to Google Play to install the update it will not yet be available.  This is because there is a lag from the time you "publish" an app/update and the time until it appears on Play.  Telling your users that there is an update when the update is unavailable would only lead to confusion and frustration.
My advice: stick with Google's update notification system and don't worry about trying to get users an update 15 minutes sooner.

A: Some people use Android Cloud-to-Device Messaging (C2DM) to notify their users of updates.  I don't think I'd bother, since I think Google Play does a pretty good job of notifying me of updates already, and implementing C2DM adds a whole new dimension to writing an app (because it requires a server component).  But maybe you want to offer your users a richer update notification than you get from Google Play.

A: @Davek804's answer above is wrong. android:versionCode is an integer value that represents the version of the application code, relative to other versions, so using "1.5b" there is incorrect. Use "15" (or "150") instead

A: Found a nice solution for your problem:
Let´s say you want to check for version updates manually on app start and notify your users for the new Update.
Step 1: Download android-market-api (not the .jar file, the full project!)
Step 2: After importing it to eclipse, write in your activity the following code:
MarketService ms = new MarketService(activity);
ms.level(MarketService.REVISION).checkVersion();

now, we need to modify MarketService.java, because it seems to be broken.
Step 3: rewrite callback method and add the following methods
protected void callback(String url, JSONObject jo, AjaxStatus status){
        if(jo == null) return;
        String googlePlayversion = jo.optString("version", "0");
        String smartphone_version = "";

        PackageInfo pInfo;
        try {
            pInfo = act.getPackageManager().getPackageInfo(act.getPackageName(), 0);
            smartphone_version = pInfo.versionName;
        } catch (NameNotFoundException e) {}
        boolean new_version_avaible = compare(smartphone_version, googlePlayversion);
        if(new_version_avaible){
            showUpdateDialog(jo);
        }
    }

    private static boolean compare(String v1, String v2) {
        String s1 = normalisedVersion(v1);
        String s2 = normalisedVersion(v2);
        int cmp = s1.compareTo(s2);
        String cmpStr = cmp < 0 ? "<" : cmp > 0 ? ">" : "==";
        System.out.printf("result: "+"'%s' %s '%s'%n", v1, cmpStr, v2);
        if(cmpStr.contains("<")){
            return true;
        }
        if(cmpStr.contains(">")||cmpStr.contains("==")){
            return false;
        }
        return false;
    }

    public static String normalisedVersion(String version) {
        return normalisedVersion(version, ".", 4);
    }

    public static String normalisedVersion(String version, String sep, int maxWidth) {
        String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);
        StringBuilder sb = new StringBuilder();
        for (String s : split) {
            sb.append(String.format("%" + maxWidth + 's', s));
        }
        return sb.toString();
    }

If you want to test it, modify googlePlayversion string to a higher version than your local one.
The source comparison method I used is from How do you compare two version Strings in Java?

A: There is also a very good approach for checking version and give user in app notification or when you want to forcefully update the application if you can decide the first connection of your app with the server.In the response of the first request you can send the current version of app stored on your server and then on client end you can take the appropriate action.
Advantages of this approach-:

1-No extra request for version no.

2-It is also applicable if you are downloading the app other than the google playstore.

3-you can also use this idea if you want to check the version at particular operation of your app ex- transaction(if you add a new payment gateway.)

A: Update 2020: now you can use in-app updates mechanism

Docs: https://developer.android.com/guide/playcore/in-app-updates

A: You can do this in a lot of ways, depending on when you want the user to be able to see that there is an update available.
If you want the user to know about the update when the app is started, just create a utility method (inside the onCreate method of your main/first Activity) that checks if a newer version is available in Google Play. If it does, display an alert dialog with a relevant message and an Intent which opens your app in Google Play when the user clicks on the positive button of the alert dialog.
If you are updating the app regularly, the user will keep getting this alert dialog every time the app is started and hence, may get irritated. Thus, this is not the best approach.
If you want the user to get a notification on the phone (and not when the user starts the app), you can use the AlarmManager class to schedule a background service which checks for an update at regular intervals. If the service finds that an upgrade is actually available, publish a notification with an intent that opens your app in Google Play.
Of course, another approach is to leave it to the OS itself. If the user has not set the "Automatically update" preference for your app, the user will get a notification regularly about an update available for your, as well as any other apps.
But not all users enable background data on their devices, so this is not completely reliable.
In the end, you must respect the users preferences. If the user does not want to automatically update the app, or does not want to see a nagging dialog box whenever he/she starts your app, don't alert the user about the update.
In my opinion, you should create a PreferenceActivity that has a preference like "Check for updates regularly", which can be set from within your app. If it is set, do the needful in your own service. May be even give the user an option to select the period after which the service will check for an update.
I hope this helps!

A: It is up to each phone owner if she wants to be notified on new versions by google play, and it's up to each phone's manufacturer if this is to be enabled by default.
If you however are in a situation where you "require" the user to update to the new version to be compatible with some form of protocol or you have a similar similar use case where you have a server component somewhere, you might want to notify the user of a potential version conflict in the UI based on information about what is the latest version.
This information can be grabbed directrly from google play, however as @Yahel pointed out in  this question google play is a closed system with no official API, and you might need to rely on unpredictable undocumented API. There is an unofficial API library here.
This leaves only one option, which is to keep this information on your own server. If you allready have a serverside this might be trivial. Simply put the latest version in an XML file and retreive that at regular intervals from your code. If the version code is outdated, trigger the notification in your UI. Here is an example implementation for doing that.
I hope this was helpful :-)

A: Don't know if you want to walk extra miles. You can try out google appengine, which serve version number for your app and let you android app check the appengine to see if there is a new version when the application is launched. That way, it does not matter if your app is in google play market nor amazon app store nor if it is installed on the phone without those two via sideloading. It is not very hard to setup appengine just for serving your application version in json. Replace "Hello World" string with your app version name ...

A: This can be using a simple webservice just this is one of the way to acheive.
i.e., when ever the app launch hit that webservice with the current version of the user app and on the server you need to check whether any new version is available or not(Must maintain the newest version of the app) and send the corresponding response to the user. If any newer version is available prompt the user to download the newest version of the application and if no newest version is available then allow the user to continue.
Hope so atleast something must be useful to you.

A: There are two models that are basically used to tackle the issue.
Pull Based
Push Based

Its depends on the architecture or design of particular system that determines whether pull based or push mechanism is used.
For pull based model you just make one http request to concerned server regarding the new version of application. The current application version no can be saved in SQLLite in android application. This can be given to server and new version can be checked against it at the server.
For push mechanism you can use C2DM push notification service.. details of which are given at http://code.google.com/android/c2dm/

A: Generally when you upload a new application to Google play most users get a notification about an update, some will have the app automatically downloaded to their device, depending on the settings they have.
If you seriously want to make a notification from your app to ask them to update (so that everyone gets the notification, whatever their Google play settings are, then you will have to make a web service which returns the number of the newest version. You can then compare that inside your app and post a notification. You could use Google App Engine ( https://developers.google.com/appengine/) because that works with eclipse and java, which you probably already have.
I would not recommend this approach as it creates a lot of work for you to provide something that most users have already got.

A: i think this is too late but it can be help some one
public enum AppVersionUpgradeNotifier {
INSTANCE;

private static final String TAG = "AppVersionUpdateManager";

private static final String PREFERENCES_APP_VERSION = "pref_app_version_upgrade";
private static final String KEY_LAST_VERSION = "last_version";

private SharedPreferences sharedPreferences;
private VersionUpdateListener versionUpdateListener;
private boolean isInitialized;

public static synchronized void init(Context context, VersionUpdateListener versionUpdateListener) {
    if (context == null || versionUpdateListener == null) {
        throw new IllegalArgumentException(TAG + " : Context or VersionUpdateListener is null");
    }

    if (!INSTANCE.isInitialized) {
        INSTANCE.initInternal(context, versionUpdateListener);
    } else {
        Log.w(TAG, "Init called twice, ignoring...");
    }
}

private void initInternal(Context context, VersionUpdateListener versionUpdateListener) {
    this.sharedPreferences = context.getSharedPreferences(PREFERENCES_APP_VERSION, Context.MODE_PRIVATE);
    this.versionUpdateListener = versionUpdateListener;
    this.isInitialized = true;
    checkVersionUpdate();
}

private void checkVersionUpdate() {
    int lastVersion = getLastVersion();
    int currentVersion = getCurrentVersion();

    if (lastVersion < currentVersion) {
        if (versionUpdateListener.onVersionUpdate(currentVersion, lastVersion)) {
            upgradeLastVersionToCurrent();
        }
    }
}

private int getLastVersion() {
    return sharedPreferences.getInt(KEY_LAST_VERSION, 0);
}

private int getCurrentVersion() {
    return BuildConfig.VERSION_CODE;
}

public void upgradeLastVersionToCurrent() {
    sharedPreferences.edit().putInt(KEY_LAST_VERSION, getCurrentVersion()).apply();
}

public interface VersionUpdateListener {
    boolean onVersionUpdate(int newVersion, int oldVersion);
}

}
use it on
public class MyApplication extends Application implements AppVersionUpgradeNotifier.VersionUpdateListener {

@Override
public void onCreate() {
    super.onCreate();

    AppVersionUpgradeNotifier.init(this,this);
}

@Override
public boolean onVersionUpdate(int newVersion, int oldVersion) {
    //do what you want

    return true;
}

}

A: <manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1.5b"
android:versionName="1.5b">

When you re-upload your app to Google Play, if these two attributes have been changed from the previous upload, Google Play will automatically send notifications to users who have installed your app. This is the AndroidManifest file.


text:
Q: Global variable's value is not changing after changing its value in function <!DOCTYPE html>

<title>Gemoetry</title>

<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0">

I'm trying to use the new values of longitude and latitude variables in my initMap function; I declared them globally and then had values passed into them in my 'success' function within ajax. but the variables keep returning undefined in my initMap function. I thought I knew global/local scope but am now confused? Why is this happening? BTW, I deleted the 'let key' variable just incase you were wondering.


text:
Q: If condition to return multiple data type I have a column with values:
10
20
30

I declared this column as nvarchar. Now I wanted a calculated column / field where if column > 0 then column * 10 else column.
The desired output is:
100
200
300

I tried if and it didn't work.

A: CASE WHEN column > 0 THEN column*10 ELSE column END

See https://help.sap.com/viewer/4fe29514fd584807ac9f2a04f6754767/2.0.02/en-US/20a4389775191014b5a6bf2ccc0df2ed.html


text:
Q: Can't change Column to array - int64 I have a CSV dataset with 2 columns that looks like the following:

Date
Open

25/2/21
7541.85

26/2/21
7562.32

27/2/21
7521.65

28/2/21
7509.14

Data columns (total 2 columns):

#
Column
Non-Null
Count
Dtype

0
Open
1280
non-null
object

1
Date
1280
non-null
datetime64[ns]

dtypes: datetime64ns, object(1)
When trying to pass this through a timeseries model I get the following error:
 ftse_open = TimeSeries.from_dataframe(ftse_open, time_col='Date', value_cols='Open')

ValueError: could not convert string to float: '7,541.85'

Then I try a different route using the following code:
ftse_open["Open"] = ftse_open["Open"].astype('Int64')
Yielding:

TypeError: object cannot be converted to an IntegerDtype

I have tried more code to resolve but I'm not sure why there seems to be no solution that I can find.
(There are no NAs in the dataset - I have checked).
Any help is appreciated, thank you.

A: Based on comments, you can try:
df["Open"] = df["Open"].str.replace(",", "").astype(float)
print(df)

Prints:
      Date     Open
0  25/2/21  7541.85
1  26/2/21  7562.32
2  27/2/21  7521.65
3  28/2/21  7509.14

df used:
      Date      Open
0  25/2/21  7,541.85
1  26/2/21  7,562.32
2  27/2/21  7,521.65
3  28/2/21  7,509.14


text:
Q: Setting a background Image in phonegap #bgImage{
background-image:url("/MedicineAlert/res/drawable-hdpi/bgimage.png");
background-size: 100% 100%;
background-repeat:no-repeat;
background-position:100% 100%;
top: 0px;
left: 0px;
}

.formButton{

    font-family: Verdana, Geneva, sans-serif;
    font-size: 24px;
    color: #FFF;
    padding: 5px 10px 5px 10px;
    border: solid 1px #CCC;

    background: #ba4742;
    text-shadow: 0px 1px 0px #000;

    border-radius: 5px;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;

    box-shadow: 0 1px 3px #111;
    -moz-box-shadow: 3px 3px 1px #999;
    -webkit-box-shadow: 3px 3px 1px #999;

    cursor: pointer;

}
.formButton:hover {
    background: #a33f3a;
}

    <!DOCTYPE HTML>

    <meta name="viewport" content="width=320; user-scalable=no" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Alert Time</title>
      <link rel="stylesheet" href="register.css" type="text/css" media="screen" title="no title">

    <hearder>

Please fill out the form and submit

        <form action="" method="post">

                    Your information Please!

        <form id="form_info" action="" method="post">
                 Fist Name   <input type="text" name="fname" required="required" />

                 Middle Name   <input type="text" name="mname" />

                 Last name   <input type="text" name="lname" required="required" />

                 Date of birth   <input type="text" name="dOfBirth" required="required"/>

                 Social security Number   <input type="text" name="sNumber" />

                 Gender   Male
                 <input type="radio" name="sex" id="male" />
                 Female
                 <input type="radio" name="sex" id="female" />

                <input type="submit" name="submitButton" value="Submit" class="formButton" />
        </form>

I have difficulty in accessing the Image in my drawable-hdpi folder. First I created a folder named image inside the assets folder, then  I tried to reference the image inside the image folder which is in the assets directory, using css but it did not work. I decided to use the drawable for my resources but still I have the same problem. Any help?

A: Put the image back in the assets/www folder maybe in a folder called images and access it as follows:
background-image:url("images/bgimage.png");
This should work.
Can you your inline css should be within the head element of the html doc and wrapped by

A: The paths used internally when the app is deployed are different to what you see in the project structure. Try
background-image:url("file:///android_res/drawable/bgimage.png");

For assets/image, use
background-image:url("file:///android_asset/image/bgimage.png");


text:
Q: OpenLDAP won't start and won't log why Recently needed to restart OpenLDAP on one of our servers. When I restart the service, the command prompt just sits there waiting for something. I never get the [ OK ]. If I CTRL+C out of it, it says
...killed.
/etc/openldap/cacerts/company.crt is not readable by "ldap[WARNING]

Just to prove a point, I made /etc/openldap 777 recursively. I still get the error.
I don't see anything in /var/log changing to give me some feedback. Where do I need to look to fix this?
This is an old server running Fedora 8 (ya I know, blame the previous IT guy).

A: Here are some ideas for additional debugging.  These are only necessary if you're absolutely positive it's not a permission problem...
First, try running slapd in debug mode:
slapd -u ldap -g ldap -d 65

Note that the argument to -d is a bit field, values for which can be found in the slapd.conf man page (look for loglevel).  65 is trace + config, which is usually sufficiently verbose for this sort of problem.  This may or may not show you anything useful.
If that doesn't work, we can use strace (a system call tracer) to figure out exactly what's going on.  Run slapd like this:
strace -o /tmp/trace -f -s 1024 slapd -u ldap -g ldap -d 7

When it dies, you'll have a file /tmp/trace containing all the system calls from slapd.  For the curious -f makes strace follow forks (not really necessary in this case, but it's my default), and -s 1024 makes strace print up to 1024 bytes of string arguments in the trace log.
Now, use grep to look for references to company.crt in this file.  In theory you'll find something that looks like this if their is a permission problem:
open("/tmp/company.crt", O_RDONLY)      = -1 EACCES (Permission denied)

Or something like this if the file is missing:
open("/tmp/company.crt", O_RDONLY)      = -1 ENOENT (No such file or directory)

A successful open looks like this:
open("/tmp/company.crt", O_RDONLY)      = 3

Where that 3 is the file descriptor returned by open (and will probably be some other positive integer).
Take a look and see if something obvious jumps out.  Let me know if that doesn't help.

A: You shouldn't set /etc/openldap to 777.  Permissions are necessary to make things work correctly sometimes.  I would suggest changing it back to 755.
You might have the incorrect user and or permission on cacerts
drwxr-xr-x  3 root root 4096 Apr 19  2007 cacerts/


text:
Q: Retrieving files from sdcard in Android In my application I'm retrieving files from sdcard and after checking is it .jpg oe .png image I'm storing path of file in File array. But I'm getting NullPointerException also the file path exists. What is wrong with following code. Please help
 File[] image;
  File f = new File("/sdcard/download");//or Environment.getExternalStorageDirectory().getPath()
        File[] files = f.listFiles();

        int j=0;
        for(int i = 0; i < files.length; i++,j++) {
            File file1 = files[i];

            String myfile = file1.getPath().substring(file1.getPath().lastIndexOf("/")+1,file1.getPath().length()).toLowerCase();
            System.out.println("file is : "+files[i]);
            if(myfile.endsWith(".jpeg")||myfile.endsWith(".png")|| myfile.endsWith(".gif") || myfile.endsWith(".jpg"))
            {
                System.out.println("file is : "+files[i]);
                image[j]=files[i];//here i'm getting exception
                }
            }

exceptions-
  02-15 19:28:36.463: E/AndroidRuntime(12918): FATAL EXCEPTION: main
02-15 19:28:36.463: E/AndroidRuntime(12918): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.my.zproject/com.my.zproject.ImportFile}: java.lang.NullPointerException
02-15 19:28:36.463: E/AndroidRuntime(12918):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
02-15 19:28:36.463: E/AndroidRuntime(12918):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-15 19:28:36.463: E/AndroidRuntime(12918):    at android.app.ActivityThread.access$2300(ActivityThread.java:125)
02-15 19:28:36.463: E/AndroidRuntime(12918):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
02-15 19:28:36.463: E/AndroidRuntime(12918):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-15 19:28:36.463: E/AndroidRuntime(12918):    at android.os.Looper.loop(Looper.java:123)
02-15 19:28:36.463: E/AndroidRuntime(12918):    at android.app.ActivityThread.main(ActivityThread.java:4627)
02-15 19:28:36.463: E/AndroidRuntime(12918):    at java.lang.reflect.Method.invokeNative(Native Method)
02-15 19:28:36.463: E/AndroidRuntime(12918):    at java.lang.reflect.Method.invoke(Method.java:521)
02-15 19:28:36.463: E/AndroidRuntime(12918):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-15 19:28:36.463: E/AndroidRuntime(12918):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-15 19:28:36.463: E/AndroidRuntime(12918):    at dalvik.system.NativeStart.main(Native Method)
02-15 19:28:36.463: E/AndroidRuntime(12918): Caused by: java.lang.NullPointerException
02-15 19:28:36.463: E/AndroidRuntime(12918):    at com.my.zproject.ImportFile.onCreate(ImportFile.java:76)
02-15 19:28:36.463: E/AndroidRuntime(12918):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

A: you need to initialize array image like this
File[] image;
File f = new File("/sdcard/download");//or Environment.getExternalStorageDirectory().getPath()
    File[] files = f.listFiles();
    image = new File[files.length]
    int j=0;


text:
Q: Integrating AngularJS and Thymeleaf I am developing a Spring based application, with Thymeleaf as the template engine. I am using AngularJS in the html5 pages generated.
Is there a way I can use the JS variables alongwith Thymeleaf?
For instance, consider that my html receives a variable 'id' from my angularJS controller. Assume that Angular sends back the value of id as 1
Using Thymeleaf, I wish to create a link like
here, id is the value being passed or generated from Angular.
Is this possible?

A: Yes you can do it this way
Profile


text:
Q: Adjust angle length in MetaPost I'm making some triangles in ConTeXt using Metafun's anglebetween macro. However, some angles look awful, specially if they're larger.
\starttext
\startuseMPgraphic{name}
u := 4cm;
pair A, B, C, D, P;
path AB, BC, AC, BD, BP;
A = (0,0); C = (cosd 50 + cosd 80, 0)*u; B = (cosd 80, sind 80)*u;
P = (cosd 80, 0)*(u); D = P*2;
AB = A -- B; AC = A -- C; BC = B -- C;
BD = B -- D; BP = B -- P;
draw AB; draw BC; draw AC;
draw BD; draw BP;
draw anglebetween(A--B, A--C, "$8x$");
draw anglebetween(C--B, C--A, "$5x$");
draw anglebetween(B--D, B--A, "$2x$");
label.llft("{\tfx\ss A}", A);
label.urt("{\tfx\ss B}", B);
label.lrt("{\tfx\ss C}", C);
label.bot("{\tfx\ss P}", P);
label.bot("{\tfx\ss D}", D);
\stopuseMPgraphic
\useMPgraphic{name}
\stoptext

As readily seen, angles labelled 8x and 5x look too large. scaled gives weird results. How do I adjust angles so they have a smaller radius?

A: Here's how you could do it using just the plain MP facilities.  By "doing it yourself" you get the flexibility to adjust the arc sizes appropriately.

\starttext
\startuseMPgraphic{name}
    pair A, B, C, D, P;
    A = origin;
    B = 6cm * dir 80;
    ypart C = 0;
    B - C = whatever * dir 130;
    P = (xpart B, ypart A);
    D = A reflectedabout(P, B);

    path arc[];
    arc1 = fullcircle rotated angle (C-A) scaled 21 shifted A cutafter (A--B);
    arc2 = fullcircle rotated angle (B-C) scaled 32 shifted C cutafter (C--A);
    arc3 = fullcircle rotated angle (A-B) scaled 42 shifted B cutafter (B--D);

    drawoptions(withcolor 2/3 red);
    draw arc1; label.urt("$8x$", point 1 of arc1);
    draw arc2; label.ulft("$5x$", point 0.7 of arc2);
    draw arc3; label.lft("$2x$", point 0 of arc3);
    drawoptions();

    draw A -- B -- C -- cycle;
    draw P -- B -- D;

    label.llft("{\tfx\ss A}", A);
    label.top("{\tfx\ss B}", B);
    label.lrt("{\tfx\ss C}", C);
    label.bot("{\tfx\ss P}", P);
    label.bot("{\tfx\ss D}", D);
\stopuseMPgraphic
\useMPgraphic{name}
\stoptext

A: Just and only for fun.
Compile with Asymptote. :-)
unitsize(1cm);
pair A=(0,0),B=4.5*dir(80),C=(5.2,0),
     P=(B.x,A.y),D=reflect(P,B)*A;
draw(A--B--C--cycle^^B--P^^B--D);
draw(scale(.7)*Label("$2x$",Relative(0)),arc(B,0.4,degrees(dir(A-B)),degrees(dir(D-B))));
draw(scale(.7)*"$5x$",arc(C,0.3,degrees(dir(B-C)),degrees(dir(A-C))));
draw(scale(.7)*"$8x$",arc(A,0.3,0,80));
label("$A$",A,dir(-135));
label("$B$",B,dir(90));
label("$C$",C,dir(-45));
label("$P$",P,dir(-90));
label("$D$",D,dir(-90));


text:
Q: Secure Action cable with Doorkeeper Authorisation I am working on ActionCable and implemented Doorkeeper Authorization in my rails application.
I want to implement authenticate my client with Doorkeeper::AccessToken with ActionCable
Here is how I authenticated right now:
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user
    identified_by :room_id

    def connect
      self.current_user = find_verified_user
      self.room_id = @user.ac_channel_room
    end

    def disconnect
      # When user will disconnect action cable, this method call will be executed.
    end

    private

    def find_verified_user
      check_access_token
      @user = User.find_by_id(@resource_owner_id) if @resource_owner_id
      reject_unauthorized_connection unless @user
    end

    def check_access_token
      # Check provided token is valid or not
      params = request.query_parameters
      @access_token ||= Doorkeeper::AccessToken.by_token(params[:access_token])
      @resource_owner_id = @access_token&.resource_owner_id
    end
  end
end

Problem is this is allowing experied access tokens as well.
Please help!

A: Your question will allow action cable connection with expired Doorkeeper::AccessToken objects.
Here is the solution:
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = authenticate!
    end

    protected

    def authenticate!
      reject_unauthorized_connection unless doorkeeper_token&.acceptable?(@_doorkeeper_scopes)

      # this will still allow expired tokens
      # you will need to check if token is valid with something like
      # doorkeeper_token&.acceptable?(@_doorkeeper_scopes)

      user = User.find_by(id: doorkeeper_token.try(:resource_owner_id))

      user || reject_unauthorized_connection
    end

    def doorkeeper_token
      ::Doorkeeper.authenticate(request)
    end
  end
end

# ...

class SomeChannel < ApplicationCable::Channel
  def subscribed
     reject unless current_user
     stream_from 'some'
  end
end


text:
Q: Angular routing not working when deployed to tomcat 9 (Ubuntu 18.04) I coded an angular project on my own PC, everything worked fine when I ran it locally with the command ng serve. Now I want to deploy it on tomcat on a VM (provided by my school) because my project needs to be public.
I created a git repository and downloaded the angular project on the VM. Followed a tutorial to deploy the app in tomcat, which simply consisted of 2 steps:

*

*Run ng build --base-href=/angular/ to generate some files

*Copy the generated files to tomcat's /webapps subfolder

But it does not work as intended. To me it seems like there's an issue with routing.
Here's my routing module:
const appRoutes: Routes = [
  {path: 'coachPortal', component: CoachPortalComponent},
  {path: 'userPortal', component: UserPortalComponent},
  {path: 'users', component: UsersComponent},
  {path: 'userDetails/:id', component: UserDetailsComponent},
  {path: 'mySessions', component: MySessionsComponent},
  {path: '', redirectTo: '/coachPortal', pathMatch: 'full'},
  {path: '**', component: CoachPortalComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

To navigate between routes, I use this old simple code: window.location.href = '/users';
This worked like a charm when I ran it locally on my pc.
But I'm guessing the reason why it's not working anymore after deploying on tomcat is because tomcat adds the prefix angular/.
When running locally on my pc the urls were localhost:4200/{componenturl}.
But on the VM it's x.x.x.x:8080/angular/{componenturl}
But because of the routing redirects I am getting 404 errors. When I first visit the root url x.x.x.x:8080/angular, it matches with the rule {path: '', redirectTo: '/coachPortal', pathMatch: 'full'}. and loads the coachPortal component and even changes the url to angular/coachPortal. But refreshing the page or manually entering angular/coachPortal gives a 404 error. And all other links don't work either.
Also on the coachPortal I have an image with src ../../../assets/logo.png and it obviously doesn't load because of how the generated files in webapps folder have different folder structure... How can I fix this? The image is directly under assets folder.

A: You can try use useHash: true. For me its working.
Example:
@NgModule({
    imports: [RouterModule.forRoot(routes, { useHash: true })],
    exports: [RouterModule],
})

and url on the VM will be x.x.x.x:8080/angular/#/{componenturl}

A: My understanding is that when you try to navigate to a virtual sub directory that is usually resolved via Angular Routing, when it is deployed your webserver is looking for an actual directory of 'coachportal', which doesn't exist so returns a 404. If the route had been navigated to through your app (by navigation buttons etc.) Angular Router would resolve it and bring up the virtual sub-directory. Your webserver is stopping the route from getting to Angular Router to resolve it. Your webserver checks to see if there is an actual folder or file and then redirects to your root to handle the routing if there is no file or folder with that name. For web projects I have deployed on IIS I include a web.config file with the following code:
<configuration>
    <system.webServer>
      <rewrite>
        <rules>
          <rule name="Angular" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAll">
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            </conditions>
            <action type="Rewrite" url="/" />
          </rule>
        </rules>
      </rewrite>
    </system.webServer>
</configuration>

from this post: Routing in Angular 7 running in subfolder not working correctly I'm not sure if it will work with your deployment setup, but should at least give you insight into what may be going on.
For your assets folder remove the ../s for a relative directory and just leave it as assets/logo.png it should handle this correctly. you can test it locally.
EDIT: changed some things for clarity

A: I also met this problem, and just find an easy way. Maybe it will help others.
with apache-tomcat-7.0.55 and angular 11. with other versions not tested.
just based on @Erikher 's answer and something more to be done:

*

*first: RouterModule.forRoot(routes, {useHash: true})

*second*(may not need)*: providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],

*third: change base-href in index.html from '/' to '#'
Then it works for me.


text:
Q: How can I create an incremental build to derive output filenames from input filenames? I must write a plugin to compile files of a certain type not covered by an existing plugin.
My initial requirements are simply that if the input file is changed or if the output is missing, then the task will not be up-to-date. In other words, I want the core "working with files" paradigm to work for me.
My first attempt was to declare both inputs and outputs to see if the project would work as most would expect.
class TestPlugin implements Plugin<Project> {
    void apply (Project project) {
        project.task('compile') {
            doFirst {
                inputs.files.eachWithIndex { inFilename, idx ->
                    def inFile = project.file(inFilename)
                    def outFilename = outputs.files[idx]
                    def outFile = project.file(outFilename)
                    logger.info "converting ${inFile} to ${outFile}"
                    outFile.append "something"
                }
            }
        }
    }
}
apply plugin: TestPlugin
compile {
    inputs.file "test.in"
    outputs.file "test.out"
}

And it does. At this point it does all I need except for one thing: I have to define outputs in correlation with inputs. But defining the outputs is complicated enough to warrant factoring that part of the code into the plugin's task.
My next attempt was to try to get the task to define its outputs but it fails because when the "populate outputs" code executes, inputs is empty and so no outputs are added.
class TestPlugin implements Plugin<Project> {
    void apply (Project project) {
        project.task('compile') {
            inputs.files.each { outputs.files.add(it.replaceFirst(~/\.in$/, '.out')) }
            doFirst {
                inputs.files.eachWithIndex { inFilename, idx ->
                    def inFile = project.file(inFilename)
                    def outFilename = outputs.files[idx]
                    def outFile = project.file(outFilename)
                    logger.info "converting ${inFile} to ${outFile}"
                    outFile.append "something"
                }
            }
        }
    }
}
apply plugin: TestPlugin
compile { inputs.file "test.in" }

The above fails with a "path may not be null..." error caused by indexing an empty outputs list (because inputs is empty at the time the task's outer block iterates over inputs.
I tried populating outputs in Project.afterEvaluate and Project.beforeEvaluate but neither worked. The beforeEvaluate closure never executed. The afterEvaluate closure executed, well, after the project was evaluated which means it executed after the task was set as either up-to-date or out-of-date and so it's not useful for what I need.
I also tried Project.configure but that didn't work either.
Then I discovered lazy configuration but since it's incubating I think I should avoid it. I'm assuming that the Java and C plugins don't use incubating features and that leaves me wondering how those plugins are accomplishing the equivalent of lazy configuration.
Then I found Gradle plugin for custom language but it doesn't have an answer. It does, however, have a comment leading me to look at a lot of gradle source code. Again, I don't think I should have to reinvent the wheel.
Lastly, if I have to push the decision to compile into doFirst and not bother with declaring outputs (and thereby abandon task up-to-datedness), then so be it. I just need to know and move on.
For more context, I'm migrating a build away from ant. The two udemy.com classes I took helped me a lot but didn't go far enough to lead me in a confident direction to solve the stated problem. I asked a similar question to one of the instructors and its community to no avail.


text:
Q: Python multiprocessing memory usage I have writen a program that can be summarized as follows:
def loadHugeData():
    #load it
    return data

def processHugeData(data, res_queue):
    for item in data:
        #process it
        res_queue.put(result)
    res_queue.put("END")

def writeOutput(outFile, res_queue):
    with open(outFile, 'w') as f
        res=res_queue.get()
        while res!='END':
            f.write(res)
            res=res_queue.get()

res_queue = multiprocessing.Queue()

if __name__ == '__main__':
    data=loadHugeData()
    p = multiprocessing.Process(target=writeOutput, args=(outFile, res_queue))
    p.start()
    processHugeData(data, res_queue)
    p.join()

The real code (especially writeOutput()) is a lot more complicated. writeOutput() only uses these values that it takes as its arguments (meaning it does not reference data)
Basically it loads a huge dataset into memory and processes it. Writing of the output is delegated to a sub-process (it writes into multiple files actually and this takes a lot of time).
So each time one data item gets processed it is sent to the sub-process trough res_queue which in turn writes the result into files as needed.
The sub-process does not need to access, read or modify the data loaded by loadHugeData() in any way. The sub-process only needs to use what the main process sends it trough res_queue. And this leads me to my problem and question.
It seems to me that the sub-process gets its own copy of the huge dataset (when checking memory usage with top). Is this true? And if so then how can i avoid id (using double memory essentially)?
I am using Python 2.6 and program is running on linux.

A: The multiprocessing module is effectively based on the fork system call which creates a copy of the current process. Since you are loading the huge data before you fork (or create the multiprocessing.Process), the child process inherits a copy of the data.
However, if the operating system you are running on implements COW (copy-on-write), there will only actually be one copy of the data in physical memory unless you modify the data in either the parent or child process (both parent and child will share the same physical memory pages, albeit in different virtual address spaces); and even then, additional memory will only be allocated for the changes (in pagesize increments).
You can avoid this situation by calling multiprocessing.Process before you load your huge data. Then the additional memory allocations will not be reflected in the child process when you load the data in the parent.
Edit: reflecting @Janne Karila's comment in the answer, as it is so relevant: "Note also that every Python object contains a reference count that is modified whenever the object is accessed. So, just reading a data structure can cause COW to copy."

A: As recommended in the documentation (-> Explicitly pass resources to child processes), I would make the large data (explicitly) global, so if there is copy-on-write (COW) available and you fork new processes (in macOS it is spawn by default nowadays), the data is available in the child processes:
def loadHugeData():
    global data
    return data

def processHugeData(res_queue):
    global data
    for item in data:
        res_queue.put(result)
    res_queue.put("END")

But keep in mind, that Python data structures are copied. You would need to some more low-level data types such as numpy because of Python GIL.


text:
Q: Solve : JAVA Selenium : Impossible to set a value on input I want to set a value to an input i try :
find(By.xpath("MyXpath")).type(montant);

and
find(By.xpath("MyXpath")).typeAndTab(montant) ;

and
find(By.xpath("MyXpath")).typeAndEnter(montant) ;

and
getDriver().findElement(By.xpath("MyXpath")).sendKeys("value", "5");

and
getDriver().findElement(By.xpath("MyXpath")).sendKeys(Keys.HOME,Keys.chord(Keys.SHIFT,Keys.END),"5");

and
Actions actionInput = new Actions(getDriver());
     actionInput.moveToElement(find(By.xpath("MyXpath"))).clickAndHold().sendKeys(montant).
     release().build().perform();

and
getDriver().findElement(By.xpath("MyXpath")).click() ;
getDriver().findElement(By.xpath("MyXpath")).clear() ;
getDriver().findElement(By.xpath("MyXpath")).sendKeys(Keys.HOME,Keys.chord(Keys.SHIFT,Keys.END),"5");

nothing work..
but i can't set the value of the input the field is empty when i clear so it's not my xpath and i don't have error at this moment, the test continue the rest of the test normally but the result at the end it's not good because this field is not set to the good value :/
Anyone have an idea ?
the input :
<input class="MyClass" input-number="" type="number" value="valAngular" min="0" max="100" xpath="1">

the value is set with Angular
is it a problem ?
thanks for your help !
Edit : I look developers of the website and it's solve, the angular property set in DOM block serenity

A: WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementByClassName('MyClass').setAttribute('value', '10')");


text:
Q: 'Equiwidth' sets Here is a question that I've been thinking of for about a week:
Suppose we're living in $\mathbb{R}^2$. Since we are living 'in' $\mathbb{R}^2$, everything on a plane will seem 1-dimensional. (That is, what we view is the projections)
Let's call a compact convex subset $A$ of $\mathbb{R}^2$ 'equiwidth' (or shortly 'EW') if its width looks all the same regardless of our viewpoint.
(In a mathematical term,) a compact convex subset $A$ of $\mathbb{R}^2$ is EW iff $l(\pi_\theta (A))$ does not depend on $\theta$ where $\pi_\theta$ is the (orthogonal) projection into the line $y\cos\theta = x\sin\theta$ and $l(B)$ is the length of $B$. (The length is well defined for $\pi_\theta(A)$, which is just a closed interval.)
My original question is to specify EW subsets of $\mathbb{R}^2$. But I found out that EW subsets are uncountably many, so it might not be a good idea to classify all of them. I just want to know some general characteristics of EW sets or interesting properties of them.

Edited: And here is how I approached the problem.
Let's just consider EW sets with width $1$. I defined an operator $r:\mathcal{P}(\mathbb{R}^2)\rightarrow \mathcal{P}(\mathbb{R}^2)$ by $r(A)=\{x\in \mathbb{R}^2 : d(x,a) \leq 1, \forall a\in A\}$. It can be shown that $A$ is EW (with width $1$) if and only if $A=r(A)$.
I also defined an operator $C:\mathcal{P}(\mathbb{R}^2)\rightarrow \mathcal{P}(\mathbb{R}^2)$ by $C(A)=\cup\{r^2(l) : l \text{ is a line segment in }A\}$. Actually, I wonder whether $C=r^2$ or not.
The reason I'm thinking of these operator is to 'extend' a certain subset of $\mathbb{R}^2$ to a subset that somehow shares some properties with EW sets. That is, given a set $A$, we can extend it by iterating $r^2$ because $A \subseteq r^2(A) \subseteq r^4(A) \subseteq \cdots$. Therefore the 'maximally extended' one is $C(A)$=$\cup_i^\infty r^{2i}(A)$, and this satisfies $C(A)=r^2(C(A))$.
EW sets cannot be extended ($A=r^2(A)$), but this is not sufficient, as $r(A)$ has to be the same as $A$. So the problem is: for what set $A$ does its maximal extension $C(A)$ becomes EW set?


text:
Q: Stirling's approximation for $ \sum _{k=1}^{n/2} \frac{n!}{k!k!(n-2k)!}a^kb^kc^{n-2k}$ Suppose $a$, $b$, and $c$ are positive real numbers satisfying $a+b+c=1$. I am trying to use Stirling's approximation to obtain an asymptotic (computable) formula for
$$ \sum _{k=1}^{n/2} \frac{n!}{k!k!(n-2k)!}a^kb^kc^{n-2k}$$
as $n \to \infty$. If $n$ is odd then the upper limit of the sum should actually be $(n-1)/2$.
The problem is how to deal with the denominator, seeing as when $n\to \infty$, as far as I understand it, you can't really use asymptotic formulas for $k!$, since $k$, for instance, will take low values for some terms in the summation.

A: Because  $$ \sum _{k=1}^{n/2} \frac{n!}{k!k!(n-2k)!}a^kb^kc^{n-2k}=
c^n \sum _{k=1}^{n/2}{n\choose k}{n-k\choose n-2k} \left(\frac{ab}{c^2} \right)^k$$
we want to study the asymptotic behaviour of the sum with term
$$g(k) = {n\choose k}{n-k\choose n-2k} d^k \tag{1}$$
for $0<k<\frac{n}{2}$ and $d=a b /c^2>0$
The first difference $g_1(k)=g(k+1)-g(k)$ is
$$g_1(k)=g(k) \left(\frac{(n-2k)(n-2k-1)}{(k+1)^2} d  -1\right) \tag{2}$$
Equating to zero, we get the "critical" index which corresponds to the maximum of $g(k)$
$$k_0=n \frac{1}{2+1/\sqrt{d}} + \frac{\sqrt{d}+2}{4\sqrt{d}+2} + O(n^{-1}) \approx  n \frac{1}{2+1/\sqrt{d}} \tag{3} $$
In the same way, we can compute the second difference
$$ \frac{g_2(k)}{g(k)} = \frac{\left( n-2k\right) \,\left( n-2k-1\right) d}{{{\left( k+1\right) }^{2}}}-2+\frac{{{k}^{2}}}{d\,\left( n-2k+1\right) \,\left( n-2k+2\right) } \triangleq h(n,k,d) \tag{4}$$
Now, we want
$$S(n,d)\triangleq \sum_k g(k) \approx \int g(x) dx \tag{5}$$
To get the asymptotics we write the above integral in a form apt for Laplace method:
$$ \int e^{n f(x)} dx \tag{6}$$
with $$f(x)=\frac{\log(g(x))}{n}$$
Laplace method is not really justified her, because $f(x)$ depends on $n$... but we hope it works anyway ($f(x)$ depends rather weakly on $n$). Then we get
$$S(n,d) \approx \sqrt {\frac{2\pi}{n |f''(x_0)|}}  e^{n f(x_0)} = \sqrt {\frac{2\pi}{|g''(k_0)/g(k_0)|}}  g(k_0) \tag{7}$$
where the last equality comes from $$f''(x)=\frac{1}{n}\left( \frac{g g'' -(g´)^2 }{g^2}\right) \implies
f''(x_0)= \frac{1}{n}  \frac{g''(x_0)}{g(x_0)} $$
Now, using Stirling approximation:
$$ g(k)\approx \frac{n^n}{k^{2k}(n-2k)^{n-2k} 2 \pi } \sqrt{\frac{n}{k^2(n-2k)}} d^k \tag{8}$$
So finally
$$S(n,d)\approx \sqrt {\frac{2\pi}{|h(n,k_0,d)|} } \frac{n^n}{2 \pi k_0^{2k_0}(n-2k_0)^{n-2k_0}  } \sqrt{\frac{n}{k_0^2(n-2k_0)}} d^{k_0} \tag{9}$$
where $k_0$ is given by $(3)$ and $h(n,k_0,d)$ by $(4)$
This gives a good approximation, especially for large $n$.
Alternatively, $h(n,k_0,d)$ can be replaced by the first term of its asympotic expansion (in $n^{-1}$) :
$$h(n,k_0,d)\approx -\frac{2}{n}(4 \sqrt{d}+4+\frac{1}{\sqrt{d}}) \tag{10}$$
For some strange reason (fortuitous cancelling I guess), this approximation works numerically better.
Some numerical examples below - "exact" value corresponds to $\log(S(n,d))$. Approximation $1$ corresponds to $(9)$ (with $(3)$ and $(4)$), approx 2 uses $(10)$.
n        d       exact          approx 1        approx 2
--------------------------------------------------------
10      0.01    0.693147        1.130952        0.648864
50      0.01    7.145196        7.279219        7.137008
400     0.01    69.91077        69.92988        69.90983
10      0.50    6.994850        7.243550        7.010905
50      0.50    41.45789        41.51482        41.46112
400     0.50    348.9017        348.9091        348.9021
10      1.00    9.099744        9.362582        9.118624
50      1.00    52.25464        52.31559        52.25839
400     1.00    435.7325        435.7404        435.7329
10      10.0    17.92682        18.29466        17.91549
50      10.0    96.75546        96.86896        96.76006
400     10.0    792.6511        792.6670        792.6517

A: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\bbox[8px,#ffe]{\ds{\sum _{k = 1}^{n/2}{n! \over k!\,k!\pars{n - 2k}!}\,a^{k}b^{k}c^{n - 2k}}} =
-c^{n} +
\sum _{k = 0}^{\infty}{n! \over k!\,k!\pars{n - 2k}!}\,a^{k}b^{k}c^{n - 2k}
\\[5mm] & =
-c^{n} +
\sum _{k, p, q\ \in\ \mathbb{N}_{\ \geq\ 0}}
{n! \over k!\,p!\,q!}\,a^{k}b^{p}c^{q}\bracks{k + p + q = n}[p = k]
\\[5mm] & =
-c^{n} + \sum _{k, p, q\ \in\ \mathbb{N}_{\ \geq\ 0}}
{n \choose k,p,q}\,a^{k}b^{p}c^{q}
\bracks{k + p + q = n}\braces{\vphantom{\Large A}\bracks{z^{0}}z^{p - k}}
\\[5mm] & =
-c^{n} +
\bracks{z^{0}}\sum _{k, p, q\ \in\ \mathbb{N}_{\ \geq\ 0}}
{n \choose k,p,q}\pars{a \over z}^{k}\pars{bz}^{\,p}c^{q}
\bracks{k + p + q = n}
\\[5mm] & =
-c^{n} + \bracks{z^{0}}\pars{{a \over z} + bz + c}^{n} =
-c^{n} + \bracks{z^{0}}
{\pars{bz^{2} + cz + a}^{n} \over z^{n}}
\\[5mm] & =
-c^{n} + b^{n}
\bracks{z^{n}}\pars{z^{2} + {c \over b}\,z + {a \over b}}^{n} =
\bbx{\ds{-c^{n} + b^{n}
\bracks{z^{n}}\braces{\vphantom{\Large A}\pars{z - r_{-}}^{n}
\pars{z - r_{+}}^{n}}}}
\end{align}
where $\ds{\braces{r_{-},r_{+}}}$ are the roots of
$\ds{z^{2} + {c \over b}\,z + {a \over b} = 0}$. Namely,
$$
r_{\pm} = {-c \pm \,\mrm{sgn}\pars{b}\root{c^{2} - 4a^{2}} \over 2b}
$$

Further progress is available whenever particular values of $\ds{a,b,c}$ are known.


text:
Q: naming the result of a case when in hive I am very new to hive.  With my case statement, I am trying to create a variable called period that is zero during one time period and one during another, but I get a 'cannot recognize input' error.  How do I name the result of a case expression in hive?  It will name itself _c7 or something like that, but then I have problems using this _c7 variable in the next step (eof error).
CREATE TABLE abc.temp2 AS
            SELECT a.*,
case
when to_date(date)>='2016-07-01' and to_date(date)<'2017-07-01' then 0
when to_date(date)>='2017-07-01' and to_date(date)<'2018-07-01' then 1
else null
end **as period,**
array_contains(z,'abc') as abc,
array_contains(z,'def') as def
FROM abc.temp a;

A: Just put the case statement within a set of parenthesis.
CREATE TABLE abc.temp2 AS
            SELECT a.*,
(case
when to_date(date)>='2016-07-01' and to_date(date)<'2017-07-01' then 0
when to_date(date)>='2017-07-01' and to_date(date)<'2018-07-01' then 1
else null
end) as period,
array_contains(z,'abc') as abc,
array_contains(z,'def') as def
FROM abc.temp a;


text:
Q: Movie with evil killer robot, time travel, bent jail cell bars. (not terminator) I have a movie that is stuck in my head but I don't know what it is called.  It isn't high production, I can't find it on websites for finding a moive and it isn't in any list anywhere.
I remember one scene specifically.  The hero man is at the jail in a sherriff's office and the robot attacks.  The hero locks himself in a jail cell to keep away from the robot but then it slowly walks up and uses its clamp like hands to bend the bars on the door.  I think the hero then destroys it somehow in a blaze of gunfire.

A: The Time Guardian.

In the distant future, the human race nears extinction and a new race of beast-like creatures rule the earth. The few surviving people live in the City, a huge protected construction with the ability to travel in both space and time. The City travels back to our time to save humanity...


text:
Q: iphone development : how to deploy application to device but not run how i can deploy an application to iphone but not run the application. is it possible ?

A: If you build your app, then drag the binary and the provisioning profile into iTunes and sync your device, the app should install.

A: Just hit the stop sign after it installs it.


text:
Q: HSBC also pointed out it managed to increase
We commonly use the past perfect in reported clauses where the reporting verb is in the past. Cambridge Dictionary

I noticed it is common not to follow the above rule:

HSBC also pointed out it managed to increase market share in Hong Kong and Singapore. BBC

Why don't they use past perfect?

A: It comes down to a difference in emphasis and style.  "managed" sounds more aggressive/powerful/proactive than "had managed".
It emphasizes the fact that they did it, rather than that it has been done.
They want credit for it.  If they wanted to emphasize simply that it had already taken place, then "had managed" might be better.
Also, if you want to keep a busy person's attention, it is best to avoid unnecessary words.  The topic here seems to be business or finance, and the context is probably some kind of news reporting.  All of these demand a terse, practical style.  For instance, they didn't use "that it managed" because "that" is unnecessary to say or hear.

A: The rule referred to is about Back shifting and it is commonly followed in indirect speech to maintain tense harmony: main verb(reporting verb) in the past, all other verbs (reported verbs) must also be of past view point. However, there are situations where natural sequence of tense is more important. So we are taught not to change the tense if the main verb is in present/ future tense i.e, we are assuming ourselves at the point of time of the main verb(reporting) and use the tense of the verb as one would have used then.
However, Wikipedia in an article on indirect speech holds that it is also possible to use the natural sequence even though the main verb(reporting verb) is past or conditional.

*

*Batman said that he needs a special key for the batmobile.

Elucidating the view point, it goes on to say that this opinion is used in situations when the reporter reporting the words agrees that they are true or valid and the circumstances being expressed remain equally true now as it did when the 'Speech Act' took place.
The example is a newspaper report, not an indirect speech in the strictest sense of the term. The situation narrated equally holds good at the point of reporting; it should not be further distanced in time.
HSBC also POINTED OUT (that) it MANAGED to ... Singapore.
The use as above is proper and fit.


text:
Q: What is concise code for instantiating the same set of directory paths in subject-based analysis (Python)? For my research project, I am running a set of scripts on many different patients. Every new script that I write, I find myself repeating the same lines of code to create variables for the different directory paths associated with each subject. First, I create global variables associated with primary locations of each type of data. Then, I create subject-specific paths to reference the given patient's directories. Here is my code:
import argparse
from os import path
from sys import exit, platform

# check OS
LINUX = False
if platform == "darwin":
    NEU_DIR = "/Volumes/Shares/NEU"
elif platform == "linux":
    NEU_DIR = "/shares/NEU"
    LINUX = True
else:
    print(f"++ Unrecognized OS '{sys.platform}'; please run on ",
          "either linux or Mac OS ++")
    exit()

# global paths
PROJECTS_DIR = path.join(NEU_DIR, "Projects")
USERS_DIR = path.join(NEU_DIR, "Users")
IED_ANALYSIS_DIR = path.join(USERS_DIR, "ied_analysis")
MRI_DIR = path.join(PROJECTS_DIR, "MRI")
IED_DIR = path.join(PROJECTS_DIR, "iEEG", "IED_data")
FIGURES_DIR = path.join(USERS_DIR, "figures")
SCRIPTS_DIR = path.join(NEU_DIR,"Scripts_and_Parameters","scripts")
PYTHON_DIR = path.join(SCRIPTS_DIR,"IED_scripts","__files","__python")

if __name__ == "__main__":

    parser.add_argument("subj", help="subject code")
    parser.add_argument("-p", "--num_parc", default=600)
    parser.add_argument("-n", "--num_network", default=17)

    args = parser.parse_args()
    subj = args.subj
    n_parcs = int(args.num_parc); n_network = int(args.num_network)

    # subject-specific paths and directories
    subj_ied_dir = path.join(IED_DIR, subj)
    subj_mri_dir = path.join(MRI_DIR, subj)
    std141_surf_dir = path.join(subj_mri_dir, "surf", "xhemi",
                                "std141", "orig")
    general_dir = path.join(std141_surf_dir, "general")
    seq_dir = path.join(subj_ied_dir, "sequence_classification")
    sc_dir = path.join(subj_ied_dir,"sc", f"Schaefer_{n_parcs}P_{n_network}N")
    subj_raw_fc_dir = path.join(subj_ied_dir, "raw_fc")
    subj_figures_dir = path.join(FIGURES_DIR, subj,
                                 f"Schaefer_{n_parcs}P_{n_network}N")
    subj_analysis_dir = path.join(IED_ANALYSIS_DIR,
                                  f"Schaefer_{n_parcs}P_{n_network}N")

It feels sloppy and inefficient to  repeat these lines of code for every new processing script that I write. As a workaround, I tried writing a helper script with a function that creates all of these paths.
def make_subj_paths(subj, n_parcs=600, n_networks=17):

    from sys import platform
    from colors import Colors
    from os import path

    # check OS
    LINUX = False
    if platform == "darwin":
        NEU_DIR = "/Volumes/Shares/NEU"
    elif platform == "linux":
        NEU_DIR = "/shares/NEU"
        LINUX = True
    else:
        print(f"++ Unrecognized OS '{platform}'; please run on ",
              "either linux or Mac OS ++", Colors.END)
        exit()

    # general paths
    PROJECTS_DIR = path.join(NEU_DIR, "Projects")
    MRI_DIR = path.join(PROJECTS_DIR, "MRI")
    IED_DIR = path.join(PROJECTS_DIR, "iEEG", "IED_data")
    USERS_DIR = path.join(NEU_DIR, "Users")
    FIGURES_DIR = path.join(USERS_DIR, "figures")

    # create name based on parcels and networks
    dir_interest = f"Schaefer_{n_parcs}P_{n_networks}N"

    # create global directories for subject
    global subj_ied_dir
    subj_ied_dir = path.join(IED_DIR,subj)

    global sc_dir; global raw_fc_dir; global seq_dir; global source_loc_dir
    sc_dir = path.join(subj_ied_dir,"sc",dir_interest)
    raw_fc_dir = path.join(subj_ied_dir, "raw_fc")
    seq_dir = path.join(subj_ied_dir,"sequence_classification")
    source_loc_dir = path.join(subj_ied_dir,"source_localization",dir_interest)

    global subj_fig_dir; global subj_fig_parc_dir
    subj_fig_dir = path.join(FIGURES_DIR,subj)
    subj_fig_parc_dir = path.join(subj_fig_dir, dir_interest)

    global docs_dir; global align_dir; global std141_dir
    docs_dir = path.join(MRI_DIR, subj, "icEEG","__docs")
    align_dir = path.join(MRI_DIR, subj, "icEEG", "align_elec_alt")
    std141_dir = path.join(MRI_DIR, subj, "surf", "xhemi", "std141", "orig")

The intended effect of this code would be to create (as global variables) all of the directories I need for a given subject when I run make_subj_paths(subj, n_parcs=600, n_networks=17). This method still seems inefficient/sloppy due to creating global variables within a function. It also does not work. My other idea is to create a Subject Class that creates all of the paths for a given subject. For every new script I write, I can first create an instance of that class for the subject input. I am not sure if this idea makes sense and I don't know the best way to execute it. Any help would be appreciated! Thank you.