text:
Q: How can I represent current JSON scheme in Objective C? Everything messed up in my head. enum, NSObject, custom interface and so on...
All I need is to declare data type in Objective C for representing this JSON collection:
{
 "firstName": "John",
 "lastName" : "Smith",
 "age"      : 25,
 "address"  :
 {
     "streetAddress": "21 2nd Street",
     "city"         : "New York",
     "state"        : "NY",
     "postalCode"   : "10021"
 },
 "phoneNumber":
 [
     {
       "type"  : "home",
       "number": "212 555-1234"
     },
     {
       "type"  : "fax",
       "number": "646 555-4567"
     }
 ]

}
This is example from wikipedia JSON article. So I need an explanation about how can I put all this data in collection (or custom type or something else, I don't know).
For example I need 1000 instances of "phonebook" collection to store and change information about 1000 people. I need to know how can I do it.

A: example for firstname and address:
NSError* error;
NSDictionary* json = [NSJSONSerialization
                  JSONObjectWithData:data
                      options:kNilOptions
                      error:&error];

NSString *firstname = [json objectForKey:@"firstname"];
NSDictionary *address = [json objectForKey:@"address"];

more here: http://caydenliew.com/2011/11/json-in-ios-5/


text:
Q: Which procedure is more secure for encryption using Password and Seed I am designing a procedure and file format for the encryption application. I came to a point when I need to make a decision regarding the method/workflow of the encryption. I can't make up my mind on pros vs cons of using one approach over another.
Below is an overview of the format structure:

------------------------------------------
| File signature || fixed    | plain     |
|----------------||----------|-----------|
| Algorithm info || fixed    | plain     |
|----------------||----------|-----------|
| Seed           || fixed    | encrypted |
|----------------||----------|-----------|
| Data           || variable | encrypted |
|----------------||----------|-----------|
| CRC            || fixed    | encrypted |
------------------------------------------

Initially, I am going to use SHA-256 for a Hash function and AES-256 for an Encryption algorithm, but later it will be configurable, as the format suggests.
Proposed procedure for creating encrypted container:

*

*Hash(Password) => Key-Pass

*Generate random Seed

*Key-Pass XOR Seed => Key-Seeded

*Encrypt Seed with Key-Pass and store encrypted Seed

*Encrypt Data with Key-Seeded and store encrypted Data

*Encrypt CRC with Key-Seeded and store encrypted CRC

Questions
A. Do I gain anything from storing encrypted Seed and CRC? Would it be less secure if I store them not encrypted?
B. Is it more or less or no difference in security of using [ Hash(Password + Seed) ] for key generation rather than prosed [ Hash(Password) XOR Seed ] for the final key?
C. A concluding question from two questions above. Would it be better or worse to use the alternative procedure for creating encrypted container:

*

*Hash(Password + Seed) => Key

*Store unencrypted Seed

*Encrypt Data with Key and store encrypted Data

*Store unencrypted CRC (or encrypted)

I guess I would have to store unencrypted Seed in order to regenerate Key on reading back the encrypted content. CRC can be either encrypted or unencrypted.

A: Building your own cryptographic file formats is always tough (and risky).
Key generation
Instead of rolling your own key generation routine, please use PBKDF2 (PKCS #5 v2.0, RFC 2898) to generate your keys. This will require you to store the salt (what you are calling a seed) in an unencrypted format.
CRC Storage
If you're already at the level of using crypto, don't use CRC for integrity checks. You're already planning on using SHA256 elsewhere, use it for your integrity check as well. (I recommend hashing the unencrypted data and storing the hash unencrypted, though you could encrypt it to if you want.)

A: If you H(password) XOR with the seed, you need to store the seed encrypted, otherwise you will give away the hash. If you give away the hash, people can easily brute force it. That is why salt and a number of iterations is used on most protocols (like PBKDF2).
You should never save the CRC unencrypted since a CRC gives information about the data within the encrypted container. Same as with a hash as Eacwacer suggested. You are better off using a MAC (also generated with the key generator for instance).
As you asked for particular answers, I'll answer your questions below:
A: better store it encrypted
B: H(password | seed) is more secure
C: difficult to say, the XOR is wrong and the plain CRC too, but I would still go for the second one
And for the unasked one:
D: pretty please with sugar on top, use a well known password based encryption algorithm instead and use a cryptographically secure way of integrity checking

redpajama_set_name: RedPajamaStackExchange


text:
Q: Polymorphism? C++ vs Java Trying out polymorphism as a beginner. I think I am trying the same code in different languages, but the result is not the same :
C++
#include <iostream>
using namespace std;

class A {
    public:

    void whereami() {
        cout << "You're in A" << endl;
    }
};

class B : public A {
    public:

    void whereami() {
        cout << "You're in B" << endl;
    }
};

int main(int argc, char** argv) {
    A a;
    B b;
    a.whereami();
    b.whereami();
    A* c = new B();
    c->whereami();
    return 0;
}

Results :
You're in A
You're in B
You're in A

Java :
public class B extends A{

    void whereami() {
        System.out.println("You're in B");
    }

}

//and same for A without extends
//...

public static void main(String[] args) {
    A a = new A();
    a.whereami();
    B b = new B();
    b.whereami();
    A c = new B();
    c.whereami();
}

Results :
You're in A
You're in B
You're in B

Not sure if i'm doing something wrong, or this has to do with the languages themselves?

A: Use "virtual functions".
#include <iostream>
using namespace std;

class A {
    public:

    virtual void whereami() { // add keyword virtual here
        cout << "You're in A" << endl;
    }
};

class B : public A {
    public:

    void whereami() {
        cout << "You're in B" << endl;
    }
};

int main(int argc, char** argv) {
    A a;
    B b;
    a.whereami();
    b.whereami();
    A* c = new B();
    c->whereami();
    return 0;
}

In Java, all instance methods are virtual functions in default.

A: You need to read up about the virtual keyword for C++.  Without that qualifier, what you have are member functions in your objects. They don't follow the rules of polymorphism (dynamic binding). With the virtual qualifier you get methods, which use dynamic binding.  In Java, all instance functions are methods. You always get polymorphism.

A: It's a bit late to answer but use override keyword in derived classes to let compiler know that you are overriding.


text:
Q: Azure Function in Python that is on a time trigger get zip file from a url, unzip, then output file to blob container in Azure storage Here is my bindings in function.json
{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "mytimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 30 7 * * *"
    },

    {
      "type": "blob",
      "direction": "out",
      "name": "outputBlob",
      "path": "jarvisetl/nppesraw",
      "connection": "AzureWebJobsStorage"
    }
  ]
}

Here is my _init.py
import datetime
import logging
import azure.functions as func
import urllib.request
from io import BytesIO
from urllib.request import urlopen
from zipfile import ZipFile

def main(mytimer: func.TimerRequest) -> str:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()

    if mytimer.past_due:
        logging.info('The timer is past due!')

    logging.info('Python timer trigger function ran at %s', utc_timestamp)

    zipurl = 'https://download.file.com'
    with urlopen(zipurl) as zipresp:
        with ZipFile(BytesIO(zipresp.read())) as zfile:
            zfile.extractall(outputblob)

My biggest issue is I am getting an error that "outputblob" is declared in the function.json but not apparent in the python script. I am not sure where "outputblob" is truly suppose to go in the Python script.

A: Update:
import datetime
import logging

import azure.functions as func

def main(mytimer: func.TimerRequest,outputblob: func.Out[func.InputStream]) -> None:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()
    testdata = 'this is test.'
    outputblob.set(testdata)
    if mytimer.past_due:
        logging.info('The timer is past due!')

    logging.info('Python timer trigger function ran at %s', utc_timestamp)

Original Answer:
Below is a simple example:
function.json
{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "route": "{test}",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    },
    {
      "name": "outputblob",
      "type": "blob",
      "path": "test1/{test}.txt",
      "connection": "str",
      "direction": "out"
    }
  ]
}

init.py
import logging

import azure.functions as func

def main(req: func.HttpRequest,outputblob: func.Out[func.InputStream],) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    testdata = 'this is test.'
    outputblob.set(testdata)
    name = req.params.get('name')
    return func.HttpResponse(f"This is output binding test, "+name)


text:
Q: No 'Access-Control-Allow-Origin' header is present (CROS) From html page using javascript ajax call am trying to call Login_check api (REST webservice) but am getting error as below.
XMLHttpRequest cannot load
http://184.30.53.119:8080/Automation_test1/TRTS/login/Login_Check. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

A: JavaScript has a same-origin policy. Which means it cannot request pages on other domains. You have a couple of options to do this, use JSONP or have a php script that you call to query the api.
More information: Working With and Around the Same-Origin Policy


text:
Q: AudioUnit: access ComponentKernel properties from CocoaView I would like to access my AudioUnit Component Kernel members from an action method defined in the cocoa view of my AudioUnit Component :
- (IBAction)iaParam1Changed:(id)sender {
    float floatValue = [sender floatValue];
    NSAssert(AUParameterSet(mParameterListener, sender, &mParameter[0], (Float32)floatValue, 0) == noErr, @"[MyAudioUnit_CocoaView iaParam1Changed:] AUParameterSet()");
    if (sender == uiParam1Slider) {
        [uiParam1TextField setFloatValue:floatValue];
    } else {
        [uiParam1Slider setFloatValue:floatValue];
    }
}

(For instance, interact with stats computed on the signal...). But I don't know how to use the AudioUnit mAU member of the Cocoa View to get the Kernel (and then its members)... How would you do that? (Maybe i'm not supposed to do that?) Thanks.

A: *

*Define an AudioUnit custom property

*Access it from the cocoa view using AudioUnitGetProperty

*Reimplement the AUEffectBase::GetProperty method

*From GetProperty, access the kernels using the GetKernel(...) method

*Enjoy some tee


text:
Q: Calling different extent of randomness of arc4random in Swift? This might be rather stupid question. I would like to know if different nuances/extent of randomness would be possible using arc4random_uniform in Swift. Here's an example:
let number = arc4random_uniform(10) + 1
print(number)

In this case, a number will be printed randomly from 1 to 10. But is there a way that I can repeat the random result, 2 to 3 times? The result would be something like this:
1, 1, 6, 6, 6, 3, 3, 8, 8, 9, 9, 9 ...

// 1) Randomly selected and 2) repeated 2 to 3 times randomly.

Perhaps I might use two arc4random_uniform functions together, but cannot express them properly. Would be much appreciated if you could give me some suggestions. <3

A: With regards to the nuances of random number generators: have a look at GKRandomSource.
What you're doing here is not really making something less random, or modifying the parameters in the random number generator. You're simply applying an operation (with one random parameter) to a collection of random integers.
extension Collection {

    func duplicateItemsRandomly(range: CountableClosedRange<Int>) -> [Element] {

        return self.reduce(into: [Element](), { (acc, element) in

            let distance = UInt32(range.upperBound - range.lowerBound + 1)
            let count = Int(arc4random_uniform(distance) + UInt32(range.lowerBound))
            let result = Array.init(repeating: element, count: count)
            acc.append(contentsOf: result)
        })
    }
}

let sequence = [1, 6, 3, 8, 9]
sequence.duplicateItemsRandomly(range: 2...3)
// [1, 1, 6, 6, 6, 3, 3, 3, 8, 8, 8, 9, 9, 9]

P.S: If you're writing this code in Swift 4.2, please use Int.random(in:).

A: In order to do this, you will need to generate two values: your random value and a repeatCount.  Also, you'll need to remember both of those values so that you can repeat the value.  You can do this with a custom class:
class RandomWithRepeats {
    var range: ClosedRange<Int>
    var repeatRange: ClosedRange<Int>
    var repeatCount = 0
    var value = 0

    init(range: ClosedRange<Int>, repeatRange: ClosedRange<Int>) {
        self.range = range
        self.repeatRange = repeatRange
    }

    // generate a random number in a range
    // Just use Int.random(in:) with Swift 4.2 and later
    func random(in range: ClosedRange<Int>) -> Int {
        return Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound + 1))) + range.lowerBound
    }

    func nextValue() -> Int {
        // if repeatCount is 0, its time to generate a new value and
        // a new repeatCount
        if repeatCount == 0 {
            // For Swift 4.2, just use Int.random(in:) instead
            value = self.random(in: range)
            repeatCount = self.random(in: repeatRange)
        }

        repeatCount -= 1
        return value
    }
}

Example:
let rand = RandomWithRepeats(range: 1...10, repeatRange: 2...3)

// generate 20 random repeated numbers
for _ in 1...20
{
    print(rand.nextValue(), terminator: " ")
}

6 6 6 8 8 8 10 10 10 2 2 9 9 5 5 8 8 8 5 5

A: I'd suggest a custom Sequence:
class RepeatingRandomSequence : Sequence {
    let rangeLow, rangeSpan : UInt32
    let repeatLow, repeatSpan : UInt32

    init(range:Range<UInt32>, count:Range<UInt32>) {
        rangeLow = range.lowerBound
        rangeSpan = range.upperBound - range.lowerBound + 1
        repeatLow = count.lowerBound
        repeatSpan = count.upperBound - count.lowerBound + 1
    }

    func makeIterator() -> AnyIterator<UInt32> {
        var count : UInt32 = 0
        var value : UInt32 = 0

        return AnyIterator {
            if(count <= 0) {
                count = arc4random_uniform(self.repeatSpan) + self.repeatLow
                value = arc4random_uniform(self.rangeSpan) + self.rangeLow
            }

            defer { count = count - 1 }

            return value
        }
    }
}

let sequence = RepeatingRandomSequence(range: 0..<10, count: 2..<3)
let randoms = sequence.makeIterator()

Note that the iterator, randoms now generates an endless sequence of random numbers using randoms.next()  Since the sequence is endless, many things aren't particularly useful, like sort, map, etc.  You could however use it like:
for value in random {
    print(value)
    if(value == 9) {  // or any other termination condition
        break
    }
}

Or more conventionally, as:
(0..<10).forEach { _ in
    print(String(describing: random.next()))
}


text:
Q: Difference between MySQL IS NOT NULL and != '' Is there any difference between MySQL
IF (myText IS NOT NULL) THEN

and
IF (myText != '') THEN

A: Yes there is a difference.
In simple words, myText IS NOT NULL specifies that myText is having some value which could be '' too.
Where as myText != '' specifies that it returns TRUE, if myText does NOT contain an empty string.

A: Yes there is a big difference between a NULL value and a blank/empty value.
Here's one resource that describes the differences.
When myText IS NULL:

*

*myText IS NOT NULL evaluates to FALSE

*myText != '' evaluates to NULL (which essentially behaves the same as FALSE would in this specific case you wrote)

However, you should not get into the habit of treating them the same, since most of the time they will behave differently: For example:
Assume you have a table tbl:
id   text
1    NULL
2
3    abc

Note: 1 contains a NULL value, and 2 contains an empty string ('').
If you run the following query:
SELECT * FROM tbl WHERE text != ''

... it will return record 3.
If you run the following query:
SELECT * FROM tbl WHERE text IS NOT NULL

... it will return records 2 and 3.

A: There is a difference. If the default value of a column is "NULL", then if no data has been set for a field, it is truly null. However, if the value of a field has been updated as '', it is not NULL, rather it is empty.
See here for more information Link


text:
Q: How to Override JQUERY-UI Dialog I found this link : https://github.com/handsontable/handsontable/issues/1480
(function($) {
    $.widget("ui.dialog", $.ui.dialog, {
        console.log("override");
        _allowInteraction: function(event) {
            if(this._super(event)) {
                return true;
            }
            return $(event.target).hasClass('copyPaste');
        },
    });
})(jQuery);

I try to put that block code in my $(document).ready(), and I've put that into separated js file, right after jquery.min.js and jquery-ui.js.
This is the snippet :
$(document).ready(function () {
    /**
     * overriding jqueryui dialog
     */
    (function($) {
        $.widget("ui.dialog", $.ui.dialog, {
            _allowInteraction: function(event) {
                console.log("override");
                if(this._super(event)) {
                    return true;
                }
                return $(event.target).hasClass('copyPaste');
            },
        });
    })(jQuery);
});

But, after I refresh my browser, and try to open the jquery dialog, browser console not logging the "override" string.
So I guess my override code didn't performed well (or not at all)
So how can I override my jquery-ui dialog, with that code, so that my jquery-ui dialog will be affected with that code?


text:
Q: Trying to run an existing application and getting (Psych::SyntaxError) The application is running on the a web server properly and I tried to run it locally and I am getting these errors.
Any idea what the issue might be? I am new to Ruby, so please excuse me if this is a simple question
..../.rvm/rubies/ruby-2.1.3/lib/ruby/2.1.0/psych.rb:370:in `parse': (<unknown>): could not find expected ':' while scanning a simple key at line 18 column 3 (Psych::SyntaxError)
from ..../.rvm/rubies/ruby-2.1.3/lib/ruby/2.1.0/psych.rb:370:in `parse_stream'
from ..../.rvm/rubies/ruby-2.1.3/lib/ruby/2.1.0/psych.rb:318:in `parse'
from ..../.rvm/rubies/ruby-2.1.3/lib/ruby/2.1.0/psych.rb:245:in `load'
from ..../.rvm/gems/ruby-2.1.3/gems/railties-3.2.3/lib/rails/application/configuration.rb:115:in `database_configuration'
from ..../.rvm/gems/ruby-2.1.3/gems/activerecord-3.2.3/lib/active_record/railtie.rb:75:in `block (2 levels) in <class:Railtie>'
from ..../.rvm/gems/ruby-2.1.3/gems/activesupport-3.2.3/lib/active_support/lazy_load_hooks.rb:36:in `instance_eval'
from ..../.rvm/gems/ruby-2.1.3/gems/activesupport-3.2.3/lib/active_support/lazy_load_hooks.rb:36:in `execute_hook'
from ..../.rvm/gems/ruby-2.1.3/gems/activesupport-3.2.3/lib/active_support/lazy_load_hooks.rb:26:in `block in on_load'
from ..../.rvm/gems/ruby-2.1.3/gems/activesupport-3.2.3/lib/active_support/lazy_load_hooks.rb:25:in `each'
from ..../.rvm/gems/ruby-2.1.3/gems/activesupport-3.2.3/lib/active_support/lazy_load_hooks.rb:25:in `on_load'
from ..../.rvm/gems/ruby-2.1.3/gems/activerecord-3.2.3/lib/active_record/railtie.rb:74:in `block in <class:Railtie>'
from ..../.rvm/gems/ruby-2.1.3/gems/railties-3.2.3/lib/rails/initializable.rb:30:in `instance_exec'
from ..../.rvm/gems/ruby-2.1.3/gems/railties-3.2.3/lib/rails/initializable.rb:30:in `run'
from ..../.rvm/gems/ruby-2.1.3/gems/railties-3.2.3/lib/rails/initializable.rb:55:in `block in run_initializers'
from ..../.rvm/gems/ruby-2.1.3/gems/railties-3.2.3/lib/rails/initializable.rb:54:in `each'
from ..../.rvm/gems/ruby-2.1.3/gems/railties-3.2.3/lib/rails/initializable.rb:54:in `run_initializers'
from ..../.rvm/gems/ruby-2.1.3/gems/railties-3.2.3/lib/rails/application.rb:136:in `initialize!'
from ..../.rvm/gems/ruby-2.1.3/gems/railties-3.2.3/lib/rails/railtie/configurable.rb:30:in `method_missing'
from ..../appname/config/environment.rb:5:in `<top (required)>'
from ..../.rvm/gems/ruby-2.1.3/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:251:in `require'
from ..../.rvm/gems/ruby-2.1.3/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:251:in `block in require'
from ..../.rvm/gems/ruby-2.1.3/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:236:in `load_dependency'
from ..../.rvm/gems/ruby-2.1.3/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:251:in `require'
from ..../appname/config.ru:4:in `block in <main>'
from ..../.rvm/gems/ruby-2.1.3/gems/rack-1.4.1/lib/rack/builder.rb:51:in `instance_eval'
from ..../.rvm/gems/ruby-2.1.3/gems/rack-1.4.1/lib/rack/builder.rb:51:in `initialize'
from ..../appname/config.ru:1:in `new'
from ..../appname/config.ru:1:in `<main>'
from ..../.rvm/gems/ruby-2.1.3/gems/rack-1.4.1/lib/rack/builder.rb:40:in `eval'
from ..../.rvm/gems/ruby-2.1.3/gems/rack-1.4.1/lib/rack/builder.rb:40:in `parse_file'
from ..../.rvm/gems/ruby-2.1.3/gems/rack-1.4.1/lib/rack/server.rb:200:in `app'
from ..../.rvm/gems/ruby-2.1.3/gems/railties-3.2.3/lib/rails/commands/server.rb:46:in `app'
from ..../.rvm/gems/ruby-2.1.3/gems/rack-1.4.1/lib/rack/server.rb:301:in `wrapped_app'
from .../.rvm/gems/ruby-2.1.3/gems/rack-1.4.1/lib/rack/server.rb:252:in `start'
from .../.rvm/gems/ruby-2.1.3/gems/railties-3.2.3/lib/rails/commands/server.rb:70:in `start'
from ../.rvm/gems/ruby-2.1.3/gems/railties-3.2.3/lib/rails/commands.rb:55:in `block in <top (required)>'
from .../.rvm/gems/ruby-2.1.3/gems/railties-3.2.3/lib/rails/commands.rb:50:in `tap'
from .../.rvm/gems/ruby-2.1.3/gems/railties-3.2.3/lib/rails/commands.rb:50:in `<top (required)>'
from script/rails:6:in `require'

A: I think that vendors are not found.
Try to run bundle command to install it on your local machine.

A: I don't know if this is helpful but I also get the following Warning
DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from  at .../appname/Rakefile:7)


text: Q: iwconfig command not found on wsl kali-linux I am trying to run iwconfig command on wsl terminal but I keep on getting error command not found I tried reinstalling wireless-tools and also runned the command as root su -c "iwconfig" but both methods didn't work. Why is this happening? Can't you run the command on wsl? Does it have to be on a linux host machine or a virtual machine or is there something I have to do to make this work?


text:
Q: Create Teams one-on-one Chat via Service Principal I'd like to use this api: https://learn.microsoft.com/en-us/graph/api/chat-post?view=graph-rest-1.0&tabs=http
To create a Teams one-on-one Chat. However I see that under "Permission type". "Application" is not supported.
Does this mean service principals or azure ad applications can't create chats? I would have thought that under the applications api permissions I can just add "Delegated"?
However when I try this via postman. I get an error saying Access token validation failure. Invalid audience., only when I use the token from the service principal. But, if I use my own access token from the graph explorer it works.
So now I'm wondering if it's even possible with a service principal? In the end I'd like to know how to do this with postman, and eventually powershell.

A: Currently create chat using application permission is not supported. You need to use the delegated permissions to create a chat inside teams. This is by design. when you use graph explorer Auth token the token consists of delegated permissions. Could you please check the permissions using jwt.io for the auth token.


text:
Q: How to know if an e-mail was received or sent? I made a VBA script to save selected e-mails onto different folders.
Is there a way, without user input, to know if an e-mail was received or sent?

A: You can check out the Sender-related properties of the email item. The MailItem.Sender property which returns or sets an AddressEntry object that corresponds to the user of the account from which the MailItem is sent. Checking that property and comparing to the Accounts configured in Outlook you may conclude where the message comes from. The Accounts collection object contains a set of Account objects representing the accounts available for the current profile. The purpose of the Accounts collection object and the Account object is to allow the enumeration of Account objects in a given profile, the identification of the type of an Account, and the use of a specific Account object to send mail.

A: The only more or less reliable way is to check if MailItem.ReceivedByXYZ properties (such as ReceivedByEntryID) are set. They seem to be only present on the received messages. But I have seen cases where it  was present on the sent messages.
You can check first if the parent folder is Inbox or Sent Items by comparing the current folder's entry id with the entry id of a folder received from Store.GetDefaultFolder using Namespace.CompareEntryIDs. If that fails, check on a ReceivedByXYZ  property.


text:
Q: NullpointerException desde una Clase (Fragmento) a la hora de llamar un método en otra Clase Estoy realizando una aplicación en Android que consta de una clase MainActivity, una clase llamada DatabaseManager y otra clase llamada Fragmento1
Estoy trabajando con un Tabhost de 3 pestañas, cada pestaña es representada por una clase(Fragmento1, Fragmento2, Fragmento3)
la clase Fragmento1 infla el layout xml del tab 1 y asi sucesivamente.
Desde el fragmento 1 deseo realizar la inserción de un registro a una base de datos, la inserción la realizo mediante un método que se encuentra en la clase Fragmento1 llamada guardarUsuario(); este método recoge todos los datos para luego enviarlos por parámetros a un método llamado insertar(); de la clase DataBaseManager
pero a la hora de llamar al método me indica NullPointer Exception, ¿Qué puede estar pasando?
public class Fragmento1 extends Fragment implements View.OnClickListener {

    private SimpleCursorAdapter adapter;
    private DataBase manager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.tab1, container, false);
        Resources res = getResources();
        Context context = getContext();

        final Spinner spinner = (Spinner) v.findViewById(R.id.spGender);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context,
                R.array.genders, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        spinner.setAdapter(adapter);

        Button btnGuardar = (Button) v.findViewById(R.id.btnGuardar);
        btnGuardar.setOnClickListener(this);

        return v;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.btnGuardar:
                guardarUsuario();

                break;

        }
    }

    public void guardarUsuario() {

        String nombre, apellido, sexo;
        int edad=0, estatura=0;

        EditText nombreId = (EditText) getView().findViewById(R.id.campoNombre);
        EditText apellidoId = (EditText) getView().findViewById(R.id.campoApellido);
        EditText edadId = (EditText) getView().findViewById(R.id.campoEdad);
        Spinner sexoId = (Spinner) getView().findViewById(R.id.spGender);
        EditText estaturaId = (EditText) getView().findViewById(R.id.campoEstatura);

        if(nombreId.length()==0){
            nombre = null;
        }else{
            nombre = nombreId.getText().toString();
        }

        apellido = apellidoId.getText().toString();

        String valor = edadId.getText().toString();
        if(edadId.length()>0){
            edad = Integer.valueOf(valor);
        }

        sexo = sexoId.getSelectedItem().toString();

        String valor2 = estaturaId.getText().toString();
        if(estaturaId.length()>0){
            estatura = Integer.valueOf(valor2);
        }

              manager.insertar(nombre,apellido,edad,sexo,estatura);

}

A: Estas declarando una variable de tipo "DatabaseManager" :
private DataBase manager;

Pero no esta siendo inicializada en ningun lugar, por lo tanto, al llamar el método insertar de la clase DatabaseManager, lo estas realizando en una instancia con valor null.
manager.insertar(nombre,apellido,edad,sexo,estatura);

Inicializa la clase antes de llamar el método,
Por ejemplo de esta forma:
manager = new DataBase(getActivity ());
manager.insertar(nombre,apellido,edad,sexo,estatura);


text:
Q: How to measure resistance I have a project to build heating element using silver ink.
My specification is the heating element must be in range 2 to 2.6ohm
I will design the circuit for the heating element, but have a problem
how to theoretically measure the resistance of the circuit(before send to print house).
Based on reference on this website
http://circuitcalculator.com/wordpress/2006/06/14/conductive-ink-traces/
the resistance can be measure as below
Resistance = Sheet_Resistivity*(Length/Width)*(Ref_Thickness/Thickness)
In my case,
Sheet Resistivity = 10miliohms/square,
Ref_Thickness = 1mil(0.025mm)
Thickness = 1mil(0.025mm)
1) Based on the quotation, if I have 50mm x 50mm & another one is 10mm x 10mm
silver ink with same thickness, the ohm will be the same which is 10miliohms.
Is it logic?
2) Another question is, how to measure the resistance if I design a complicated
circuit as per attached image? In the image, 1box considered as 1mm x 1mm
Point "A" and point "B" will be connected to battery(+ve & -ve).
Blue color indicate the silver ink

Your advice and explanation will be very helpfull. Thank you.

A:

*

*Based on the quotation, if I have 50mm x 50mm & another one is 10mm x 10mm
  silver ink with same thickness, the ohm will be the same which is 10miliohms.
  Is it logic?

Yes. The increased width and increased length counter each other, resulting in the same resistance for both.

*Another question is, how to measure the resistance if I design a complicated
  circuit as per attached image?

Fill it with squares, and do the calculations for resistances in parallel and series as normal. You won't get an exact number, but you should be in the ballpark.

A: As well as Ignacio's answer on the straight bits, you can consult "Handbook of Electronic Package Design, By Michael Pecht" which has formulas used for correcting for the corner geometry when you use a serpentine (meander) pattern.


text:
Q: Loop through users folders and delete a folder How can I loop through the /home directory for each user and delete a folder? It will be a common one called /home/$user/.quarentine.

A: In a single line:
for user in $(ls /home); do rm -Rf /home/${user}/.quarentine; done

A: Like this:
#!/bin/bash
#Get the list of users
USERS=`ls -l /home|grep "^d"|awk '{print $NF}'`
#Loop for each user and delete the files
for i in $USERS
do
  rm -rf /home/$i/.quarentine
done


text:
Q: How to update Sqlmap with git? I'm try to update my sqlmap in the Linux. But I get the error like this :

error pathspec did not match any file s known to git.

I'm just a freshman, and I am not too familiar with Git.
How can I get past this error?

A: It depends on the exact git command you are using.
For instance, if you checkout a branch you have not yet fetched from your remote repo, try git fetch first.
Then git checkout yourBranch: if origin/yourBranch exists, it will work.
If you checkout a file, pay attention to the case: it can be case-sensitive.

I can't checkout .fatal : You are on a branch yet to be born .

Make sure you have added and make at least one commit.
git add .
git commit -m "first commit"

A: is git
git add
git commit -m

is not git   Direct
sqlmap --update


text:
Q: IMG SRC json.parse results need cleaned up I am using an old script I had from a previous project. I wanted to try it out before making an attempt to just do it via fetch. I thought i would get lucky! I am still new to XMLHTTPRequest and fetch and is another reason I just wanted to try and figure it out using the old script first.
Anyway, when the page loads status is 200 for banners.php page. My Response Preview however has the URL with added characters ...
https: \ / \ /www.f-cdn.com \ /assets \ /img \ /fl-logo-c555380d.svg
The image is not displaying on the page. I just see the box for it.
However the console is giving me a 404 status telling me that the javascript is undefined. But I believe it is defined. This is line 137
document.getElementById("goldads").innerHTML =('<\/a>');

Console
oneArrayItem http://...game.js:137:11
bannerOne/xmlhttp.onreadystatechange http://...game.js:140:1
(Async: EventHandlerNonNull) bannerOne http://...game.js:121:1
<anonymous> http://...game.js:87:1

The url for the image is suppose to be https://www.f-cdn.com/assets/img/fl-logo-c555380d.svg
I'm using that image as a test. It's just some image I picked the matches the size image I was looking for.
myscript.js
function bannerOne() {
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
 {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
var jsonData = JSON.parse(xmlhttp.responseText) // json.parse returns array
    {
        var img = document.createElement('img'); // element to hold image
//      var img = document.createElement('goldBanner'); // element to hold image

        console.log(jsonData);
function oneArrayItem() {
  var firstArrayItem = jsonData[0];{  // banner_link , banner_image_url
    link =(firstArrayItem.banner_link);      // link is not yet defined in database
    src =(firstArrayItem.banner_image_url);
//  document.getElementById("goldads").innerHTML =('<\/a>');
//  document.getElementById("goldads").innerHTML =('<\/a>');
    document.getElementById("goldads").innerHTML =('<\/a>');
  }
}
oneArrayItem()
                                                 }
      }
  }
xmlhttp.open("GET","../php/goldbanners/banners.php",true);
xmlhttp.send();
}

bannerOne()

Before I try and change it to fetch can you tell me where the error is in this code so I understand it better?
mypage.html

banners.php
<?php
session_start();
if(empty($_SESSION['userid']))
{
    header("Location: ../login/index.php");
}
include('../../login/database.php');

if (isset($_SESSION['userid'])) {

try {
$db = DB();

$stmt = $db->prepare("SELECT gold FROM usersystem ORDER BY RAND() LIMIT 1");
//$stmt->execute([$userid]);
$stmt->execute();
$goldBanner = $stmt->fetchColumn();

}
catch(PDOException $e)
{
    $pdo = null;  /*** close the database connection ***/
    echo $e->getMessage();
}

echo json_encode($goldBanner);

}
// unexpected end of file error !!! Fix it
?>


text:
Q: CollectionView scrollbars visibility CollectionView VerticalScrollBarVisibility="Always" does not imply a scrollbar which is always visible (as the enum name seems to state), rather (this is on a windows 10 machine), the scrollbar is visible only by hoovering mouse where it eventually will be visible.
Why is this not working somewhat like e.g. Microsoft Teams (Version 1.5.00.9163 in my case)?
(Where it is visible if the mouse is hoovered over anywhere in the control/view (and even growing in size when mouse hoovers over the then visible scrollbar)


text:
Q: How valuable is the RSA private key in kubernetes for an attacker? I am currently playing with kubernetes and read about a security issue (cve-2018-18264) where it was possible to gain unauthorized access to the dashboards secrets (the certificate plus the RSA private key).
Now I am wondering how valuable the RSA private key and the certificate is for an attacker especially in kubernetes? Can someone tell me about?
How about if Diffie-Hellman is used for key exchange?

A: As said on CVE-2018-18264: Kubernetes Dashboard TLS Certificate Leak.

Description
Kubernetes Dashboard before 1.10.1 allows attackers to bypass authentication and use Dashboard's Service Account for reading secrets within the cluster.

So if You deployed an app, lets take this Mysql Wordpress deployment, attacker might gain access to your DB login and password.
Also if You are using secrets as authentication between application, attacker might use MITM attack.
DH is no longer considered as secure.

...
  However, research published in October 2015 suggests that the parameters in use for many DH Internet applications at that time are not strong enough to prevent compromise by very well-funded attackers, such as the security services of large governments.[3]
Paper talking about this is Imperfect Forward Secrecy: How Diffie-Hellman Fails in Practice


text:
Q: Fastest way of finding common elements between two list of lists in python I have a list as follows.
mylist =
[
   [
      [
         "chocolate_pudding",
         920.8000000000001
      ],
      [
         "caramel_pudding",
         345.59999999999997
      ],
      [
         "pudding",
         248.0
      ],
      [
         "banana_pudding",
         27.599999999999998
      ]
   ],
   [
      [
         "biscuits",
         190.8
      ],
      [
         "chocolates",
         33.599999999999994
      ],
      [
         "chocolate_pudding",
         920.8000000000001
      ]
   ],
   [
      [
         "tiramusu",
         145.8
      ]
   ],
   [
      [
         "cakes",
         139.29999999999998
      ]
   ],
   [
      [
         "butter_cakes",
         133.0
      ]
   ],
   [
      [
         "chocolate_pudding",
         920.8000000000001
      ]
   ]
]

I want to find elements that appears more than one time in the lists (e.g., ["chocolate_pudding", 920.8000000000001]) and want to remove the repeating ones, while keeping the very first entry.
So, my output should look like below.
mylist =
[
   [
      [
         "chocolate_pudding",
         920.8000000000001
      ],
      [
         "caramel_pudding",
         345.59999999999997
      ],
      [
         "pudding",
         248.0
      ],
      [
         "banana_pudding",
         27.599999999999998
      ]
   ],
   [
      [
         "biscuits",
         190.8
      ],
      [
         "chocolates",
         33.599999999999994
      ]
   ],
   [
      [
         "tiramusu",
         145.8
      ]
   ],
   [
      [
         "cakes",
         139.29999999999998
      ]
   ],
   [
      [
         "butter_cakes",
         133.0
      ]
   ]
]

The code I have been trying is as follows.
mylist_copy = mylist

for item in mylist:
    myindex = mylist.index(item)
    #print(item)

    for single_item in item:
        #print(single_item)
        for item_copy in mylist_copy:
            if mylist_copy.index(item_copy) != myindex:
                if single_item in item_copy:
                    print(single_item)

Since, it has many for loops I want an efficient way of doing it. Note: I also tried;
mylist_copy = mylist

for item in mylist:
    myindex = mylist.index(item)
    for item_copy in mylist_copy:
          if mylist_copy.index(item_copy) != myindex:
                print(set(item).intersection(item_copy))

However, intersection does not support lists.
Is there an easy and fast way of doing this in python?

A: With set() object and preserving the order of sublists:
mylist = [[["chocolate_pudding", 920.8000000000001], ["caramel_pudding", 345.59999999999997],
          ["pudding", 248.0], ["banana_pudding", 27.599999999999998]], [["biscuits", 190.8],
          ["chocolates", 33.599999999999994], ["chocolate_pudding", 920.8000000000001]],
          [["tiramusu", 145.8]], [["cakes", 139.29999999999998]], [["butter_cakes", 133.0]],
          [["chocolate_pudding", 920.8000000000001]]]

result, foods = [], set()
for sub_l in mylist:
    new_sublist = []
    for i in sub_l:
        if i[0] not in foods:     # on the 1st occurrence of `foodstuff` name
            new_sublist.append(i)
            foods.add(i[0])       # add `foodstuff` into set of unique foods
    if new_sublist: result.append(new_sublist)

print(result)

The output:
[[['chocolate_pudding', 920.8000000000001], ['caramel_pudding', 345.59999999999997], ['pudding', 248.0], ['banana_pudding', 27.599999999999998]], [['biscuits', 190.8], ['chocolates', 33.599999999999994]], [['tiramusu', 145.8]], [['cakes', 139.29999999999998]], [['butter_cakes', 133.0]]]

A: You can unroll the inner lists and put them all in a set. Sets may not contain duplicates, so you don't even have to check for it, the set does it for you in very little time. Only caveat is that a set can not contain a list, so they need to be turned into tuples first. If you are fine with these two type conversion, it can be done in a simple set comprehension and should be reasonably fast:
no_duplicates = {tuple(inner) for outer in mylist for inner in outer}

Or you change the types back afterwards:
no_dupe_lists = list(map(list, no_duplicates))

You dind't ask for this, but if you want to copy a list, you have to use one of the proper copy techniques: mylist_copy = list(mylist) or mylist_copy = mylist[:] or mylist_copy = [element for element in mylist], with the first one being the recomended one.
Since your list contains nested lists, those need to be copied as well though:
mylist_copy = [[list(inner) for inner in outer] for outer in mylist]

A: Once a great person said, take only what you want, why delete? Now two person said :
mylist = [[["chocolate_pudding", 920.8000000000001], ["caramel_pudding", 345.59999999999997],
          ["pudding", 248.0], ["banana_pudding", 27.599999999999998]], [["biscuits", 190.8],
          ["chocolates", 33.599999999999994], ["chocolate_pudding", 920.8000000000001]],
          [["tiramusu", 145.8]], [["cakes", 139.29999999999998]], [["butter_cakes", 133.0]],
          [["chocolate_pudding", 920.8000000000001]]]

result=[]
track=[]
for i in mylist:
    sublist=[]
    for k in i:
        if k not in track:
            track.append(k)
            sublist.append(k)

    if sublist:

        result.append(sublist)

print(result)

output:
[[['chocolate_pudding', 920.8000000000001], ['caramel_pudding', 345.59999999999997], ['pudding', 248.0], ['banana_pudding', 27.599999999999998]], [['biscuits', 190.8], ['chocolates', 33.599999999999994]], [['tiramusu', 145.8]], [['cakes', 139.29999999999998]], [['butter_cakes', 133.0]]]


text:
Q: Dynamic Firebase Connection to the same app Can My App Connect to different Firebase Project Without register the app in the project (the package name and SHA-1) ? and still able to use firestore, storage and google sign in ?

A: Yes you can. But I believe the app should be connected via SHA-1 as you said to one project, and then you can add other projects without registration.
Implementation guide for those who might be interested in it. This article is also a good resource to show how to connect, database, authentication and storage. Multiple Firebase Projects One App
Initialize the secondary project, the one not connected to the Firebase project in the class that extends Application but any activity should work.
FirebaseOptions issuetracker = new FirebaseOptions.Builder()
            .setProjectId("project id")
            .setApplicationId("")
            .setApiKey("")
            .setDatabaseUrl("")
            .build();

    FirebaseApp.initializeApp(this, issuetracker, "issues");

Then where you want to interact with it
FirebaseApp secondary = FirebaseApp.getInstance("issues");
DatabaseReference ref = FirebaseDatabase.getInstance(secondary).getReference();

"issues" is any name you give for the secondary project. Can be anything.


text:
Q: Why $dt/t$ in Mellin transform I've noticed that often when people write the Gamma function $\Gamma(s) = \int_0^\infty t^{s-1}e^{-t}\,dt$, that they write it like
$$
  \Gamma(s) = \int_0^\infty t^s e^{-t}\,\frac{dt}{t} ,
$$
where they group the $\frac 1t$ with the $dt$.
Other Mellin transforms are also often written similarly, with the $\frac{dt}{t}$ grouped together.
My question is:
In what sense is writing these integrals in this way "better" or "more meaningful" or "natural"?

A: $\dfrac{dt}{t}$ is the (well, unique up to a constant factor, so "a", strictly) Haar measure on the topological group $(0,+\infty)$ (with multiplication). That makes some transformations particularly nice when written in that style,
$$\int_0^\infty f(at)\,\frac{dt}{t} = \int_0^\infty f(t)\,\frac{dt}{t}$$
for all $a > 0$, so
$$\int_0^\infty t^s g(at)\,\frac{dt}{t} = a^{-s}\int_0^\infty \left(at\right)^sg(at)\,\frac{dt}{t} = a^{-s}\int_0^\infty t^sg(t)\,\frac{dt}{t},$$
which may be a bit nicer on the eye than it would be for $\int_0^\infty t^{s-1}g(at)\,dt$.
When we use the variant of the Mellin transform$^1$ defined as
$$\mathscr{M}[f](s) = s\int_1^\infty x^{-s}f(x)\frac{dx}{x}$$
for locally integrable $f\colon [1,+\infty) \to \mathbb{C}$ with at most polynomial growth, we have
$$\mathscr{M}[f](s) = s\mathcal{L}[F](s),$$
where $F(t) = f(e^t)$ and $\mathcal{L}$ is the Laplace-transform. Thus it is rather easy to translate theorems about the Laplace transform into theorems about the Mellin transform.
These are not compelling reasons why writing $\dfrac{dt}{t}$ is the only right thing to do, but in this way, some things look a little nicer and perhaps more natural.

$^1$ The only one I have more than seen in passing, it's well suited to working with the Riemann $\zeta$-function.


text:
Q: How can I preserve the animations and settimeout value when the page is refreshed with javascript? When the page is entered for the first time, the remaining remaining value is shown in seconds to everyone in the same way. In other words, the time does not start again every time the page is entered. It is redirected to the tensecond() function when the time is up. I use setTimeout in animations to coincide with the countdown from 10 part in this function. I'm having some problems and I'm open to your suggestions.
The first problem is this: If the time is close to running out when I enter or refresh the page, for example, if there is 5 seconds, then the tensecond() function is not requested when the time is 0, so I can't see the animations. I have to wait 1 more turn before I can see the animations.
The second problem is this: I think it is related to the first problem. Animations disappear when I refresh the page while the animations are playing, or when I exit the page and re-enter immediately.
Actually, my problem is briefly about this: Every time I enter the page, the time continues from where it left off. I want to see this in animations or functions.
CSS
 @keyframes glowing1 {
        50% {
            background-color: #3fd619;
            box-shadow: 0 0 20px #3fd619;

        }

        100% {
            background-color: #3fd619;
            box-shadow: 0 0 5px #3fd619;

        }
    }

    .glowing500 {
        animation: glowing 300ms infinite;

    }

    .glowingwin {
        animation: glowing1 300ms infinite;
    }

JS
function tensecond() {

        setTimeout(function () {
            const
                delay = ms => new Promise(r => setTimeout(r, ms)),
                btn_A = document.getElementById('first'),
                btn_B = document.getElementById('second'),
                animLoopgenerator = function* () {
                    const animLoop = [{
                            stop: null,
                            start: btn_A,
                            time_ms: 600
                        }, {
                            stop: btn_A,
                            start: btn_B,
                            time_ms: 600
                        }, {
                            stop: btn_B,
                            start: null,
                            time_ms: null
                        },

                    ];

                    for (elm of animLoop) yield elm
                };

            async function animLoop() {
                for await ({
                    stop,
                    start,
                    time_ms
                } of animLoopgenerator()) {
                    if (stop) stop.classList.remove('glowing500');
                    if (start) start.classList.add('glowing500');
                    if (time_ms) await delay(time_ms);
                }
            }

            animLoop();
        }, 25000);

        setTimeout(function () {

            var random = Math.floor(Math.random() * 2) + 1;

            if (random == 1) {
                const
                    delay = ms => new Promise(r => setTimeout(r, ms)),
                    btn_A = document.getElementById('first'),
                    animLoopgenerator = function* () {
                        const animLoop = [{
                            stop: null,
                            start: btn_A,
                            time_ms: 4000
                        }, {
                            stop: btn_A,
                            start: null,
                            time_ms: null
                        }, ];

                        for (elm of animLoop) yield elm
                    };

                async function animLoop() {
                    for await ({
                        stop,
                        start,
                        time_ms
                    } of animLoopgenerator()) {
                        if (stop) stop.classList.remove('glowingwin');
                        if (start) start.classList.add('glowingwin');
                        if (time_ms) await delay(time_ms);
                    }
                }

                animLoop();
            } else if (random == 2) {
                const
                    delay = ms => new Promise(r => setTimeout(r, ms)),
                    btn_B = document.getElementById('second'),
                    animLoopgenerator = function* () {
                        const animLoop = [{
                            stop: null,
                            start: btn_B,
                            time_ms: 4000
                        }, {
                            stop: btn_B,
                            start: null,
                            time_ms: null
                        }, ];

                        for (elm of animLoop) yield elm
                    };

                async function animLoop() {
                    for await ({
                        stop,
                        start,
                        time_ms
                    } of animLoopgenerator()) {
                        if (stop) stop.classList.remove('glowingwin');
                        if (start) start.classList.add('glowingwin');
                        if (time_ms) await delay(time_ms);
                    }
                }

                animLoop();
            }

        }, 30000);
    }

    var interval10 = 10000;
    var interval35 = 35000;

    setInterval(function () {
        var remaining = interval35 - (Date.now() % interval35);
        if (remaining >= 100) {
            if (remaining >= interval10) remaining -= interval10;
            document.getElementById("timer").innerText =
                millisToMinutesAndSeconds(remaining);
        } else {
            tensecond();
        }
    }, 100);

    function millisToMinutesAndSeconds(millis) {
        var seconds = Math.floor((millis % 60000) / 1000);
        return (seconds < 10 ? "0" : "") + seconds;
    }


text:
Q: What does .sum( ) do specifically in this situation? Usually when I've seen the sum function used, it has taken an argument within it's parentheses. What exactly does it do in the following, and what is the point of it?
a = torch.randn(2, 2)
a = ((a * 3) / (a - 1))
print(a.requires_grad)
a.requires_grad_(True)
print(a.requires_grad)
b = (a * a).sum()
print(b)
print(b.grad_fn)


text:
Q: boost log - undefined reference when using a global logger I have successfully built a boost example rotating_file (boost 1.63) using my own cmake file instead of jamfile. Then I have add following modification:
#include <boost/log/sources/global_logger_storage.hpp>
...
//before main
BOOST_LOG_GLOBAL_LOGGER(my_logger, src::logger)
...
//src::logger lg;
src::logger& lg = my_logger::get();

A program also contains this line:
#define BOOST_ALL_DYN_LINK

Here are cmake libs:
target_link_libraries(test "libboost_log.so"
                           "libboost_log_setup.so"
                           "libboost_date_time.so"
                           "libboost_filesystem.so"
                           "libboost_system.so"
                           "libboost_thread.so")

This line:
src::logger& lg = my_logger::get();

generates:
global_logger_storage.hpp:154: error: undefined reference to `my_logger::construct_logger()'

What is wrong ?
Edit
I add sink and other attributes this way:
logging::core::get()->add_sink(sink);
logging::core::get()->add_global_attribute("TimeStamp", attrs::local_clock());
logging::core::get()->add_global_attribute("RecordID", attrs::counter< unsigned int >());

so at the end of the BOOST_LOG_GLOBAL_LOGGER_INIT I just add:
src::logger logger;
return logger;

It works.

A: You need a call to BOOST_LOG_GLOBAL_LOGGER_INIT. In one project I have the following in a header:
// register a global logger
BOOST_LOG_GLOBAL_LOGGER(logger, boost::log::sources::severity_logger_mt<boost::log::trivial::severity_level>)

In the source file I have this:
BOOST_LOG_GLOBAL_LOGGER_INIT(logger, src::severity_logger_mt) {
    src::severity_logger_mt<boost::log::trivial::severity_level> logger;

    // add attributes
    logger.add_attribute("LineID", attrs::counter<unsigned int>(1));    // lines are sequentially numbered
    logger.add_attribute("TimeStamp", attrs::local_clock());             // each log line gets a timestamp

    return logger;
}

When I comment out the BOOST_LOG_GLOBAL_LOGGER_INIT, I get the same error as you do. My powers of deduction tell me that BOOST_LOG_GLOBAL_LOGGER_INIT provides the definition that you (we) need.


text:
Q: Android service connection policy What is the best practice - let each Activity maintain its own connection to Service, or create a static class that holds a single Service connection?

A: You assume those are your only two options. Of those two, the former is the only one that is possible, using your literal terms.
Personally, I recommend you consider the command pattern wherever possible -- use startService() to send a command (in the form of an Intent) to the service, which does the work and calls stopSelf() when appropriate. This works well with an IntentService, as the IntentService will process the command on a background thread and automatically calls stopSelf() when there is no more work to be done.


text:
Q: ¿Cómo editar una página externa a través de un iframe sin acceso denegado? El siguiente código me captura un sitio web idénticamente.
<?php
    $URL = "http://domain.com/embed.html";

    $domain = file_get_contents($URL);

    echo $domain;
?>

Pero que parámetros o filtros debo agregarle para obtener solo cierta parte de un sitio y poder eliminar o reemplazar enlaces y contenidos, bloquear ejecución de scripts*.
Encontré también un ejemplo empleado con jQuery para editar una página externa a través de un iframe sin acceso denegado, etc.
Pero, no entiendo en sí, como funciona específicamente, ¿Que valores se deben emplear para eliminar o remplazar enlaces y contenidos bloquear ejecución de scripts, pueden explicarme?

$(document).ready(function(){
cleanit = setInterval ( "cleaning()", 500 );
});

function cleaning(){
if($('#frametest').contents().find('.selector').html() == "somthing"){
    clearInterval(cleanit);
    $('#selector').contents().find('.Link').html('ideate tech');
}
}

He observado en esta pregunta atributos nuevos de HTML5, que se pueden hacer directo en un iframe pero de esa manera no lo deseo en ciertas partes se congela todo sin mostrarme nada.

A: Para lo que intentas hacer te sugiero algunas expresiones regulares que te pueden ayudar, sin embargo, para casos mas específicos que requieras, deberás identificar que expresión regular se adapta a tus necesidades:
Una vez obtenido el contenido de la web con:
$URL = "http://domain.com";
$domain = file_get_contents($URL);

Para poder eliminar ciertas etiquetas puedes aplicar (https://stackoverflow.com/questions/1886740/php-remove-javascript):
$domain = preg_replace('/


text:
Q: Featherlight lightbox gallery inside tabs deselects current tab I currently have a very simple lightbox gallery inside a tabbed interface, however when clicking a photo from the gallery the currently selected tab is lost and no tab is selected.
So once the user closes the gallery image he doesn't see the current tab he was in.
I made a JSFiddle of this behaviour, try clicking the second tab and opening an image from the gallery, when closing it the currently selected tab is lost.
http://jsfiddle.net/urvmubxp/1/
The jquery for tabs and gallery is this:
$('.my-tabs li').click(function(){
    $(".tab").css('display','none');
    $(".my-tabs li").removeClass('selected');
    $(this).addClass('selected')
    $('#'+this.childNodes[0].href.split('#')[1]).fadeIn('slow');
    return false;
})
//set first tab active
$('.my-tabs li').eq(0).click();

$('.gallery2').featherlightGallery({
    gallery: {
        next: 'next »',
        previous: '« previous'
    },
    variant: 'featherlight-gallery2'
});

Is there something to do in order to keep consistency with tabs while using the gallery?

A: This is not a FL problem. Since you are using $('.my-tabs li') as a trigger for your tabs, and your gallery is nested as ul li too, the click on a gallery li causes your code to execute as well... you could use $('.my-tabs > ul > li') or asign a class to the tab-lis...


text:
Q: If another instance is running, [set focus] and open file on the 'old' instance How can i check if another instance is running ?
Also if it is running how can I force my already opened instance to open a file ?
Also if it is possible can I force it to get focus? ( I need this seperate)

A:
How can i check if another instance is running ?

You could use Process.GetProcesses() to get a list of processes which are running on your machine. And simply do your compare with Process.Name. With rather simple name, you may need additional check for your application.

Also if it is running how can I force my already opened instance to
  open a file ?

If you want to communicate between 2 processes, I would recommend SendMessage method. See here.

Also if it is possible can I force it to get focus? ( I need this
  seperate)

You could use SetForgoundWindow method (also require P/Invoke). See here.


text:
Q: sql for Group By and SUM with date range condition Below is the Invoices table:

I am trying to make a sql query which gives me output based on due_date range with the sum of balance_amount group by company_id

My try:
select invoices.company_id,
SUM(invoices_cmonth.balance_amount) as cmonth,
SUM(invoices_1month.balance_amount) as 1month,
SUM(invoices_2month.balance_amount) as 2month
from `invoices`
LEFT JOIN invoices invoices_cmonth
ON (invoices.company_id = invoices_cmonth.company_id and invoices_cmonth.due_date >= '2021-11-10')
LEFT JOIN invoices invoices_1month
ON (invoices.company_id = invoices_1month.company_id and invoices_1month.due_date < '2021-11-10' and invoices_1month.due_date >= '2021-10-10')
LEFT JOIN invoices invoices_2month
ON (invoices.company_id = invoices_2month.company_id and invoices_2month.due_date < '2021-10-10' and invoices_2month.due_date >= '2021-9-10')
where invoices.`status` = 'ACTIVE'
and invoices.`balance_amount` > 0
and `invoices`.`deleted_at` is null
group by invoices.`company_id`

But it is giving me wrong figures in balance amount.

A: I suggest just making a single pass over the invoices table using conditional aggregation for the various time windows:
SELECT
    company_id,
    SUM(CASE WHEN due_date >= '2021-11-10' THEN balance_amount ELSE 0 END) AS cmonth,
    SUM(CASE WHEN due_date >= '2021-10-10' AND due_date < '2021-11-10'
             THEN balance_amount ELSE 0 END) AS 1month,
    SUM(CASE WHEN due_date >= '2021-09-10' AND due_date < '2021-10-10'
             THEN balance_amount ELSE 0 END) AS 2month
FROM invoices
WHERE
    status = 'ACTIVE' AND balance_amount > 0 AND deleted_at IS NULL
GROUP BY
    company_id;


text:
Q: handling printer from php application My server based application need to directly handle printer. the problem is that i am using php as my web application language. My applcation runs on LAMP platform.
i have tried couple of methods. but ididn't find any useful. please advise me.

A: Can you elaborate a bit?
Is it local printer? Network printer? Is priniter connected to server or client? Have you tried this?


text:
Q: Как заполнить таблицу в одном документе Word данными из таблицы Excel с помощью макроса VBA? Всех приветствую!
Возникла задача автоматизации формирования таблицы в документе Word из данных, вводимых в таблицу Excel.

*

*Имеется таблица Excel
Примерный формат приведён ниже, с неопределенным количеством вводимых данных, но со строго указанной формой. Необходимо при нажатии клавиши формировать таблицу в Word документе.

*Имеется сам типовой Word документ
Таблица в документе должна быть заполнена данными из таблицы Excel и в зависимости от количества пунктов (№ п/п) расширяться полями (в качестве примера приведены пустые поля).

*Имеется пример кода, который нашел на просторах интернета:
Думал переделать под свои задачи, но пока не знаю с чего именно начать.

Sub main()
Dim wdApp As Object
Dim wdDoc As Object

HomeDir$ = ThisWorkbook.Path
Set wdApp = CreateObject("Word.Application")
i% = 2
Do
If Cells(i%, 1).Value = "" Then Exit Do
If Cells(i%, 1).Value <> "" Then

NPP$ = Cells(i%, 1).Text
ID$ = Cells(i%, 2).Text
Adress$ = Cells(i%, 3).Text
SN$ = Cells(i%, 4).Text

DataC$ = Date

FileCopy HomeDir$ + "\template.doc", HomeDir$ + "\" + NPP$ + "_" + ID$ + "_" + DataC$ + ".doc"
Set wdDoc = wdApp.Documents.Open(HomeDir$ + "\" + NPP$ + "_" + ID$ + "_" + DataC$ + ".doc")

wdDoc.Range.Find.Execute FindText:="&date", ReplaceWith:=DataC$

wdDoc.Range.Find.Execute FindText:="&id", ReplaceWith:=ID$
wdDoc.Range.Find.Execute FindText:="&adress", ReplaceWith:=Adress$
wdDoc.Range.Find.Execute FindText:="&sn", ReplaceWith:=SN$

wdDoc.Save
wdDoc.Close
End If

i% = i% + 1
Loop
wdApp.Quit
MsgBox "Готово!"

End Sub

Подскажите, как это реализовать с применением макросов VBA?
Буду рад любой помощи, примерам кода, алгоритму как это делать. Прочесал форумы, но не нашел необходимой информации, хоть и задача является типичной.


text:
Q: How to set App Icon for a scripting Application written in AppleScript? I used following both techniques but unable to achieve.

*

*Set icns file in Plist - this shows up the icon in the dialog boxes but not in the dock.

*Do get info on the app and paste the app icon. This works very well but unable to Software sign it. Removing the icon apparently allows me to Software sign the app.
Any suggestions are appreciated.

A: Create icns file with different AppIcon sizes varying from 1024 to 32.


text:
Q: GCC have: command not found [: too many argument This is my first post, so if I do it something wrong - sorry ;)
I have problem with Debian, which don't have access to internet and will not.
cat /proc/version
Linux version 2.6.32-5-686 (Debian 2.6.32-48squeeze6) (jmm@debian.org) (gcc version 4.3.5 (Debian 4.3.5-4) ) #1 SMP Tue May 13 16:33:32 UTC 2014

I want to monitore it by SNMP, but when I try install it I have a issue.
root@debian:/home/rkrainski/net-snmp-5.9.1# sudo ./configure
checking for gcc... gcc
checking whether the C compiler works... no
configure: error: in `/home/rkrainski/net-snmp-5.9.1':
configure: error: C compiler cannot create executables
See `config.log' for more details

Below config.log
This file contains any messages produced by compilers while
running configure, to aid debugging if configure makes a mistake.

It was created by Net-SNMP configure 5.9.1, which was
generated by GNU Autoconf 2.69.  Invocation command line was

  $ ./configure

## --------- ##
## Platform. ##
## --------- ##

hostname = debian
uname -m = i686
uname -r = 2.6.32-5-686
uname -s = Linux
uname -v = #1 SMP Tue May 13 16:33:32 UTC 2014

/usr/bin/uname -p = unknown
/bin/uname -X     = unknown

/bin/arch              = unknown
/usr/bin/arch -k       = unknown
/usr/convex/getsysinfo = unknown
/usr/bin/hostinfo      = unknown
/bin/machine           = unknown
/usr/bin/oslevel       = unknown
/bin/universe          = unknown

PATH: /usr/local/sbin
PATH: /usr/local/bin
PATH: /usr/sbin
PATH: /usr/bin
PATH: /sbin
PATH: /bin
PATH: /usr/X11R6/bin

## ----------- ##
## Core tests. ##
## ----------- ##

configure:3402: checking for gcc
configure:3418: found /usr/bin/gcc
configure:3429: result: gcc
configure:3658: checking for C compiler version
configure:3667: gcc --version >&5
/usr/bin/gcc: line 11: have: command not found
/usr/bin/gcc: line 50: [: too many arguments
configure:3678: $? = 2
configure:3667: gcc -v >&5
/usr/bin/gcc: line 11: have: command not found
/usr/bin/gcc: line 50: [: too many arguments
configure:3678: $? = 2
configure:3667: gcc -V >&5
/usr/bin/gcc: line 11: have: command not found
/usr/bin/gcc: line 50: [: too many arguments
configure:3678: $? = 2
configure:3667: gcc -qversion >&5
/usr/bin/gcc: line 11: have: command not found
/usr/bin/gcc: line 50: [: too many arguments
configure:3678: $? = 2
configure:3698: checking whether the C compiler works
configure:3720: gcc    conftest.c  >&5
/usr/bin/gcc: line 11: have: command not found
/usr/bin/gcc: line 50: [: too many arguments
configure:3724: $? = 2
configure:3762: result: no
configure: failed program was:
| /* confdefs.h */
| #define PACKAGE_NAME "Net-SNMP"
| #define PACKAGE_TARNAME "net-snmp"
| #define PACKAGE_VERSION "5.9.1"
| #define PACKAGE_STRING "Net-SNMP 5.9.1"
| #define PACKAGE_BUGREPORT "net-snmp-coders@lists.sourceforge.net"
| #define PACKAGE_URL ""
| #define NETSNMP_CONFIGURE_OPTIONS ""
| /* end confdefs.h.  */
|
| int
| main ()
| {
|
|   ;
|   return 0;
| }
configure:3767: error: in `/home/rkrainski/net-snmp-5.9.1':
configure:3769: error: C compiler cannot create executables
See `config.log' for more details

## ---------------- ##
## Cache variables. ##
## ---------------- ##

ac_cv_env_CC_set=
ac_cv_env_CC_value=
ac_cv_env_CFLAGS_set=
ac_cv_env_CFLAGS_value=
ac_cv_env_CPPFLAGS_set=
ac_cv_env_CPPFLAGS_value=
ac_cv_env_CPP_set=
ac_cv_env_CPP_value=
ac_cv_env_LDFLAGS_set=
ac_cv_env_LDFLAGS_value=
ac_cv_env_LIBNL3_CFLAGS_set=
ac_cv_env_LIBNL3_CFLAGS_value=
ac_cv_env_LIBNL3_LIBS_set=
ac_cv_env_LIBNL3_LIBS_value=
ac_cv_env_LIBS_set=
ac_cv_env_LIBS_value=
ac_cv_env_LT_SYS_LIBRARY_PATH_set=
ac_cv_env_LT_SYS_LIBRARY_PATH_value=
ac_cv_env_PKG_CONFIG_LIBDIR_set=
ac_cv_env_PKG_CONFIG_LIBDIR_value=
ac_cv_env_PKG_CONFIG_PATH_set=
ac_cv_env_PKG_CONFIG_PATH_value=
ac_cv_env_PKG_CONFIG_set=
ac_cv_env_PKG_CONFIG_value=
ac_cv_env_build_alias_set=
ac_cv_env_build_alias_value=
ac_cv_env_host_alias_set=
ac_cv_env_host_alias_value=
ac_cv_env_target_alias_set=
ac_cv_env_target_alias_value=
ac_cv_prog_ac_ct_CC=gcc

## ----------------- ##
## Output variables. ##
## ----------------- ##

AGENTLIBS=''
AGENT_INCLUDES=''
ALLOCA=''
AR=''
AS=''
AUTOCONF=''
AUTOHEADER=''
AWK=''
CC='gcc'
CCPATH=''
CFLAGS=''
CONFIGURE_OPTIONS='""'
COPY_PERSISTENT_FILES=''
CPP=''
CPPFLAGS=''
DEFS=''
DEVFLAGS=''
DLLIBS=''
DLLTOOL=''
DPKG_QUERY_PATH=''
DSYMUTIL=''
DUMPBIN=''
ECHO_C=''
ECHO_N='-n'
ECHO_T=''
EGREP=''
EMBEDPERLINSTALL=''
EMBEDPERLUNINSTALL=''
ENV_SEPARATOR=''
EXEEXT=''
EXTERNAL_MIBGROUP_INCLUDES=''
EXTRACPPFLAGS=''
FEATUREHEADERS=''
FEATURETARGS=''
FEATURE_ADD_FLAGS=''
FEATURE_REMOVE_FLAGS=''
FGREP=''
FILE=''
FIND=''
FTMAINSUBS=''
GNU_vpath=''
GREP=''
HAVE_LIBCURSES=''
HELPER_INCLUDES=''
INSTALL_DATA=''
INSTALL_PREFIX=''
INSTALL_PROGRAM=''
INSTALL_SCRIPT=''
LAGENTLIBS=''
LD=''
LDFLAGS=''
LD_NO_UNDEFINED=''
LIBCURSES=''
LIBNL3_CFLAGS=''
LIBNL3_LIBS=''
LIBOBJS=''
LIBS=''
LIBTOOL=''
LIBTOOLFLAGS=''
LIBTOOL_DEPS=''
LINKCC=''
LIPO=''
LMIBLIBS=''
LNETSNMPLIBS=''
LN_S=''
LPSTAT_PATH=''
LTLIBOBJS=''
LT_SYS_LIBRARY_PATH=''
MAINSUBS=''
MANIFEST_TOOL=''
MIBGROUP_INCLUDES=''
MYSQLCONFIG=''
MYSQL_INCLUDES=''
MYSQL_LIBS=''
NETSNMP_BUILD_PCAP_PROG_FALSE=''
NETSNMP_BUILD_PCAP_PROG_TRUE=''
NETSNMP_BUILD_SET_PROG_FALSE=''
NETSNMP_BUILD_SET_PROG_TRUE=''
NETSNMP_BUILD_SSH_PROG_FALSE=''
NETSNMP_BUILD_SSH_PROG_TRUE=''
NETSNMP_BUILD_TLS_PROG_FALSE=''
NETSNMP_BUILD_TLS_PROG_TRUE=''
NETSNMP_BUILD_USM_PROG_FALSE=''
NETSNMP_BUILD_USM_PROG_TRUE=''
NETSNMP_DEFAULT_MIBDIRS=''
NETSNMP_DEFAULT_MIBS=''
NETSNMP_HAVE_AGENTX_LIBS_FALSE=''
NETSNMP_HAVE_AGENTX_LIBS_TRUE=''
NM=''
NMEDIT=''
NON_GNU_VPATH=''
OBJDUMP=''
OBJEXT=''
OTHERAGENTLIBLFTS=''
OTHERAGENTLIBLOBJS=''
OTHERAGENTLIBOBJS=''
OTOOL64=''
OTOOL=''
PACKAGE_BUGREPORT='net-snmp-coders@lists.sourceforge.net'
PACKAGE_NAME='Net-SNMP'
PACKAGE_STRING='Net-SNMP 5.9.1'
PACKAGE_TARNAME='net-snmp'
PACKAGE_URL=''
PACKAGE_VERSION='5.9.1'
PARTIALTARGETFLAGS=''
PATH_SEPARATOR=':'
PERLARGS=''
PERLFEATURES=''
PERLINSTALLTARGS=''
PERLLDOPTS_FOR_APPS=''
PERLLDOPTS_FOR_LIBS=''
PERLPROG=''
PERLTARGS=''
PERLUNINSTALLTARGS=''
PERL_SYSTEM_INVOKES_POSIX_SHELL=''
PERSISTENT_DIRECTORY=''
PKG_CONFIG=''
PKG_CONFIG_LIBDIR=''
PKG_CONFIG_PATH=''
PSCMD=''
PSPROG=''
PYTHONARGS=''
PYTHONCLEANTARGS=''
PYTHONFEATURES=''
PYTHONINSTALLTARGS=''
PYTHONPROG=''
PYTHONTARGS=''
PYTHONUNINSTALLTARGS=''
RANLIB=''
RC=''
SED=''
SET_MAKE=''
SHELL='/bin/bash'
SNMPCONFPATH=''
SNMPD=''
SNMPLIBPATH=''
SNMPLIB_INCLUDES=''
SNMPSHAREPATH=''
STRIP=''
TOP_INCLUDES=''
TRAPLIBS=''
UCDPERSISTENT_DIRECTORY=''
UNAMEPROG=''
USETRAPLIBS=''
VAL_LIBS=''
VERSION=''
WHOAMI=''
ac_ct_AR=''
ac_ct_CC='gcc'
ac_ct_DUMPBIN=''
ac_cv_NETSNMP_SYSTEM_INCLUDE_FILE=''
bindir='${exec_prefix}/bin'
build=''
build_alias=''
build_cpu=''
build_os=''
build_vendor=''
crypto_files_c=''
crypto_files_lo=''
crypto_files_o=''
datadir='${datarootdir}'
datarootdir='${prefix}/share'
default_mibs_install=''
dllcleans=''
docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
dvidir='${docdir}'
exec_prefix='NONE'
host=''
host_alias=''
host_cpu=''
host_os=''
host_vendor=''
htmldir='${docdir}'
includedir='${prefix}/include'
infodir='${datarootdir}/info'
installucdheaders=''
installucdlibs=''
krb5_config=''
libdir='${exec_prefix}/lib'
libexecdir='${exec_prefix}/libexec'
localedir='${datarootdir}/locale'
localstatedir='${prefix}/var'
mandir='${datarootdir}/man'
oldincludedir='/usr/include'
other_agentobjs=''
other_ftagentobjs=''
other_ftobjs_list=''
other_lagentobjs=''
other_lobjs_list=''
other_objs_list=''
other_src_list=''
other_trapd_objects=''
pdfdir='${docdir}'
prefix='NONE'
program_transform_name='s,x,x,'
psdir='${docdir}'
sbindir='${exec_prefix}/sbin'
security_ftobj_list=''
security_hdr_list=''
security_lobj_list=''
security_obj_list=''
security_src_list=''
sharedstatedir='${prefix}/com'
sysconfdir='${prefix}/etc'
target=''
target_alias=''
target_cpu=''
target_os=''
target_vendor=''
transport_ftobj_list=''
transport_hdr_list=''
transport_lobj_list=''
transport_obj_list=''
transport_src_list=''

## ------------------- ##
## File substitutions. ##
## ------------------- ##

MODULE_LIST=''
agent_module_list_c=''
agent_module_list_deps=''
agent_module_list_ft=''
agent_module_list_lo=''
agent_module_list_o=''
agentgroup_list_ft=''
agentgroup_list_lo=''
agentgroup_list_o=''
mib_module_list_c=''
mib_module_list_deps=''
mib_module_list_ft=''
mib_module_list_lo=''
mib_module_list_o=''
mibgroup_list_ft=''
mibgroup_list_lo=''
mibgroup_list_o=''
module_list_c=''
module_list_deps=''
module_list_ft=''
module_list_lo=''
module_list_o=''
module_rules=''

## ----------- ##
## confdefs.h. ##
## ----------- ##

/* confdefs.h */
#define PACKAGE_NAME "Net-SNMP"
#define PACKAGE_TARNAME "net-snmp"
#define PACKAGE_VERSION "5.9.1"
#define PACKAGE_STRING "Net-SNMP 5.9.1"
#define PACKAGE_BUGREPORT "net-snmp-coders@lists.sourceforge.net"
#define PACKAGE_URL ""
#define NETSNMP_CONFIGURE_OPTIONS ""

configure: exit 77

I tried to find solution about gcc, but only I found:
root@debian:/home/rkrainski/net-snmp-5.9.1# ls /usr/bin | grep gcc
gcc
root@debian:/home/rkrainski/net-snmp-5.9.1# /usr/bin/gcc
/usr/bin/gcc: line 11: have: command not found
/usr/bin/gcc: line 50: [: too many arguments
root@debian:/home/rkrainski/net-snmp-5.9.1# /etc/bash_completion.d/gcc
/etc/bash_completion.d/gcc: line 11: have: command not found
/etc/bash_completion.d/gcc: line 50: [: too many arguments
root@debian:/home/rkrainski/net-snmp-5.9.1# echo "$PATH"
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
root@debian:/home/rkrainski/net-snmp-5.9.1# ls -l /etc/bash_completion.d/gcc
-rwxrwxrwx 1 root root 1604 Nov 16  2010 /etc/bash_completion.d/gcc
root@debian:/home/rkrainski/net-snmp-5.9.1# cat /etc/environment
PATH="$PATH:/usr/bin"

Below what is include gcc file:
root@debian:/home/rkrainski/net-snmp-5.9.1# cat /etc/bash_completion.d/gcc
# gcc(1) completion
#
# The only unusual feature is that we don't parse "gcc --help -v" output
# directly, because that would include the options of all the other backend
# tools (linker, assembler, preprocessor, etc) without any indication that
# you cannot feed such options to the gcc driver directly.  (For example, the
# linker takes a -z option, but you must type -Wl,-z for gcc.)  Instead, we
# ask the driver ("g++") for the name of the compiler ("cc1"), and parse the
# --help output of the compiler.

have gcc &&
_gcc()
{
    local cur cc backend

    COMPREPLY=()
    _get_comp_words_by_ref cur

    _expand || return 0

    case $1 in
        gcj)
            backend=jc1
            ;;
        gpc)
            backend=gpc1
            ;;
        *77)
            backend=f771
            ;;
        *)
            backend=cc1 # (near-)universal backend
            ;;
    esac

    if [[ "$cur" == -* ]]; then
        cc=$( $1 -print-prog-name=$backend )
        # sink stderr:
        # for C/C++/ObjectiveC it's useless
        # for FORTRAN/Java it's an error
        COMPREPLY=( $( compgen -W "$( $cc --help 2>/dev/null | \
           tr '\t' ' ' | \
           sed -e '/^  *-/!d' -e 's/ *-\([^ ]*\).*/-\1/' | \
           sort -u )" -- "$cur" ) )
    else
        _filedir
    fi
} &&
complete -o filenames -F _gcc gcc g++ c++ g77 gcj gpc
[ $USERLAND = GNU -o $UNAME = Cygwin ] && \
[ -n "${have:-}" ] && complete -o filenames -F _gcc cc

# Local variables:
# mode: shell-script
# sh-basic-offset: 4
# sh-indent-comment: t
# indent-tabs-mode: nil
# End:
# ex: ts=4 sw=4 et filetype=sh

cat /etc/bash.bashrc
root@debian:/home/rkrainski# cat /etc/bash.bashrc
# System-wide .bashrc file for interactive bash(1) shells.

# To enable the settings / commands in this file for login shells as well,
# this file has to be sourced in /etc/profile.

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, overwrite the one in /etc/profile)
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '

# Commented out, don't overwrite xterm -T "title" -n "icontitle" by default.
# If this is an xterm set the title to user@host:dir
#case "$TERM" in
#xterm*|rxvt*)
#    PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'
#    ;;
#*)
#    ;;
#esac

# enable bash completion in interactive shells
#if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
#    . /etc/bash_completion
#fi

# if the command-not-found package is installed, use it
if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found ]; then
        function command_not_found_handle {
                # check because c-n-f could've been removed in the meantime
                if [ -x /usr/lib/command-not-found ]; then
                   /usr/bin/python /usr/lib/command-not-found -- $1
                   return $?
                elif [ -x /usr/share/command-not-found ]; then
                   /usr/bin/python /usr/share/command-not-found -- $1
                   return $?
                else
                   return 127
                fi
        }
fi

cat ~/.bashrc
root@debian:/home/rkrainski# cat ~/.bashrc
# ~/.bashrc: executed by bash(1) for non-login shells.

# Note: PS1 and umask are already set in /etc/profile. You should not
# need this unless you want different defaults for root.
# PS1='${debian_chroot:+($debian_chroot)}\h:\w\$ '
# umask 022

# You may uncomment the following lines if you want `ls' to be colorized:
# export LS_OPTIONS='--color=auto'
# eval "`dircolors`"
# alias ls='ls $LS_OPTIONS'
# alias ll='ls $LS_OPTIONS -l'
# alias l='ls $LS_OPTIONS -lA'
#
# Some more alias to avoid making mistakes:
# alias rm='rm -i'
# alias cp='cp -i'
# alias mv='mv -i'

mount | grep noexec
root@debian:/home/rkrainski# mount | grep noexec
proc on /proc type proc (rw,noexec,nosuid,nodev)
sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)
devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=620)
binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,noexec,nosuid,nodev)

I tried to instal gcc offline but still the same error: checking for C compiler default output file name... configure: error: C compiler cannot create executables
Do You have any ideas? Don't forgot that PC don't have internet access.
Thank You in advance


text:
Q: Angular mat-form-field add space between label Hello how can show the mat-label its half hidden.

A: in the component css file:
mat-form-field {
    line-height 55px !important;

}
or
mat-label{
 line-height 55px !important;

}

or
::ng-deep mat-form-field {
       line-height 55px !important;
}
or
::ng-deep mat-label {
 line-height 55px !important;

}

be careful with the later because it is universal.  you may have to play around with the css order of the element.  like I said the best thing to do is to view it with chrome dev tools so you can get the exact class map.

A: my temporary solution is to use
.mat-form-field-appearance-fill .mat-form-field-label-wrapper{ overflow: visible!important; }


text:
Q: How to run node.js file from PHP file so I've been trying to run an SMS script after the user submits a form.
If I use
node send-sms.js

locally on my machine, it works.
However, if I try to use
$sendSmsPath = "send-sms.js";
exec('/public_html/node_modules/node '.$sendSmsPath);

Nothing happens. No error, nothing. I tried using a relative path, as well as an absolute one. My folder scheme is as follows: public > other_folder > php > php_file.php AND public > node_modules
Any ideas are welcome, thanks

A: You are using the wrong path to Node.js. Try this:
<?php
$sendSmsPath = "send-sms.js";
exec('/c/Program Files/nodejs/node '.$sendSmsPath);

node_modules is for the dependencies of your script, not the actual Node.js executable.
If you'd like to run your script on another machine make sure it has Node.js installed globally and you know the path of the executable (can be found with which node)


text:
Q: Code for login with Oracle database I have one oracle table hrd_user with data user_name (rajesh )  pswd(12345).
I am  trying to login with this code but it show Not Registered User or Invalid Name/Password.
try
{
    if (textBox1.Text == "" || textBox2.Text == "")
    {
        MessageBox.Show(" Enter UserName and Password .");
        return;
    }

    cmd = new OracleCommand("SELECT * FROM hrd_user where user_Name=:user_name and pswd=:pswd", con);
    cmd.Parameters.Add(new OracleParameter(":user_name", textBox1.Text));
    cmd.Parameters.Add(new OracleParameter(":pswd", textBox2.Text));

    OracleDataAdapter da = new OracleDataAdapter(cmd);
    da.Fill(ds);
    int i = ds.Tables[0].Rows.Count;
    if (i == 1)
    {
        this.Hide();
        show_db_managoption frm = new show_db_managoption();
        frm.Show();
        ds.Clear();
    }
    else
    {
        MessageBox.Show("Not Registered User or Invalid Name/Password");
        textBox1.Text = "";
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

A: though your code looks correct,i would like to suggest you few changes.
1.  Make sure your OracleConnection object con is opened using following statement.
con.Open();

2. make sure that there are no whitespaces in given username and password.
invoke Trim() method on both username and password to get rid of any whitespaces.
cmd.Parameters.Add(new OracleParameter(":user_name", textBox1.Text.Trim()));
cmd.Parameters.Add(new OracleParameter(":pswd", textBox2.Text.Trim()));

3. while comparing the username and password with EmptyString i would suggest you to use built-in method String.IsNullOrWhitespace() of String class to get better results.
if(String.IsNullOrWhiteSpace(textBox1.Text) || String.IsNullOrWhiteSpace(textBox2.Text))
{
    MessageBox.Show(" Enter UserName and Password .");
    return;
}


text:
Q: AFNetworking 2.0 POST request not working swift I am facing an issue with AFNetworking 2.0 (coding on Swift). GET method, of library seems that works perfect for me. Although, POST method returns me error. The error is Bad username/password. From the first looking that seem an authentication issue, but actually when I tried the POST request on Postman (REST Client) worked perfect.
So what I am doing:
Configuration:
var policy : AFSecurityPolicy = AFSecurityPolicy();
policy.allowInvalidCertificates = true;

self.client = AFHTTPRequestOperationManager(baseURL: self.basicUrl)
self.client!.operationQueue = NSOperationQueue.mainQueue()
self.client!.securityPolicy = policy

var responseSerializer : AFJSONResponseSerializer = AFJSONResponseSerializer()

self.client!.responseSerializer = responseSerializer

var requestSerializer : AFJSONRequestSerializer = AFJSONRequestSerializer()
requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")

self.client!.requestSerializer = requestSerializer

and my request
internal func loginUser(email : String, password : String, onCompletion : WebClientLoginResponse) -> Void
{
    var params : Dictionary = ["email":email, "pass":password]

    self.client!.POST("login", parameters: params, success: { (operation : AFHTTPRequestOperation!, response : AnyObject!) -> Void in

        var finalResponse : Dictionary = Dictionary<String, String>()

        finalResponse = response as Dictionary

        onCompletion(true, nil, nil, nil)

        }) { (operation : AFHTTPRequestOperation!, error : NSError!) -> Void in

            println("Error \(error.description) \(operation.responseObject) ")

            onCompletion(false, nil, nil, nil)
    }
}

What do you think guys? Am I missing anything?
Thank you!

A: Does your server require JSON-encoded parameters? See the accepted answer to this question.
Also, consider using the Swift version of AFNetworking, AlamoFire, which has an easier (IMHO) way to set the encoding format.


text:
Q: SqlAlchemy Foreign Key Error on Many to Many Relationship I am attempting to set up a basic many-to-many relationship in SqlAlchemy. I am able to successfully create the database using db.create_all() but I run into an error when trying to retrieve any records from the database.
class Geo(db.Model):
    __tablename__ = 'geos'

    geo = db.Column(db.Integer, primary_key=True)
    states = db.relationship("State", secondary='geos_states')

class State(db.Model):
    __tablename__ = 'states'

    state_short = db.Column(db.String, primary_key=True)
    geos = db.relationship("Geo", secondary='geos_states')

class GeoState(db.Model):
    __tablename__ = 'geos_states'

    id = db.Column(db.Integer, primary_key=True)
    geo_id = db.Column(db.Integer, db.ForeignKey('geos.geo')),
    state_short_id = db.Column(db.String, db.ForeignKey('states.state_short'))

The error is as follows:
sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers.  Original exception was: Could not determine join condition between parent/child tables on relationship Geo.states - there are no foreign keys linking these tables via secondary table 'geos_states'.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify 'primaryjoin' and 'secondaryjoin' expressions.

A: The pattern you are using is a variant on the many-many relationship pattern in SQLAlchemy.
Typically what you would do is the following
geostates_association_table = Table(
    'geo_states', Base.metadata,
    db.Column(
        'geo_id', db.Integer,
        db.ForeignKey('geos.geo')
    ),
    db.Column(
        'state_short_id', db.String,
        db.ForeignKey('states.state_short')
    )
)

class Geo(db.Model):
    __tablename__ = 'geos'

    geo = db.Column(db.Integer, primary_key=True)
    states = db.relationship(
        "State",
        secondary= geostates_association_table,
        back_populates='geos'
    )

class State(db.Model):
    __tablename__ = 'states'

    state_short = db.Column(
        db.String,
        primary_key=True
    )
    geos = db.relationship(
       "Geo",
       secondary=geostates_association_table,
       back_populates='states'
    )

I think this what you need since you don't seem to have any additional columns required on the mapping table in the many-many relationship. However, if you did you would need to use the Association Object pattern which is what you are doing originally. In this case
class Geo(db.Model):
    __tablename__ = 'geos'

    geo = db.Column(
        db.Integer,
        primary_key=True
    )
    states = db.relationship(
        "GeoState",
        back_populates="geos"
    )

class State(db.Model):
    __tablename__ = 'states'

    state_short = db.Column(
        db.String,
        primary_key=True
    )
    geos = db.relationship(
        "GeoState",
         back_populates="states"
    )

class GeoState(db.Model):
    __tablename__ = 'geos_states'
    # Notice how we set primary keys on both the fields
    geo_id = db.Column(
        db.Integer,
        db.ForeignKey('geos.geo'),
        primary_key=True
    ),
    state_short_id = db.Column(
        db.String,
        db.ForeignKey('states.state_short'),
        primary_key=True
    ),
    some_other_field = db.Column(
       db.String
    )

    geos = relationship("Geo", back_populates="states")
    states = relationship("State", back_populates="geos")

Note that in this case what you'll get in your relationship lists for State and Geo will actually be GeoState objects. If you want to use the Association Object pattern but have the relationship lists be populated by their respective counterpart objects instead. You can use the AssociationProxy sqlalchemy extension which you can find the documentation for here
For your reference,
The Association Object pattern is documented here
Basic Many to Many pattern is documented here


text:
Q: Can I use uEnv.txt to trigger a SW update on i.MX6 I would like to use the uEnv.txt file and add a uenvcmd to detect an environment variable. The variable holds a flag to trigger the export the flash as a mass storage so it can be updated.
The goal is to design an automated update mechanism for the i.MX6 platform. The steps would be as follow:

*

*i.MX6 is up and running (kernel + application).

*User trigger an update request via the application.

*The application detects the request, set an environment variable to 1, and reboots.

*U-boot restarts and loads the uEnv.txt file.

*The script in uenvcmd is executed, and the flash environment variable is detected and set back to 0.

*The i.MX6 mounts the flash memory via USB-C (ums 0 mmc 0) through the uenvcmd script.

*User flash the application via BalenEtcher

*User hard reboots the board after the flash is complete (BalenaEtcher signals the end of the flash).

*U-boot restarts and this time launches the updated kernel+application (the uenvcmd is executed but the export of flash is bypassed due to the environment variable set to 0).

Let me know if there is another alternative to handle the update of the i.MX6 in the field without extra libraries (Mender,...) with simple user interaction and uEnv.txt file.


text:
Q: How to make default route to login page if not authenticated react-router-dom I have an application where the first thing(default route) a user sees is a landing page with a register or login form if that user is not authenticated, if a user is authenticated I want to show the dashboard, (similar to how social media works) I have created 2 layouts <IsAuthenticated /> (where i render everything i want user that is authenticated to see) and an <Authentication /> (where i render the landing page with register and login forms), i'm having a really hard time making the logic how to use react router with this, If you know a tutorial suggestion where they handle this type of routing would be great

A: You can do something like this
export const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
    {...rest}
    render={(props) =>
        isLogin ? (
            <Component {...props} />
        ) : (
            <Redirect
                to={{
                    pathname: '/',
                    state: { from: props.location },
                }}
            />
        )
    }
/>

);

A: This function will redirect to the login page if the user isn't authenticated (change your AuthContext according to yours).
You can do the opposite for public route that shouldn't be accessible if the user is logged in (the login page for exemple).
const PrivateRoute = (props) => {
    const { children } = props;
    let auth = useContext(AuthContext);
    let location = useLocation();

    if (!auth.isLoggedIn) {
        return <Navigate to="/login" state={{ from: location }} replace />;
    }

    return <>{children}</>;
};

In your routes :
<Route
    path="/MY_SECRET_ROUTE"
    element={
        <PrivateRoute>
            <MySecretComponent />
        </PrivateRoute>
    }
>


text:
Q: I wish to keep opacity the same even after restart I wish to make it where the opacity is the same when I quit the application and reopen it to be the opacity i set it from the trackbar value... hopefully these images help...
http://imgur.com/gallery/yK3no
    Private Sub TrackBar1_Scroll(sender As Object, e As EventArgs) Handles TrackBar1.Scroll

        Me.Opacity = TrackBar1.Value * 0.01
        Form1.Opacity = TrackBar1.Value * 0.01
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Label5.Text = TrackBar1.Value
// this is the Label showing the value of track bar 1 which you'll see in the images.

    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        My.Settings.Default("Settings") = "Some Value"
        My.Settings.Default.Save()
//here is the settings in properties to save the value on exit however doesn't work... any ideas?

    End Sub
End Class

Here are my current setting i set it for now till then
    Private Sub TrackBar1_Scroll(sender As Object, e As EventArgs) Handles TrackBar1.Scroll
        Me.Opacity = TrackBar1.Value * 0.01
        Form1.Opacity = TrackBar1.Value * 0.01
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Label5.Text = TrackBar1.Value
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        If Label5.Text = TrackBar1.Value Then
            My.Settings.Opacity = TrackBar1.Value * 0.01
        End If
    End Sub
End Class

A: You are going to want to use the Application Settings to save that value.
this answer will hopefully help you: Best practice to save application settings in a Windows Forms Application


text:
Q: Error 'unsupported operand type(s) for +: 'UserBalanceChange' and 'int'' I want to make multithreaded transactions in django, when the payment of one user is divided between the second and third user in different proportions. I wrote the code. It works for two users, and when a third user appears, an error appears, although the code is exactly the same as for two users.
my views.py:
    @transaction.atomic()
def transaction_file(request):
    if request.method == "POST":
        try:
            buyer = request.POST.get('buyer')
            seller = request.POST.get('seller')
            admin = request.POST.get('admin')
            amount = request.POST.get('amount')

            buyer_obj = UserBalanceChange.objects.get(user = buyer)
            seller_obj = UserBalanceChange.objects.get(user=seller)
            admin_obj = UserBalanceChange.objects.get(user=admin)

            with transaction.atomic():
                buyer_obj.amount -= int(0.8*int(amount))
                buyer_obj.save()

                seller_obj.amount += int(0.8*int(amount))
                seller_obj.save()

                with transaction.atomic():
                    buyer_obj.amount -= int(0.2 * int(amount))
                    buyer_obj.save()

                    admin_obj = admin_obj + int(0.2 * int(amount))
                    admin_obj.save()
                # messages.success(request, 'Транзакция успешно проведена')
                return HttpResponse('Транзакция успешно проведена')

        except Exception as e:
            print(e)
            # messages.success(request,'Что-то пошло не так!(')
            return HttpResponse('Что-то пошло не так!(')

    return render(request,'chat/files/chattransaction.html')

my models.py
class UserBalanceChange(models.Model):
user = models.ForeignKey(User,on_delete = models.CASCADE, related_name='balance_changes')
amount = models.DecimalField(verbose_name='Amount', default=0, max_digits=18, decimal_places=2)
datetime = models.DateTimeField(verbose_name='date', default=timezone.now)

def __str__(self):
    return f'{self.user.username}'

my html:
<form method="POST" style="width: 50%;">
                      {% csrf_token %}
    <form method="post">

        Покупатель
        <input class="form-control" name="buyer" type="text" placeholder="Покупатель">

        Продавец
        <input class="form-control" name="seller" type="text" placeholder="Продавец">

        Админ
        <input class="form-control" name="admin" type="text" placeholder="Админ">

        Цена
        <input class="form-control" name="amount" type="text" placeholder="Цена">

      <button type="submit" class="btn btn-primary">Купить</button>
    </form>

A: The error is probably on your line:
admin_obj = admin_obj + int(0.2 * int(amount))

You are trying to add to the object instead of the amount field of the object.


text:
Q: Javascript Array logging confusion I have noticed something that I cannot understand at all. I am doing something really simple in JavaScript:
var a = [1,2,3];

console.log(a.push(4));
console.log(a);
console.log(a.push(5));

I would expect the console to log: 4, [1,2,3,4], and 5 as described here for example.
The catch is that the actual console output looks like: 4, [1,2,3,4,5], and 5
See: http://jsfiddle.net/HknMF/
What on earth makes the 5 appear in the second log output?
EDIT: fwiw here's a screenshot of Firebug showing both behaviors: http://i.imgur.com/fwAK3.png

A: The console in some browsers uses a reference to the array/object, so when you inspect it and the object changed after the console.log() call you'll see the changed object.
In Firefox this also happens for objects, but not for arrays which are displayed inline anyway:
>>> var a = [1,2,3]; console.log(a.push(4)); console.log(a); console.log(a.push(5));
4
[1, 2, 3, 4]
5

Especially for objects that do not contain functions a quick workaround is either cloning them (log $.extend({}, yourObject) if you have jQuery) or logging their JSON string version (then you lose the nice object view and just get a plain string though). An array can easily cloned (shallow copy!) using a.slice(0)

A: Dependent of the Browser either your live array gets logged (Chrome) or A string representation (Firefox).
A shallow copy is sufficient to prevent that. Use:
console.log( a.slice(0) );

for that.