text:
Q: jQuery: Wrap only first and second child, not the rest of children In my actual code:

I need to produce:

I was playing with wrap, .wrapAll() and children, but I'm stuck.
If in my actual code i have:

How do i produce:

A: First as Adam said remove the # prefix from your id attributes.  Also match your closing tags, currently you have a
 where a
 should be.
Then, you can do it using :lt() and .wrapAll() like this:
$("#mother div:lt(2)").wrapAll("

");

This gets everything less than index 2 (0 and 1 are the first 2), then wraps it.  You can test it here.

A: Remove # from your HTML ids.
$("#mother div:eq(0), #mother div:eq(1)").wrapAll("

")

A: sharp should not be part of the id's.  Then you can do:
$('#child-01, #child-02').wrapAll('
');

A: $(document).ready(function(){
  $(".new-grid__item:nth-child(1), .new-grid__item:nth-child(2)").wrapAll('

');
});


text:
Q: Spray Returning JSON I've just started using Spray and I'm building a sample API that simply returns some JSON.
Take the following example. I have the alphabet stored in a singleton...
class Alphabet {}

object Alphabet {
    final val alphabet = Array('a', 'b', 'c', ...)
}

I then have a simple spray route...
path("list") {
  get {
    respondWithMediaType(`application/json`) {
      complete(Alphabet.alphabet)
    }
  }
}

This works fine and seems to return an "application/json" response with the correct data. But is this valid? i.e. is this a correctly formatted response that would be expected by an end user?
The reason I ask is I have looked at a number of Spray examples and most seem to use case classes and specify custom JSON formatters similar to this...
object CustomJsonProtocol extends DefaultJsonProtocol {
  implicit val responseFormat = jsonFormat3(CaseClassHere)
}

...

complete {
  CaseClassHere("Test", "Test");
}

Whats the correct approach?
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Time limit for using commands I am using JDA to write a bot.
I have already written several commands and I want to make it so that the user can call the command only once, then he has to wait, say, 5 seconds to use it again.
I tried to do this using the java.util.concurrent.TimeUnit library.
But the problem is that after these 5 seconds the bot begins to respond to messages that I sent during the time the command was not called.
And it is necessary so that he only replies to it times, and ignored subsequent messages of the same kind.
If you need the source code, please write in the comments.
Thank you in advance, good luck and no bugs.

A: You're making it way to complicated, the solution is much more simple. Just store a timestamp whenever a user executes a command. If the user sends another command, compare the current timestamp with the previous one, and if there within 5 seconds, ignore the command.You can store a timestamp per user, per command, or both depending on your requirements.


text:
Q: How to turn off the Quick Fix popup in VS Code I am running VS Code 1.52.1 in Windows, editing JavaScript code. I am a double-click, copy & paste junkie. I mouse over something, like a function name, with the intent to double click copy it to the clipboard. But sometimes VS Code wants to suggest a "Quick Fix". This would be OK with me, except that the Quick Fix is displayed in a popup that overlays the code I am attempting to copy. Depending on how fast I am working, I may not notice until I paste the "old" contents of the clipboard into my target location.
Take the following function, for example.
// function to allow a promise-oriented caller to invoke
// a callback-oriented function
function callbackToPromise( resolve, reject ) {
    return function done( err, data ) {
        if(err) {
            reject(err);
        }
        else {
            resolve(data);
        }
    }
}

I mouse over the function name and the Quick Fix appears, overlaying the line of code where the mouse is hovering. The fix itself is redacted to avoid irrelevant discussion.

This behavior is both inconvenient and annoying, as it shifts my focus from the code to the misbehaving tool. It's like stubbing my toe a dozen times a day.
How can I configure VS Code not to automatically display Quick Fix popups? I would much prefer if VS Code would simply underline the function name and let me press the hotkey to see the popup.

A: I'm not aware of an exact/direct setting for the Quick Fix suggestion. What you can do though is to control the entire popup: increase the delay or disable it on mouse hover, then use shortcut keys to show it only when you want it to.
The settings for the mouse hover are editor.hover.*:

"editor.hover.delay": 300,
"editor.hover.enabled": true,
"editor.hover.sticky": true,

Set editor.hover.delay to some "high" value, so it gives you time to double-click to copy things before the popup appears. Or, disable it entirely with editor.hover.enabled.
As for the hotkeys, in Keyboard Shortcuts, there's editor.action.showHover:

You can disable the popup on mouse hover with editor.hover.enabled set to false, and then just use the shortcut key to show it manually (I'm using a Mac so it's showing Mac shortcut keys. There should also be one for Windows.)
From the popup, there's also a shortcut key for directly showing the Quick Fix suggestions. You can also configure that from Keyboard Shortcuts as editor.action.quickFix:

Again, you can disable the popup on mouse hover with editor.hover.enabled set to false and then just use the Quick Fix shortcut key to show it as needed.

A: In Windows 10 this is how I did it: Settings -> Text Editor -> Quick Suggestions Delay.


text:
Q: Rails format.xml render and pass multiple variables Typical usage is:
respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @users }
end

And now I want to also pass a string named "teststring".
I've seen reference to using
:local => {:users => @users, :another => @another}

But I don't know how to merge the two together.  I just haven't seen everything all together.  Not much documentation to really explain the :xml in that line.  And I don't know if I can deal with the string with :teststring => teststring?
And lastly, how do I deal with them in my index.html.erb now that I have multiple variables?  Do they get passed with the same name from the render command?
Thanks.

A: If you want to render custom XML, you'll need to create a index.xml.erb file in the corresponding view directory for the controller. It works just like any HTML template you'd use, then:
app/controllers/home_controller.rb:
def index
    @users = ...
    @another = "Hello world!"

    # this `respond_to` block isn't necessary in this case -
    # Rails will detect the index.xml.erb file and render it
    # automatically for requests for XML
    respond_to do |format|
        format.html # index.html.erb
        format.xml # index.xml.erb
    end
end

app/views/home/index.xml.erb:
<?xml version="1.0" encoding="UTF-8"?>
<document>
    <%= @users.to_xml # serialize the @users variable %>
    <extra_string><%= @another %></extra_string>
</document>

(You can read about ActiveRecord's to_xml method here.)


text:
Q: Why asp.net model binder can not map a string values to a Object property that have the same name I have a model class named Server and I have created a new ServerToEdit viewModel class, as follow:-
public class ServerToEdit
    {
        public Server Server { get; set; }
       [Required]
        public String IPAddress { get; set; }
    }

Part of the Create view is:-
    model TMS.ViewModels.ServerToEdit

    @* This partial view defines form fields that will appear when creating and editing entities *@
     @Html.AntiForgeryToken()

        @Html.LabelFor(model => model.Server.CustomerName)

        @Html.EditorFor(model =>model.Server.CustomerName)
        @Html.ValidationMessageFor(model =>model.Server.CustomerName)

       IP Address

        @Html.EditorFor(model => model.IPAddress)
        @Html.ValidationMessageFor(model => model.IPAddress)

IPAddress

    @Html.LabelFor(model =>model.Server.ILOIP)

    @Html.EditorFor(model =>model.Server.ILOIP)
    @Html.ValidationMessageFor(model =>model.Server.ILOIP)

The Create actin method is :-
[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Server server, TechnologyIP technologyIP)
        {
           try
           {
               if (ModelState.IsValid)
           {
                repository.InsertOrUpdateServer(server,technologyIP);
                repository.Save();
                return RedirectToAction("Index");
            }

but the model binder was not able to bind the IPAddress field inside my view to the TechnologyIP.IPAddress property? the technologyIP model class is :-
public class TechnologyIP
    {
        public String IPAddress { get; set; }

        public int ID { get; set; }
    }

A: On first look, I would imagine that it's because the model you passed to the view is not the same model you are asking for back. Change this line:
public ActionResult Create(Server server, TechnologyIP technologyIP)

to
public ActionResult Create(ServerToEdit serverToEdit)

and this line:
repository.InsertOrUpdateServer(server,technologyIP);

to
repository.InsertOrUpdateServer(serverToEdit.Server, serverToEdit.technologyIP);

Let us know how you get on.


text:
Q: how to include Bootstrap.css in angular2 final release I am trying to include bootstrap.css locally in angular2 final release.
I put bootstrap.css in dist/assets/css folder.
In index.html i put
<link rel="stylesheet" href="./assets/css/bootstrap.css" />

But its not working.
Dont know whats wrong.
project is generated through angular-cli.
Plz help.
thanks

A: Don't place it in dist folder. Place it somewhere else, u can place inside app/assets.. During build dist folder is overridden.

A: As you are using angular-cli you can follow steps given on Global Library Installation to update your angular-cli.json.


text:
Q: General Term For Getting Property Of A Nullable Object Considering the JavaScript below:
var foo = undefined;
if(foo?.bar == true){
    console.log("Wow. Impossible...");
}

Is there a general programming term for the ?. following the foo variable?
This allows you to compare a member of a potentially null object without having to explicitly check if the variable is null.
I'd like to be able to see if this functionality exists in other languages, but I'm not really sure what to look up.

A: It is known as Optional Chaining in JS.
Ref:

*

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

*https://javascript.info/optional-chaining
It is known differently in different languages, e.g. in C# it is called Null-Conditional.


text:
Q: I want to put 0 instead of negative values from DATEDIFF The table with the following structure is considered:
MEDICINE: (name, price, quantity, expiration_date );
I did
SELECT Name,
DATEDIFF(expiration_date, CURRENT_DATE)
AS days
FROM MEDICINE;

I got negative results from datediff, but I want to put 0 instead of the negative values. How can I make this? Any help?

A: Try this:
SELECT  Name
,       CASE
            WHEN DATEDIFF(expiration_date, CURRENT_DATE) < 0 THEN 0
            ELSE DATEDIFF(expiration_date, CURRENT_DATE)
        END AS days
FROM MEDICINE;

Unfortunately you have to repeat the expression, but the engine should be smart enough to only calculate it once.

A: This should work for you.
GREATEST(0, DATEDIFF(expiration_date, CURRENT_DATE))

Read about these conditional operators here. Spend some time reading about the suite of functions and operators in your SQL language: it's time well spent.

A: You can use GREATEST() in combination with a - because DATEDIFF() doesn't exist in PostgreSQL:
SELECT Name,
 GREATEST(expiration_date - CURRENT_DATE, 0)
AS days
FROM MEDICINE;

A: You can do it using SQL case.
This should work:
SELECT Name,
CASE WHEN DATEDIFF(expiration_date, CURRENT_DATE) > 0 THEN DATEDIFF(expiration_date, CURRENT_DATE)
ELSE 0
END
AS days
FROM MEDICINE;

You can read more about it here: https://www.w3schools.com/sql/sql_case.asp


text:
Q: How to use/do coding on a same web application between two people We are a two man team working on a same c#, .net web application. Now everytime we do anything we have to merge our files. Also we can not work on same files together. We know we can use a source safe so that we can work together on the same project at a time but not sure how to use it on our desktop pc (we do not have a server where we can put our code). Any suggestion will be greatly appreciated.

A: Git is helpful and keeps track of changes
See more on http://www.git-scm.com/


text:
Q: Is Otis in the Bumblebee (Transformers) movie Charlie's half-brother, adopted brother, or step-brother? Is Otis the son of Ron and a deceased first wife of his?

A: Per the official novelisation, Ron is Otis and Charlie's stepfather.

Her mother, Sally, was washing dishes, and her stepfather, Ron, was drying. Sally was a nurse and was wearing scrubs. Sally and Ron giggled about something, and then they kissed.
...
"Ah, Otis-san!" Ron said.
"Hiiiii -yah!" Otis said again. His hands launched out and chopped at
the air in front of his stepfather.

Sally appears to be their their shared biological mother (noting that Charlie repeatedly calls out Ron as her stepfather, but only ever refers to Otis as her brother.
Their shared biological father died quite recently of a heart attack, which is a point of contention with her mother.


text:
Q: Java string replace and the NUL (NULL, ASCII 0) character? Testing out someone elses code, I noticed a few JSP pages printing funky non-ASCII characters. Taking a dip into the source I found this tidbit:
// remove any periods from first name e.g. Mr. John --> Mr John
firstName = firstName.trim().replace('.','\0');

Does replacing a character in a String with a null character even work in Java? I know that '\0' will terminate a C-string. Would this be the culprit to the funky characters?

A:
Does replacing a character in a String with a null character even work in Java? I know that '\0' will terminate a c-string.

That depends on how you define what is working. Does it replace all occurrences of the target character with '\0'? Absolutely!
String s = "food".replace('o', '\0');
System.out.println(s.indexOf('\0')); // "1"
System.out.println(s.indexOf('d')); // "3"
System.out.println(s.length()); // "4"
System.out.println(s.hashCode() == 'f'*31*31*31 + 'd'); // "true"

Everything seems to work fine to me! indexOf can find it, it counts as part of the length, and its value for hash code calculation is 0; everything is as specified by the JLS/API.
It DOESN'T work if you expect replacing a character with the null character would somehow remove that character from the string. Of course it doesn't work like that. A null character is still a character!
String s = Character.toString('\0');
System.out.println(s.length()); // "1"
assert s.charAt(0) == 0;

It also DOESN'T work if you expect the null character to terminate a string. It's evident from the snippets above, but it's also clearly specified in JLS (10.9. An Array of Characters is Not a String):

In the Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NUL character).

Would this be the culprit to the funky characters?

Now we're talking about an entirely different thing, i.e. how the string is rendered on screen. Truth is, even "Hello world!" will look funky if you use dingbats font. A unicode string may look funky in one locale but not the other. Even a properly rendered unicode string containing, say, Chinese characters, may still look funky to someone from, say, Greenland.
That said, the null character probably will look funky regardless; usually it's not a character that you want to display. That said, since null character is not the string terminator, Java is more than capable of handling it one way or another.

Now to address what we assume is the intended effect, i.e. remove all period from a string, the simplest solution is to use the replace(CharSequence, CharSequence) overload.
System.out.println("A.E.I.O.U".replace(".", "")); // AEIOU

The replaceAll solution is mentioned here too, but that works with regular expression, which is why you need to escape the dot meta character, and is likely to be slower.

A: Should be probably changed to
firstName = firstName.trim().replaceAll("\\.", "");

A: I think it should be the case. To erase the character, you should use replace(".", "") instead.

A:
Does replacing a character in a String
  with a null character even work in
  Java?

No.

Would this be the culprit to the funky characters?

Quite likely.

A: This does cause "funky characters":
System.out.println( "Mr. Foo".trim().replace('.','\0'));

produces:
Mr[] Foo

in my Eclipse console, where the [] is shown as a square box.  As others have posted, use String.replace().


text:
Q: Connecting to RabbitMQ service inside Docker container failing I am having trouble connecting to a dockerized RabbitMQ container. I am trying to connect to it using another docker service I wrote.
My docker-compose.yaml file is below:
version: "3.9"
services:
    rabbitmq:
        hostname: "rabbitmq"
        image: "rabbitmq:3-management"
        container_name: "rabbitmq"
        ports:
            - "5672:5672"
            - "15672:15672"
        stdin_open: true
        tty: true

    my_app:
        image: 'my-app'
        container_name: 'my-app'
        build: ./my_app
        ports:
            - "8000:8000"
        volumes:
            - ./my_app:/src
        command: python manage.py runserver 0.0.0.0:8000
        env_file: ./common.env
        stdin_open: true
        tty: true
        depends_on:
            - "rabbitmq"
        networks:
            - sandbox
networks:
    sandbox:
        name: sandbox_network

Now, my producer code looks as follows:
credentials = pika.PlainCredentials("guest", "guest")
        connection = pika.BlockingConnection(
            pika.ConnectionParameters("rabbitmq", 5672, "/", credentials)
        )
        channel = connection.channel()

        channel.queue_declare(queue="croudie_creation")

        channel.basic_publish(exchange="", routing_key="hello", body="Hello World!")

        print(" [x] Sent 'Hello World!'")

        connection.close()

I keep getting the following error message:
Error message
Could someone please help me out here?


text:
Q: Xcode is displaying colors inline in the code How to prevent Xcode from displaying colors inline
let colors:[UIColor] = [
    #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1),
    #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1),
    #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1),
    #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1),
    #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1)
]

renders the color values in boxes inline.
How to prevent this from happening?

A: The other answers may prevent the color display, but make your code run slower, because every time the initialiser is used there is real code being run to create an Objective-C object. The #colorLiteral doesn't generate any code.
And I can't quite get why you are opposed to actually seeing the colors.

A: Use the UIColor(red:green:blue:alpha) initializer instead of color literals.
let color = UIColor(red: 0, green: 1, blue: 1, alpha: 0)

A: Use like below example:
static let Blue : UIColor = UIColor(red: 43.0/255.0, green: 81.0/255.0, blue: 162.0/255.0, alpha: 1.0)


text:
Q: C++ How to avoid repetitive code for variables of different third-party type? I have class that is managing a number of similar member variables of different, but similar type.
class Manager {
  Type1 a;
  Type2 b;
  Type3 c;
  void process();
};

Although the types are different, they share some functions and attributes. At least this lets me use some templated functions to process the class members in a similar way.
template <typename T>
void process(T& t) {
  // do something with t
}

void Manager::process() {
  process(a);
  process(b);
  process(c);
}

At one point in my program I also need to supply strings equal to the member variable names.
template <typename T>
void print(T t, std::string name) {
  std::cout << name << ": " << t.msg << std::endl;
}

void Manager::print() {
  print(a, "a");
  print(b, "b");
  print(c, "c");
}

I have reduced the code samples to illustrate my problem. In reality, there are many more places where I simply copy-paste entire blocks of code for each variable. Every now and then, a new member variable with a new type is added.
What pattern can I use to avoid these seemingly unnecessary repetitions of similar code?
I have thought of something like a std::map<std::string, ParentType> members;. I guess this would allow me to loop over all member variables instead of copy-pasting code and I could also store a corresponding name string for each variable. However, the types that I use have no common parent class and are third-party, i.e. I cannot modify the implementation of Type1/Type2/Type3/...
I guess what I really want is to have only a single place where I define types and names and then being able to simply loop over all variables for performing similar processing.
I can think of partially solving this using preprocessor macros, but aren't those rather discouraged in modern code?

A: It seems like this is exactly the use case for the preprocessor---removing repeating code and stringifying identifiers. If you don't like it, and you don't mind the horrible syntax, you could make Manager a tuple:
class Manager {
    std::tuple<Type1, Type2, Type3 /* more types can be added ... */> tup;
}

Then you can run a function on each element using std::apply. See Template tuple - calling a function on each element.
void Manager::process() {
    std::apply([](auto ...x){
        std::make_tuple(process(x)...);
    }, this->tup);
}

Without reflection I believe there is no cleaner solution. And your stringify print example is impossible without macros.

A: You might create template function for your class, something like:
class Manager {
  Type1 a;
  Type2 b;
  Type3 c;

  template <typename F>
  void apply(F f)
  {
    f(a); f(b); f(c);
  }
  template <typename F>
  void apply_with_name(F f)
  {
    f("a", a); f("b", b); f("c", c);
  }

  void process() { apply([](auto& t){ t.process(); }); }
  void print() { apply_with_name([](const std::string& name, auto& t){ std::cout << name << ": " << t.msg << std::endl; }); }
};


text:
Q: Axiom of Choice implies the Well-Ordering Principle I am trying to understand the proof of this implication we were taught in my set theory module. I cannot seem to tie it together with the final line of the argument... We used this lemma:

Given $F\colon \mathcal{P}(X)\to X$, there exists a unique well-ordered set $(W,<)$ such that

*

*$W\subseteq X$;

*for all $x\in W$, we have $F(\{y\in W:y<x\})=x$; and

*$F(W)\in W$.

The proof given is:

Let $\sigma\colon\mathcal{P}(X)\to X$ be a choice function (technically defined on $\mathcal{P}(X)-\{\emptyset\}$ but we may let $\sigma(\emptyset)$ be any member of $X$). Take $F\colon\mathcal{P}(X)\to X$ defined as $F(A)=\sigma(X-A)$ and apply the lemma.

How does the lemma yield the well ordering principle? I assume that we want $W$ to be $X$ since WO states that the well-ordering relation is on the set $X$ (for all $X$).

A: Yes, the point is that $W=X$.
The key to that is the last part of the conclusion of the lemma: $F(W)\in W$, which is the same as $\sigma(X\setminus W)\in W$. If $X\setminus W$ is nonempty, then this contradicts $\sigma$ being a choice function, so the only way we can have $\sigma(X\setminus W)\in W$ is if $X\setminus W=\varnothing$, in which case $\sigma(\varnothing)$ is just some member of $X$.
Since $W\subseteq X$ and $X\setminus W=\varnothing$, it must be that $W=X$.


text:
Q: AKMIDIListener: ReceivedNoteOn unable to change UI Components I am creating an application that receives MIDI notes and plays music in the app according to the note it received. I am using AudioKit's AKMIDIListener protocol and the function receivedMIDINoteOn. It am able to recieve these events and play the notes that I want to play from my app accordingly. However, I am also trying to change UI components within the ReceivedMIDINoteOn function, but I am unable to do so. Otherwise, the receivedMIDINoteOn is handling it's events correctly, the UI simply won't change to reflect this for some reason. The UIViewController that I am changing also has the AKMIDIListener protocol, and the receivedMIDINoteOn function is also defined in that UIViewController. I have provided a code snippet below to help ID the problem. Why might the UI components not update? In the code below, the "playButton" is not being updated when it receives the MIDINoteOn function, even though I know the function runs because it plays the background music. Also, the playButton changes it's title accordingly whenever I use change the title in some other function in my code
let midi = AudioKit.midi

class firstPageViewController: UIViewController, AKMIDIListener {

@IBOutlet var MusicButtons: [UIButton]!
@IBOutlet var playButton: UIButton!
@IBOutlet var pauseButton: UIButton!
@IBOutlet var WaveForm: AudioVisualizationView!

@IBOutlet weak var firstButton: UIButton!

@IBOutlet weak var secondButton: UIButton!

@IBOutlet weak var thirdButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    isOnFirstPage = true
    isOnSecondPage = false
    isOnThirdPage = false
    self.secondButton.setTitleColor(UIColor.blue, for: .normal)
    self.thirdButton.setTitleColor(UIColor.blue, for: .normal)
    midi.openInput()
    midi.addListener(self)
    self.init_buttons()
    self.init_soundwave()
    self.init_audio()
}

func receivedMIDINoteOn(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) {
    let currNum = mapping[Int(noteNumber)]
    if currNum == 64 { //Play button
        self.playBackground(0)
        self.playButton.setTitle("Currently Playing", for: .normal)
    }
    else if currNum == 67 { //Pause button
        self.pauseMusic(0)
        self.playButton.setTitle("Play", for: .normal)
    }
    else if currNum == 68 { //Switch button - first page
        self.firstPageSwitch(0)
    }
    else if currNum == 69 { //Switch button - second page
        self.secondPageSwitch(0)
    }
    else if currNum == 70 { //Switch button - third page
        self.thirdPageSwitch(0)
    }
    else if currNum == 71 {
        //
    }
    else if currNum == 65 {
        //
    }
    else if currNum == 66 {
        //
    }
    else {
        if isOnFirstPage! {
            self.playMusic(currNum: currNum!, holder: audioPlayer)
            self.MusicButtons![currNum!].backgroundColor = UIColor(red: 247/255, green: 183/255, blue: 98/255, alpha: 1.0)
        }
        if isOnSecondPage!{
            self.playMusic(currNum: currNum!, holder: secondAudioPlayer)
            self.MusicButtons![currNum!].backgroundColor = UIColor(red: 247/255, green: 183/255, blue: 98/255, alpha: 1.0)
        }
    }
}

}

A: The commenter is correct, you need wrap your UI calls in a
DispatchQueue.main.async {

  // ... code here

}

And also perhaps will have to put an self.playButton.setNeedsDisplay() at the end.


text:
Q: Azure DevOps SSH release pipeline task and Docker Compose STDERR I am using Classic release pipelines in Azure DevOps and configured simple SSH task what calls docker-compose:
cd /home/asem/platform/$(ServiceName) && sudo docker-compose up -d --force-recreate

Issue: task fails with errors:

Docker-compose returns 0 exit code, but write some messages in STDERR. Pipeline task treat them as errors and fails.
Questions:

*

*Why docker-compose designed that way what EXIT code = 0, but there are some errors were written in STDERR ?

*Any good solution (please see found workarounds in my answer below) ?

A: Workaround 1: pipe docker compose STDERR to STDOUT like cd /home/asem/platform/$(ServiceName) && sudo docker-compose up -d --force-recreate 2 >&1
sudo docker-compose up -d --force-recreate 2 >&1
That works, but I don't like it because it can hide some real errors
Workaround 2: Uncheck "Fail on STDERR" for task

That works, but release stage displays errors which is not good though.


text:
Q: Is it possible to upgrade a device owner app through Google Play? I've created a device owner app, which I install through a QR code when I factory reset my devices. Everything's fine until here.
Now I have a new version of the same device owner app, and I want to update the devices which have the previous version to this new version.
Is it possible to achieve this using Google Play?
I don't want to use custom methods like uploading the APK somewhere and downloading it with some Java code, because I want to centralize the releases in Google Play.
So far I have uploaded the new version (version code is 5, old one is 2) of the app to Google Play and tried to upgrade from there, but it does not work: in Google Play I just see the app as installed, and the "Disable" and "Open" button, but not the button to upgrade it.
Any thoughts? I've found some posts like the ones below, but they're 5 years old, maybe something has changed and this is not longer possible.

*

*Install updates for a Device-Owner App

*Install a GooglePlay located App from NFC
I haven't been able to find any specific information on updates with device owner apps. The documentation is extensive about how to create and install a device owner app, but not on how to upgrade it.
Thanks a lot in advance!

A: You didn't install it from play store , I THINK you can't update Device-Owner apps which were not installed from play store , except for the way you mentioned.


text:
Q: Can't refresh webquery in Excel 2016 Since a few weeks I am using Office 2016 and I have a few Excel spreadsheets that collect data from my own webservice using a web query. As you can see, the webservice has the right properties in the connections dialog:

When I refresh, I always get the following error message:

It's in Dutch, but the error message says "Can't find Data Source". As you can see, the url of the webservice is not fully displayed. I can't find anything about it on Google, but did the length of a valid web query url change in the new version of Excel?
It works perfectly fine in Excel 2013 and Excel 2010.

A: After applying the Office Click-To-Run update (1609) to Excel 2016, I experience the same issue. It works in previous Excel versions, including 2013 and 2010. It seems a part of the URL in the GET request Excel makes is cut off.
By rolling back Office Click-To-Run update (1609), the problem disappears.
I have ended up working around this by shortening my URL's. This is probably only a solution to others if they can use an URL-shortening service (TinyUrl) or have control of the webservice.
It really seems like an Excel bug.


text:
Q: Rendered more hooks than during the previous render.(component exception) My code is(shortForm)
import..
export default function App({ navigation }) {
   function HomeScreen({ navigation }) {
   ...
   }
   const [ItemURL, setItemURl] = useState('URL')
   return (
        <ItemContext.Provider value={ItemURL}>
            ...
        </ItemContext.Provider>
    )
}

I am trying to add context API in my app. I am getting this error when trying to add useState.
Full code
export default function App({ navigation }) {
    function HomeScreen({ navigation }) {
        const [WantLogIn, setWantLogIn] = useState(false)
        const [OpenAnimation, setOpenAnimation] = useState(0)

        useEffect(() => {
            ...
        }, [OpenSetting])

        useEffect(() => {
            ...
        }, [ItemOpen])

        useEffect(() => {
            ...
        }, [OpenAnimation])
        return (
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                ...
            </View>
        )
    }

    const [loaded1] = useFonts({
        Poppins_Bold: require('./assets/fonts/Poppins-Bold.ttf'),
    })
    if (!loaded) {
        return null
    } else {
        setCustomText(customTextProps)
    }
    if (!loaded1) {
        return null
    }
    const [ItemURL, setItemURl] = useState('URL')

    return (
        <ItemContext.Provider value={ItemURL}>
            <ApplicationProvider {...eva} theme={{ ...eva.light, ...theme }}>
                <NavigationContainer>
                    <Stack.Navigator headerMode='none' mode='model' screenOptions={{}}>

                    </Stack.Navigator>
                </NavigationContainer>
            </ApplicationProvider>
        </ItemContext.Provider>
    )
}

This is my full code and removed some unnecessary things.I used react navigation in this app(is that making any problems).
When I put const ItemURL on the top of the other const of app function it starts working.

A: You are using the useState('URL') after checking for loaded. If not loaded, the function returns null and nothing is rendered, but also, the last useState is never reached.
Now if the fonts are loaded, the return state is not called and the useState is called. Now you have a different number of hooks calls, which is forbidden.
Move the useState above the early return of (!loaded).
export default function App({ navigation }) {
    function HomeScreen({ navigation }) {
        const [WantLogIn, setWantLogIn] = useState(false)
        const [OpenAnimation, setOpenAnimation] = useState(0)

        useEffect(() => {
            ...
        }, [OpenSetting])

        useEffect(() => {
            ...
        }, [ItemOpen])

        useEffect(() => {
            ...
        }, [OpenAnimation])
        return (
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                ...
            </View>
        )
    }

    const [loaded1] = useFonts({
        Poppins_Bold: require('./assets/fonts/Poppins-Bold.ttf'),
    })

    const [ItemURL, setItemURl] = useState('URL') // MOVE THIS UP

    if (!loaded) {
        return null
    } else {
        setCustomText(customTextProps)
    }
    if (!loaded1) {
        return null
    }

    return (
        <ItemContext.Provider value={ItemURL}>
            <ApplicationProvider {...eva} theme={{ ...eva.light, ...theme }}>
                <NavigationContainer>
                    <Stack.Navigator headerMode='none' mode='model' screenOptions={{}}>

                    </Stack.Navigator>
                </NavigationContainer>
            </ApplicationProvider>
        </ItemContext.Provider>
    )
}


text:
Q: sequelize findall with count every relation child for each parent and thank for the answers.
i use nodejs / sequelize / mysql
this is my problem:
i have table client like this:
id username age name
----------------------
12 seveun   25  john  |
----------------------
10 superlol 12  johny |
----------------------

the table client has one to many relation with statistic table
the statistic table seem like this :
id  gain  profit clientId
-------------------------
12  22     25      12   |
-------------------------
10 34      12      12   |
-------------------------
10 34      12      10   |
-------------------------

i want this result :
{
 client: [
  {
    'username': 'seveun',
    'statistic': [total: 2]
  },
  {
    'username': 'superlol'
    'statistic': [total: 1]
  }
 ]
}

i test this sequelize code :
await ClientModel.findAll({
  include: [
   {
     as: 'statistic',
     model: StatisticModel,
     attributes: [
       [[Sequelize.fn("COUNT", Sequelize.col("statistic.id")), "total"]]
     ],
   },
 ],
});

but the count, count every statistic, not statistic for each parent
my result is :
client: [
  {
    'username': 'seveun',
    'statistic': [total: 3]
  }

thanks a lot for your help

A:
This should work perfectly fine for 1:m associations. Lets you count children for every parent. But, for some reason, this doesn't work for multiple 'include's. So NOTE!!!:

*

*trying to count grand-children breaks the entire query

*trying to get attributes of children breaks the entire query

sequelize: 5.21.11

await ClientModel.findAll({
  include: [
    {
      as: 'statistic',
      model: StatisticModel,
      attributes: [], // empty array is important here!
     },
  ],
  attributes: [
    'id', [Sequelize.fn("COUNT", Sequelize.col("statistic.id")), "total"]
  ],
  group : ['ClientModel.id'], // group only by parent.id here!
});

A: Aggregation must be done on the parent model according to  this issue
Try the following code for your use case
  await ClientModel.findAll({
    attributes: [
      "username",
      [Sequelize.fn("COUNT", Sequelize.col("statistic.id")), "total"],
    ],
    include: [
      {
        as: "statistic",
        model: StatisticModel,
        attributes: [],
      },
    ],
    group: ["ClientModel.id"],
  });

Sequelize >= 3.0.1


text:
Q: A good Minimax representation in Gomoku? I am trying to code a Gomoku (five in a row) game in Java as an individual project.  For the AI, I understand that the use of a Minimax function with Alpha-beta Pruning is a good way to approach this.  However, I'm having a little trouble envisioning how this would work.
My question is this: what is a good representation for a node in a minimax tree?
I'm thinking my evaluation function will "weight" all the empty spaces on the board.  It will then take the best value from that board as the node of the minmax decision tree.  Am I on the right direction?
And any other tips are also welcome!
Thanks in advance!

A: The state space search is through the different states of the board. There are a lot of moves, since you can place a stone anywhere unoccupied. Each state can be represented as a e.g. 9x9 matrix, with 3 values -- white, black, or unoccupied. With a 9x9 board, there are therefore 3 ^ 81 possible board states.
From any board state, the number of moves is the number of unoccupied vertices. You can place a stone on any of these vertices. You can only play your own color. So, at most there are 81 possible moves .. 81 for the first move, 80 for the second, and so on. So you can search to depth 5 reasonably, and possibly more .. not too bad.
The proper representation is, as mentioned, a 2D matrix -- this can just be a 2D array of ints, with values e.g. 0 for unoccupied, 1 for white, 2 for black. ... int[9,9].
Your evaluation function doesn't sound very good. Instead, I would give points for the following:
-- get 5 in a row -- basically give it the max score for this one, since it's a win
-- 4 in a row with 2 open ends -- also max score, since opponent can't block you from getting 5.
-- 4 in a row with 1 open end -- still a very threatenning position, since opponent has to play
in one spot to block.
-- 3 in a row with 2 open ends -- very high score again
--- 4, 3, 2, 1 with both closed ends -- 0, since can't ever make 5 in a row.
and so on.
Then, you just apply the standard minimax algorithm -- i.e. alpha beta pruning -- it would be exactly the same as chess, but you have a different state space generator and evaluation function.

A: I'd consider an evaluation function of the following form: consider each set of, say, 6 positions in a line. (On a 19x19 board there are 14 along each line and varying numbers from 0 to 14 along each diagonal; I think that comes to 742 of these on the whole board. My arithmetic may be wrong.) For each set there are 729 possible arrangements of black, white and empty spaces. Or, er, 378 if you take end-to-end symmetry into account. Or, er, um, fewer than that but I can't be bothered to work out how many fewer if you take black/white symmetry into account too.
So now your evaluation function will consist of a table-lookup for each block of 6 stones, in a 378-or-however-many-element table (or perhaps two of them, one for horizontal and vertical lines, one for diagonal ones). Add up the results and that's your evaluation of the position.
It may turn out that actually a larger table (derived from a longer row of positions) works better.
But what goes in the table? Let your program work that out. Start with arbitrary values in the table (you might, e.g., take eval(line) = #black(line)-#white(line) or something). Let your program play itself, using alpha-beta search. Now update the table entries according to what happens. There are many different ways of doing this; here are a (sketchily-described) few.

*

*During each game, keep track of how many times each pattern occurred in each player's positions. When the game's over, adjust each pattern's score so that patterns seen more often by the winning player look better.

*Each time you do a search, adjust the scores for the patterns in the current position to bring the current static score nearer to the score obtained by search.

*Each time a move is made, adjust the scores for each pattern in the "before" position to make the "before" score match the "after" score better.

*Have lots of different tables (hence lots of different variants of the evaluation function). Let them play against one another. Apply some sort of evolution (e.g., play all against all, then throw out the worst performers and replace them with mutants derived from the better performers).

For a more sophisticated version of these ideas (applied to chess, but the same ideas would work fine for gomoku), take a look at http://cs.anu.edu.au/~Lex.Weaver/pub_sem/publications/knightcap.pdf .


text:
Q: Representing a 4D array as a 1D array python I'd like to understand how to correctly represent a 4-dimensional array as a 1-dimensional array and so that I can get the indexing correct (i.e retrieve the array entry in the 1D array given the 4 input coordinates ). Can anyone please point me to the correct indexing for the 4-D array?
I have a minimal example here (where I set the odd numbered index entries of the array as 1). The dim4_index is the particular counter of interest.
#python script to count a 4-d array and check that we get what we expect
import numpy as np
from numpy import zeros
x_arrsize=3
y_arrsize=x_arrsize+1
z_arrsize=x_arrsize+1
w_arrsize=x_arrsize+1
a=zeros([x_arrsize,y_arrsize,z_arrsize,w_arrsize])
print a
#set every entry not divisible by 2 to 1
for x in range(0, x_arrsize):
    for y in range(0, y_arrsize):
        for z in range(0,z_arrsize):
            for w in range(0,w_arrsize):
                if((x%2>0) or (y%2>0) or (z%2>0) or (w%2>0)):
                    a[x][y][z][w]=1

flat_arr=a.flatten()
print flat_arr

print('\n')
for i in range(0,x_arrsize):
    for j in range(0,y_arrsize):
        for k in range(0,z_arrsize):
            for l in range(0,w_arrsize):
                # use stack overflow formula here

                #index each unique hit in the array:
                #arrays are indexed as follows:
                # N dim representation:
                # (Hit, Stream, Block, Thread)
                #formula from stack overflow:
                #  Array[N,M,K,L] - > 1d rep is Array[N*M*K*L]
                #  flat_index(i,j,k,l) -> 1d rep -> (M*N*K)*i+(M*N)*j+M*k+l

                index_firstpart=(x_arrsize)*(y_arrsize)*(z_arrsize)
                index_secondpart=(x_arrsize)*(y_arrsize)
                index_thirdpart=(y_arrsize)
                # 1D representation
                dim4_index=index_firstpart*i+index_secondpart*j+index_thirdpart*k+l
                val_orig=a[i][j][k][l]
                if(a[i][j][k][l]>0):
                    print("Original coordinates ({},{},{},{}), New index: {},val_orig: {} val_new: {}".format(i,j,k,l,dim4_index,val_orig,flat_arr[dim4_index]))

This logic seems to work ok when the n-dimensional array is a hypercube (so NxNxNxN but when I change it to MxNxNxN) I find that some the flattened array is not correctly called (i.e. a zero entry is retrieved when I expected 1).
So my representation formula might not be quite accurate.
Is there a general formula for representing this conversion from 4D -> 1D? And I would prefer a non-numpy solution if possible (the formula for the conversion is what I'm looking for).
Linked formula I tried to use: Need of an algorithm for arrays index in a flat representation
Any input would be appreciated.

A: Have now tried a new example instead starting from first principles:
import numpy as np
from numpy import zeros
arrsize=10
x_arrsize=arrsize
y_arrsize=arrsize+1
z_arrsize=arrsize+2
w_arrsize=arrsize+3
a=zeros([x_arrsize,y_arrsize])
for x in range(0,x_arrsize):
    for y in range(0,y_arrsize):
        if((x==y)):
            a[x][y]=1 # define as 1 if X=Y=Z
print("2D EXAMPLE")
print a
flat_arr=a.flatten()
print flat_arr
print("DIRECT REPRESENTATION (2D)")
for itr in range(0,len(flat_arr)):
    if(flat_arr[itr]>0):
        print (itr,flat_arr[itr])
print("TRANSFORMATION (2D)")
for x in range(0,x_arrsize):
    for y in range(0,y_arrsize):
        dim2_index=x+y*x_arrsize
        if(flat_arr[dim2_index]>0):
            print(dim2_index,flat_arr[dim2_index])

print("3D EXAMPLE")

b = zeros([x_arrsize,y_arrsize,z_arrsize])
for x in range(0,x_arrsize):
    for y in range(0,y_arrsize):
        for z in range(0,z_arrsize):
            if(x==y):
                b[x][y][z]=1

flat_b=b.flatten()
print("Flattened representation (3D)")
valid_itrs=[]
for itr in range(0,len(flat_b)):
    if(flat_b[itr]>0):
        print(itr,flat_b[itr])
        valid_itrs.append(itr)
print("Transformed representation (3D)")
for x in range(0,x_arrsize):
    for y in range(0,y_arrsize):
        for z in range(0,z_arrsize):
            dim3_index=x+y*x_arrsize+z*y_arrsize*x_arrsize
            if(flat_b[dim3_index]):
                isValidItr=(dim3_index in valid_itrs)
                print (dim3_index,flat_b[dim3_index],isValidItr)

print("\nNOW DOING 4D example")
c=zeros([x_arrsize,y_arrsize,z_arrsize,w_arrsize])
for x in range(0,x_arrsize):
    for y in range(0,y_arrsize):
        for z in range(0,z_arrsize):
            for w in range(0,w_arrsize):
                if((x==y) and (x==z)):
                    c[x][y][z][w]=1
print("4D flattened representation")
flat_c=c.flatten()
valid_itrs=[]
for itr in range(0,len(flat_c)):
    if(flat_c[itr]>0):
        print(itr,flat_c[itr])
        valid_itrs.append(itr)
print("TRANSFORMED (4D)")
for x in range(0,x_arrsize):
    for y in range(0,y_arrsize):
        for z in range(0,z_arrsize):
            for w in range(0,w_arrsize):
                dim4_index=x+y*x_arrsize+z*y_arrsize*x_arrsize+w*z_arrsize*y_arrsize*x_arrsize
                isValid=(dim4_index in valid_itrs)
                if(isValid):
                    print (dim4_index,flat_c[dim4_index],isValid)
                elif(flat_c[dim4_index]>0):
                    print(dim4_index,flat_c[dim4_index],isValid)
                else:
                    continue

which now appears to produce the correct answer (the isValid check always shows True - basically the ordering of x,y,z,w loop might not be best to get the sequential ordering of the 4D index).
So the formula I found is:
dim4_index=x+y*x_arrsize+z*y_arrsize*x_arrsize+w*z_arrsize*y_arrsize*x_arrsize


text:
Q: What's the difference between $f(x)=\sqrt{x^2+9}$ and $k(x^2+9)=\sqrt{x^2+9}$? Let's say we 've got a function $f(x)=\sqrt{x^2+9}$, which is a composite function. $f(x)=\sqrt{g(x)}$ and $g(x)=x^2+9$.
When we have a function like $h(x)=x$, we are allowed to set $x$ to $x+9$ and have $h(x+9)=x+9$.
So why do we need $g(x)$ and can't just set $x=x^2+9$, which with a function like $k(x)=\sqrt{x}$ leads to $k(x^2+9)=\sqrt{x^2+9}$ (same as f(x) above)?
Where's the difference between these two ($f(x),k(x)$)? Is $x^2+9$ even a valid argument for $k(x)$?

A: A function is a mapping from elements of a domain set to elements of a range set (also called the "codomain").  Let's consider your example of $k(x) = \sqrt{x}$.  This actually is an incomplete definition of a function; you also need to specify the domain and range.  So suppose $k$ takes nonnegative real numbers to nonnegative real numbers.
Then when we take the function $g(x) = x^2+9$, we again have to specify the domain and range.  So let's say $g$ takes real numbers to real numbers greater than or equal to 9.
Now consider the composition $f(x) = k(g(x))$.  The equation is $\sqrt{x^2+9}$.  But now the domain and range have changed a bit from the original $k$ or $g$.  In particular, now the domain is all real numbers, and the range is real numbers greater than or equal to 3.  So there is a subtle difference between the functions $f(x)$ and $k(x)$.  It's important to keep the domain and range/codomain in mind whenever you do function composition.
Now to address your confusion regarding how we are "allowed" to set $x = x^2+9$ and write $k(x^2+9) = \sqrt{x^2+9}$.  Again, think about a function as taking inputs to outputs.  So when you write $k(x^2+9) = \sqrt{x^2+9}$, what you're saying is that given a number $x$, $k$ maps the number $x^2+9$ to $\sqrt{x^2+9}$.  This is really just a variable substitution.  There is nothing wrong with writing down $k(x^2+9)$, or $k(e^x)$; just like with $k(2)$ or $k(\pi)$, it represents passing some value into the function $k$.
Hopefully that addresses your questions, and let me know in the comments if I can clarify further!

A: $f(y)$ is a function which maps $y$ to $\sqrt{y^2+9}$, and you've fed $y=x$ into it to get your first function.
$k(y)$ is a function which maps $y$ to $\sqrt y$, and you've fed $y=x^2+9$ into it to get your second function.


text:
Q: How to submit form and remain on the same page There is a similar question which demonstrates how to do it in jQuery. Unfortunately, I'm using prototype and translating the code isn't very straight forward.
Submit form and stay on same page?
What needs to happen is the value (email) is posted to the page on the subDomain and the user does not get redirected. I do not have any control to edit the page on the subDomain.
Any assistance would be appreciated.
function submitEmailForm(){
        var userEmail = $('Text').value;
        $('EmailForm').action = 'http://subDomain.myDomain.com/?email_address='+userEmail;
        $('EmailForm').request({ onComplete: function(){ return false;} });
    }

<form method="post" id="EmailForm" onsubmit="submitMobileEmailForm(); return false;">
          <input type="text" id="Text"/>
          <input type="submit" id="Submit" value=""/>
</form>

A: You need to redirect it on the same page on click of button by JQuery.
http://www.webdeveloper.com/forum/archive/index.php/t-105181.html

A: You can simulate form submissions with AJAX.
(Note: I used an old project I worked on as a template, so some techniques I used might be a little old. For example, event handling might work differently.)
function ajaxFormSubmission(form)
{
    xhrThingy = yourFunctionForObtainingXMLHttpRequestInstance();// XHR support is different for various browsers, so you might need to have browser specific code.
    xhrThingy.onreadystatechange = eventHandlerHere;
    xhrThingy.open('POST', 'theFileThatWillHandleYourRequest.php', true);// The used arguments are: HTTP request Method, request url, asynchronous flag
    xhrThingy.setRequestHeader("Content-type", "application/x-www-form-urlencoded");// Simulating Form Submission

    var emailData = form.elements['Text'].value;// Extracting needed data from form
    var postData = "emailAddress=" + emailData;
    xhrThingy.send(postData);
}

The eventHandlerHere function can then check for a response. Something like this:
function eventHandlerHere()
{
    if (xhrThingy.readyState==4 && xhrThingy.status==200)
    {
        var response = xhrThingy.responseText
        // Do whatever you need to do with the email adress
    }
}

In the project I worked on, I used a nested method for quick prototyping, so your exact implementation will look different. For example, I reference the xhrThingy, which is only in scope because the function was nested inside the ajaxFormSubmission function.


text:
Q: Get Youtube subscriber count for a user I need to get the subscriber count/list of a Youtube user, is there any API which allows this. I have tried using

http://gdata.youtube.com/feeds/api/users/[username]

but this returns count of subscriptions not subscribers

A: There is subscriberCount in the returned xml , its the actual subscribers count of your channel .


text:
Q: How can i select top numbers from array column in postgresql 9.4 create table foo_table(foo_id int, foo_array int[], some_other_column text)

insert into foo_table(foo_array) values (ARRAY[1,3,8,32,55])
insert into foo_table(foo_array) values (ARRAY[2,4,9,31,38,92,99])
insert into foo_table(foo_array) values (ARRAY[5,12,15,35,47])
insert into foo_table(foo_array) values (ARRAY[6,7,13])

The foo_array arrays will have variable number of elements.
All the array elements will be unique and all the numbers in all arrays will also be unique.
I wonder that how can i select biggest 5 numbers from foo_array column which in that case would be 99,92,55, 47, 38.

A: select t.nr
from foo_table
  cross join lateral unnest(foo_array) as t(nr)
order by nr desc
limit 5

Alternatively somewhat shorter:
select unnest(foo_array) nr
from foo_table
order by nr desc
limit 5

Using a set-returning function in the select list is somewhat deprecated - or a least discouraged.


text:
Q: How to quote a string containing dollar sign $ and single quote '? My directory's name contains a $ and ', for example
:~$ export DIR=\$my\'dir
:~$ sh -c "ls $DIR"

How can I run above command without $my being expanded? I know the single quote doesn't work since the $DIR contains one.
Actually, the question came from using find command as follows:
:~$ find ./\$my\'dir -type d -exec sh -c 'ls "{}"' \;

It says ./\'dir: No such file or directory, if I remove the double quotes then it says unexpected EOF while looking for matching '.

A: Wow, some complex solutions here! I think all you need to do is this though:
find ./\$my\'dir -type d -exec sh -c 'ls "$1"' sh {} \;

Instead of putting the arguments into the sh command string, just use them as arguments to sh. Note the second sh is the value of $0, everything after that is a positional argument.
As for your full problem of finding directories not containing pdfs, you are usually always better off using find for this kind of thing rather than ls. This should be close to what you are looking for:
find . -type d \
  -exec sh -c '[ "$(find "$1" -maxdepth 1 -type f -iname "*.pdf")" = "" ]' sh {} \; \
  -print

A: Ok... here is a convoluted way to do it. It'll fail if the filenames contain new line characters.
  find . -type d -print0                          \ # get the directory list,
                                                  \ # separated by nulls
| xargs -0 ls -1 -d -Q --quoting-style=shell      \ # pick it with xargs, and use
                                                  \ # ls to apply shell quotes to each
                                                  \ # entry
| xargs -d '\n' -I '{}'                           \
        sh -c "ls {} | grep -qi \.pdf$ || echo {}"  # pick each quoted entry
                                                    # with xargs again
                                                    # (using -d, so it keeps the quotes)
                                                    # and insert it in the string

This relies on ls -Q --quoting-style=shell quoting with single quotes... otherwise, use single quotes on the argument to sh -c.
Ugh.

A: What you want is not easily possible because it is not possible to quote arbitrary strings from "outside" only (i.e. by enclosing in "" or ''). This could be done by quoting each character with \ but I don't see how that shall be done with simultaneously calling the shell.
This is possible:
echo "$DIR" | sed -e 's/./\\&/g' -e 's/^.*$/echo &/' | bash -s

But that cannot be put in an -exec statement. And the echo cannot be called from a shell because that shell would run into the quoting problem with the argument. You can make the find output the shell input:
find ./\$my\'dir -type d -print0  | xargs -0 -n 1 ls

But: You could write the string to a file and have the shell read it from there:
find ./\$my\'dir -maxdepth 0 -type d -fprint tmpfile -exec bash -c 'cat tmpfile' \;

Sorry, no, not even that works: find opens the file, does the -exec action and afterwards writes to the file... So... this works but is kind of crazy, of course:
find ./\$my\'dir -maxdepth 0 -type d -fprint tmpfile -exec bash -c '(sleep 1; cat tmpfile)&' \;

A: I'm not sure I understand your problem:
$ mkdir \$my\'dir
$ touch \$my\'dir/foo
$ ls $DIR
foo

As for finding subdirectories that don't include PDF files, just run this:
find . -type d -print0 | while IFS= read -r -d '' dir; do
    [ $(find "$dir" -iname "*.pdf"  | wc -l) -gt 0 ] || echo $dir;
done


text:
Q: Adsense shows an 'X-Frame-Options' to 'SAMEORIGIN' error Recently I noticed that all my websites give an error in Chrome console (removing adsense the error goes away):

Refused to display https://googleads.g.doubleclick.net/pagead/drt/si?p=******&dpt=1 in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

Nothing was changed, I don't use iframe, Ads is still visible. But I don't like this error, I read about youtube and maps error, but didn't find any about adsense.
What can I do to fix it?
Page of example: http://www.incinqueterre.com/en/trails-all

A: In my case the Google Publisher Toolbar was to blame - turning it off fixed the error.

A: I just started getting this error recently as well when using chrome.
From my searching around the interwebs, I found hte following information.  It appears to be a bug in the webkit engine (chrome, safari, et al):
Invalid 'X-Frame-Options' header from google's Doubleclick response
https://bugs.webkit.org/show_bug.cgi?id=110857
Once Chrome (and maybe others) upgrade their version of webkit it will go away.


text:
Q: PostgreSQL Database - Error Assistance I'm trying to create a query that will update the value of rgn_no and chp_cd within the table bue to the values of rgn_no and chp_cd within the table chapterassociation. I don't think the WHERE clause is any problems, but I'm getting the following error when I run it in:
SQL error:
ERROR:  insert or update on table "bue" violates foreign key constraint "bue_chp_cd_fkey"
DETAIL:  Key (chp_cd)=(CA3) is not present in table "chapter".

Any assistance is greatly appreciated!
SQL Query:
UPDATE bue SET
 rgn_no = chapterassociation.rgn_no,
 chp_cd = chapterassociation.chp_cd
FROM
 chapterassociation
WHERE
 bue.mbr_no IS NULL AND bue.chp_cd IS NULL
 AND bue.work_state = chapterassociation.work_state
 AND bue.bgu_cd = chapterassociation.bgu_cd

A: Read the error message:
ERROR: insert or update on table "bue" violates foreign key constraint
"bue_chp_cd_fkey" DETAIL: Key (chp_cd)=(CA3) is not present in table "chapter".

It says that one of your updates wants to set chp_cd to 'CA3', but that CA3 is not an allowed value, because a foreign key constraint wants the value 'CA3" to be present in the table "chapter". That's all.
There is nothing wrong with your query's syntax, it is just the fact that your query would cause the data to conflict with a constraint in the data model.


text:
Q: Very simple log4j2 XML configuration file using Console and File appender I'd like a very simple XML configuration file with a console and a file appender using log4j2.
(The Apache Website is killing me with much Information.)

A: There are excellent answers, but if you want to color your console logs you can use the pattern :
<PatternLayout pattern="%style{%date{DEFAULT}}{yellow}
            [%t] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green} %logger{36} - %message\n"/>

The full log4j2 file is:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="APP_LOG_ROOT">/opt/test/log</Property>
    </Properties>
    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT">
            <PatternLayout pattern="%style{%date{DEFAULT}}{yellow}
                [%t] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green} %logger{36} - %message\n"/>
        </Console>
        <RollingFile name="XML_ROLLING_FILE_APPENDER"
                     fileName="${APP_LOG_ROOT}/appName.log"
                     filePattern="${APP_LOG_ROOT}/appName-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout pattern="%d{DEFAULT} [%t] %-5level %logger{36} - %msg%n"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="19500KB"/>
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="error">
            <AppenderRef ref="ConsoleAppender"/>
        </Root>
        <Logger name="com.compName.projectName" level="debug">
            <AppenderRef ref="XML_ROLLING_FILE_APPENDER"/>
        </Logger>
    </Loggers>
</Configuration>

And the logs will look like this:

A: <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="MyFile" fileName="all.log" immediateFlush="false" append="false">
            <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console" />
            <AppenderRef ref="MyFile"/>
        </Root>
    </Loggers>
</Configuration>

Notes:

*

*Put the following content in your configuration file.

*Name the configuration file log4j2.xml

*Put the log4j2.xml in a folder which is in the class-path (i.e. your source folder "src")

*Use Logger logger = LogManager.getLogger(); to initialize your logger

*I did set the immediateFlush="false" since this is better for SSD lifetime. If you need the log right away in your log-file remove the parameter or set it to true

A: Here is my simplistic log4j2.xml that prints to console and writes to a daily rolling file:
// java
private static final Logger LOGGER = LogManager.getLogger(MyClass.class);

// log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="logPath">target/cucumber-logs</Property>
        <Property name="rollingFileName">cucumber</Property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
        </Console>
        <RollingFile name="rollingFile" fileName="${logPath}/${rollingFileName}.log" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
            <Policies>
                <!-- Causes a rollover if the log file is older than the current JVM's start time -->
                <OnStartupTriggeringPolicy />
                <!-- Causes a rollover once the date/time pattern no longer applies to the active file -->
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="DEBUG" additivity="false">
            <AppenderRef ref="console" />
            <AppenderRef ref="rollingFile" />
        </Root>
    </Loggers>
</Configuration>

TimeBasedTriggeringPolicy
interval (integer) - How often a rollover should occur based on the
  most specific time unit in the date pattern. For example, with a date
  pattern with hours as the most specific item and and increment of 4
  rollovers would occur every 4 hours. The default value is 1.
modulate (boolean) - Indicates whether the interval should be adjusted
  to cause the next rollover to occur on the interval boundary. For
  example, if the item is hours, the current hour is 3 am and the
  interval is 4 then the first rollover will occur at 4 am and then next
  ones will occur at 8 am, noon, 4pm, etc.
Source: https://logging.apache.org/log4j/2.x/manual/appenders.html

Output:
[INFO ] 2018-07-21 12:03:47,412 ScenarioHook.beforeScenario() - Browser=CHROME32_NOHEAD
[INFO ] 2018-07-21 12:03:48,623 ScenarioHook.beforeScenario() - Screen Resolution (WxH)=1366x768
[DEBUG] 2018-07-21 12:03:52,125 HomePageNavigationSteps.I_Am_At_The_Home_Page() - Base URL=http://simplydo.com/projector/
[DEBUG] 2018-07-21 12:03:52,700 NetIncomeProjectorSteps.I_Enter_My_Start_Balance() - Start Balance=348000

A new log file will be created daily with previous day automatically renamed to:
cucumber_yyyy-MM-dd.log
In a Maven project, you would put the log4j2.xml in src/main/resources or src/test/resources.

A: log4j2 has a very flexible configuration system (which IMHO is more a distraction than a help), you can even use JSON. See https://logging.apache.org/log4j/2.x/manual/configuration.html for a reference.
Personally, I just recently started using log4j2, but I'm tending toward the "strict XML" configuration (that is, using attributes instead of element names), which can be schema-validated.
Here is my simple example using autoconfiguration and strict mode, using a "Property" for setting the filename:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
    <Properties>
        <Property name="filename">log/CelsiusConverter.log</Property>
    </Properties>
    <Appenders>
        <Appender type="Console" name="Console">
            <Layout type="PatternLayout" pattern="%d %p [%t] %m%n" />
        </Appender>
        <Appender type="Console" name="FLOW">
            <Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n" />
        </Appender>
        <Appender type="File" name="File" fileName="${filename}">
            <Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
        </Appender>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="File" />
            <AppenderRef ref="Console" />
            <!-- Use FLOW to trace down exact method sending the msg -->
            <!-- <AppenderRef ref="FLOW" /> -->
        </Root>
    </Loggers>
</Configuration>


text:
Q: Implement async "yielding" the proper way Async method runs sync on caller context/thread until its execution path runs into an I/O or similar task which has some waiting involved and then, instead of waiting, it returns to original caller, resuming its continuation later. The question is, what is the preferred way of implementing that "wait" method. How do the File/Network/etc async methods do it?
Lets assume I have a method which will have some waiting involved which is not covered by current IOs out of the box. I do not want to block calling thread and I do not want to force my caller to do a Task.Run() to offload me, I want a clean async/await pattern so that my callers can seamlessly integrate my library and I can run on its context until such time I need to yield. Lets for the sake of argument assume that I want to make a new IO lib which is not covered and I need a way to make all the glue that keeps async together.
Do I Task.Yield and continue? Do I have to do my own Task.Run/Task.Wait, etc? Both seem like more of the same abstractions (which brings the question how does Yield yield). I am curious, because there is a lot of talk about how async/await continuation works for the consumer and how all IO libs come already prepped, but there is very little about how the actual "breaking" point works and how process makers should implement it. How does the code at the end of a sync path actually release control and how the method operates at that point and after.

A: If you're the bottom of the async pile, with no inbuilt async downstream calls to defer to, then: it falls to you. The simple way to do this is to allocate a TaskCompletionSource<T> (TCS) for some T, hook up the async work (that isn't Task<T> based) in whatever way you need to, stick the TCS somewhere you can get at it later, and hand back the .Task from the TCS, to the caller. When the async work completes - possibly via some kind of callback, or whatever is suitable for that API; fetch the TCS from where-ever you stuffed it, and signal completion there, via TrySetResult etc.
There are various things to consider, though:

*

*in many cases, you may want to ensure that you pass TaskCreationOptions.RunContinuationsAsynchronously to the TCS constructor, if "thread theft" would be a huge concern (otherwise, the await steals the thread of whatever calls .TrySetResult)

*there are ways of creating and managing Task[<T>] instances without the additional allocation of a TaskCompletionSource<T>, but they're more advanced

*or at the extreme end, if this is high throughput: ValueTask[<T>] has a token-based API (via IValueTaskSource[<T>]) that allows the same object model to be used many times (as different ValueTask[<T>] values), to avoid any additional allocations - again, this is an advanced scenario


text:
Q: Tableview display alert error I am writing a simple tableview app, when tapping the row, a alert shows up.
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *rowValue =self.greekLetters[indexPath.row];
   // NSString *message=[[NSString alloc] initWithFormat:@"You selected%@!",rowValue];

   if (indexPath.row==0) {
        NSString *message=[[NSString alloc] initWithFormat:@"This is course aaaaa",rowValue];
    }

    if (indexPath.row==1) {
        NSString *message=[[NSString alloc] initWithFormat:@"This is course aaaaa"];
    }

    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Course introduction" message:message delegate:nil cancelButtonTitle:@"Return to courses list" otherButtonTitles:nil, nil];

    [alert show];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

However, Xcode doesn't like my if statement here, while the following statement works.
NSString *message=[[NSString alloc] initWithFormat:@"You selected%@!",rowValue];

Could anyone give me an example of how to use the message here please?

A: This is a problem with scope.  You need to declare message before the if statement:
NSString *message;

if (indexPath.row==0) {
    message=[[NSString alloc] initWithFormat:@"This is course aaaaa",rowValue];
}

else if (indexPath.row==1) {
    message=[[NSString alloc] initWithFormat:@"This is course aaaaa"];
}

UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Course introduction" message:message delegate:nil cancelButtonTitle:@"Return to courses list" otherButtonTitles:nil];

[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];

However, if the course number is determined by the row number do:
NSString *rowValue =self.greekLetters[indexPath.row];

NSString *message = [[NSString alloc] initWithFormat:@"This is course %@",rowValue];

UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Course introduction" message:message delegate:nil cancelButtonTitle:@"Return to courses list" otherButtonTitles:nil];

[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];

A: You've forgotten to include %@ in the first if-statement.
NSString *message= [[NSString alloc] initWithFormat:@"This is course aaaaa %@",rowValue];

By the way, there's no need to do [[NSString alloc] init] at all, just use [NSString stringWithFormat:...]


text:
Q: Prevent a Console App (.NET Core) from printing "exited with code 0." in VS2019 and VS2022 When I start a Console App (.NET Core) with Ctrl+F5 (Start Without Debugging) in Visual Studio Community 2019 (Version 16.3.1), the following message is appended in the Console window at the end:

C:\HelloWorld\bin\Debug\netcoreapp3.0\HelloWorld.exe (process 1672) exited with code 0.

using System;

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

Is there any way to prevent Visual Studio 2019 from printing this message? I tried the solution from preventing a similar message from appearing in the Output Window, by changing the option: Tools > Options > Debugging > Output Window > Process Exit Messages = Off, but it has no effect in the Console Window.

Note: this message is not shown in Visual Studio 2017. It is only shown in Visual Studio 2019, and only on .NET Core apps.
Note 2022: the accepted answer is not working on Visual Studio 2022 version 17.4.0 (the latest version).

A: You can disable it by checking the Tools > Options > Debugging > General > Automatically close the console when debugging stops option:

As stated by the console itself (Visual Studio 2019 v16.3.2):

That will make the console just print Press any key to continue... by starting without debugging (CTRL + F5) and not the exit code (still leaves the console open):


text:
Q: Windows Startup folder environment variable I'm developing a setup.exe for my application that copies it to the startup folder with the following path:
cd %PROGRAMDATA%\Microsoft\Windows\Start Menu\Programs\Startup

Now I'm worried if this path could change in different versions of Windows. Does anybody knows if the startup folder path is always the same? There is a better way to configure an application to start every boot?
Any tip will be very helpful,
Thanks

A: The startup priority in Windows is as follows, listed from first to start to last to start:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Runonce
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows\Run
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
SystemDrive\Documents and Settings\All Users\Start Menu\Programs\Startup
SystemDrive\Documents and Settings\username\Start Menu\Programs\Startup

The last two items relate to Windows XP days. Which relate to    %PROGRAMDATA%\Microsoft\Windows\Start Menu\Programs\Startup
And yes, to answer your question, Windows Vista, 7, 8, and 10 use the same startup folder.
So, if you want your program to run first, always use: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Otherwise, the startup folder, will load after everything else is loaded.

A: You want to look up the folders from the shell namespace, e.g. by passing FOLDERID_Startup (or FOLDERID_CommonStartup) to the functions to lookup folder from the shell namespace.
The registry entries (HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run and others) mentioned in another answer are better options. See here
Microsoft also has an article describing the relative order of the different methods.
(The startup folder has the advantage of being easy(ish) for the user to control)


text:
Q: Pick row that has multiple other rows in adjacent table I have a table called conversations. Beside that, I have a table called conversation_participants.
When users create a conversation, they pick which other users they want to make it with. I do, tough, want to check before creating a new conversation, that it doesn't already exists with that batch of participants - if so I just want to reuse the existing one.
So my question is. How do I find a row in conversation that has the exact relations in conversation_participants.
My table looks like this (simplified).
   | conversations       |
   | ------------------- |
   | id      | int (pk)  |
   | created | timestamp |
   | ------------------- |

   | conversation_participants                |
   | ---------------------------------------- |
   | id           | int (pk)                  |
   | created      | timestamp                 |
   | conversation | int (fk to conversations) |
   | user         | int (fk to users)         |
   | read         | timestamp                 |
   | ---------------------------------------- |

Now the question is. How do I find the row in conversation that has the exact set of users in conversation_participants? It must be the exact set – not just a subset.

A: Find all conversations that do not have a conversation_participants that is not in the list:
SELECT c.id
FROM conversations AS c
WHERE NOT EXISTS (SELECT 1 FROM conversation_participants AS cp
                  WHERE cp.conversation = c.id
                    AND cp."user" NOT IN (/* list of users */));

A: You can use aggregation.  If you construct the list of participants in order in a string or array, you can use:
select cp.conversation
from conversation_participants cp
group by cp.conversation
having string_agg(user order by user, ',') = '1,2,3,4';

You can also do this without strings or arrays:
select cp.conversation
from conversation_participants cp
where user in (1, 2, 3, 4)
group by cp.conversation
having count(*) = 4;  -- all four users

If you pass the values in as an array:
select cp.conversation
from conversation_participants cp
where user i= any :ar
group by cp.conversation
having count(*) = cardinality(:ar)  -- all four users


text:
Q: How to approach this question (multivariable calculus/limits)? The thing is I don't want any direct answer I just need a tip of a trick that I can apply to get the magic. I am not really interested in the answer, so please don't write the answer for the question but rather how to approach and think about the question.
I'm given the following
$$\lim_{(x,y)\to (2,-2)}\frac{\ln(x^4-y^4+1)}{x^2-y^2}.  $$
I obviously have tried to approach it from the $x$ axis by setting $y=0$ and so from the $y$ axis by setting $x =0$ but it didn't help out because when you set $x=0$ you end up with an undefined answer in $\mathbb R$. Mathematica tho says that the limit converges to $8$
Thank you in advance!

A: Since you wrote you only want a hint: Try to use that
$\lim\limits_{t\to0} \frac{\ln(1+t)}t=1$ might simplify things a bit.
More details are hidden below:

 Using the above you should get $$\lim_{(x,y)\to (2,-2)}\frac{\ln(x^4-y^4+1)}{x^2-y^2} = \lim_{(x,y)\to (2,-2)} \frac{x^4-y^4}{x^2-y^2} = \lim_{(x,y)\to (2,-2)} (x^2+y^2).$$

BTW you wrote in your post that you get undefined result if you set $x=0$. By undefined answer you mean that you get limit in indeterminate form? WA returns 8 for that limit:http://www.wolframalpha.com/input/?i=lim+y-%3E2+ln%2817-y%5E4%29%2F%284-y%5E2%29 (But I agree that computation of this limit is of similar difficulty as the original limit in your post.)


text:
Q: How do I load a specific page as initial page in Flatlist in react native? Suppose I have more than 100 data. Now when implementing Flatlist the initial page that loads is the first item from the data. Now my question is how do I load a specific data 50th data and still be able to scroll up or down.

A: If you go with the function-based approach, you need to add
const flatListRef = useRef(null);

In useEffect(), focused scroll to specific index with scrollToIndex() function.
setTimeout(() => flatListRef.scrollToIndex({ animated : true, index : DATA[50] }), 500);
//replace DATA and add anything to index you want to focus

And in return(),
<FlatList
    ref={ flatListRef }
    data={DATA}
    ...
/>

Hope this works for you.

A: FlatList has a prop called initialScrollIndex, check it here


text:
Q: Can't upload xlsx library in Amazon Web Service (R) I need to use the xlsx package in AWS but I have not been able to upload it. I have tried, as other posts suggested, installing the package with its dependencies, but didn't work. This is the error message that I get using AWS:

When I try to upload the library in my computer (without using AWS), I can upload the library without problem. Does anybody knows what could be happening? Thanks in advance!


text:
Q: C++: Initialize a member pointer to null? I have a class that looks like:
class Foo
{
public:
    Foo();
    virtual ~Foo();

private:
    Odp* bar;
};

I wish to initialize bar to NULL. Is this the best way to do it?
Foo::Foo() : bar(NULL)
{
}

Also, is it necessary that the destructor is virtual? (If that is true, then must the constructor be virtual as well?)

A: Four distinct ways exist. Which one is the best is up to you
Foo::Foo() : bar() // value initialization
{
}

Foo::Foo() : bar(0) // direct null pointer constant
{
}

Foo::Foo() : bar(NULL) // null pointer constant by macro
{
}

Foo::Foo() : bar(nullptr) // pointer literal of type std::nullptr_t
{
}

A: *

*Yes

*Regarding your second question about destructor being virtual see: http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.7
Short answer, No destructor isn't necessary to be vitual in your case.

*There are no such things as virtual constructors.

A:
I wish to initialize bar to NULL. Is this the best way to do it?

It is the correct way. So, yes.

Also, is it necessary that the destructor is virtual?

No. The destructor only needs to be virtual if you will be inheriting from the Foo class and will be using a Foo pointer to delete those derived classes (although as a general rule of thumb, it should be virtual if there are any other virtual members).

(If that is true, then must the constructor be virtual as well?)

No. Constructors neither need to be virtual, nor can they.

A: Another option you might want to consider is to use a smart pointer class (such as boost::scoped_ptr, boost::shared_ptr or C++0x's unique_ptr) instead of a raw pointer.  The constructor of the smart pointer will make sure it's initialized to something NULL-like if you don't need some other explicit initialization.  The smart pointer will also ensure that the pointed-to object is destroyed.
You just need to decide what kind of smart point policy is appropriate for the item and choose accordingly (even auto_ptr might be better than a raw pointer as long as you're aware of the various pitfalls).

A: 1, yes
2, only if you want somebody to be able to derive from your class and use a pointer to the base class - but make the dtor virtual anyway
3, no you can't have a virtual ctor (or all ctors are virtual I suppose?)

A: *

*Yes, the initializer list is best.

*Maybe. The destructor should be virtual if you intend to have any other virtual functions in the class, or if you intend the class to be inherited from (although usually those things go together).

*No. It's not possible to have a virtual constructor in C++. (what would such a thing even mean?)
The nature of your question suggests to me that you don't really understand what the virtual keyword does, or what is is for, and you are just copying something you saw elsewhere or in a tutorial. It's best to understand the purpose of all of the code you're writing. Here might be a place to start: http://www.parashift.com/c++-faq-lite/virtual-functions.html

A: Virtual functions are to determine which function of class (which is defined in both base and derived class) must be called during run time. But when object is created compiler knows which  constructor is to be called. for eg. when base object is created base constructor is calledand same for the derived class. Hence making constructor to be virtual doesnt makes any sense.But once when the base class object pointer points to the derived class object, and then destructor is called ,compiler gets confused which destructor(either of baseor derived) needs to be called, which is can only resolved using lookup table vtable and hence destructor needs to be virtual.


text:
Q: How to deploy a web application to Azure Web App while signing the binaries? I have a solution with a web application that I want to deploy to Azure App Service. My solution contains assembly attributes to sign the assemblies using an installed key container (using sn -i <infile> <container>). This solution also builds an MSI file for the clients' usage, which is signed using signtool. Now I want to setup an automatic deployment for the web application in this solution to Azure App Service. I prefer to wire it up with GitHub instead of publishing the binaries elsewhere and using them to deploy.
When I connected my GitHub account, the deployment fails because it can't sign these binaries. I know I have to give my certificate for signing somehow, but don't know how. I was hoping I could use Azure Key Vault, but not sure how to wire it up with the build that gets triggered when a checkin in made. What is the best way to achieve automated deployment to Azure App Service.
Thanks for your help.

A: I think you should use Web Roles with Startup task in order to copy your assembly, however, I'll search if there's an option to keep with App Service for that.
Startup tasks with Web Roles:
https://azure.microsoft.com/en-us/documentation/articles/cloud-services-startup-tasks/


text:
Q: Why does "cat {foo}" not output foo, but "cat {foo,bar}" does? I was trying to concatenate text files in sub-folders and tried:
cat ./{mainfolder1,mainfolder2,mainfolder3}/{subfolder1}/book.txt > out$var

However this did not return anything. So, tried adding a non existing 'subfolder2'
cat ./{mainfolder1,mainfolder2,mainfolder3}/{subfolder1,subfolder2}/book.txt > out$var

And this time it did work out, concatenating the files successfully.
Why does this happens?

A: By definition, brace expansion in GNU Bash requires either a sequence expression or a series of comma-separated values:

Patterns to be brace expanded take the form of an optional preamble, followed by either a series of comma-separated strings or a sequence expression between a pair of braces, followed by an optional postscript.

You can read the manual for details.
A few simple samples:
echo {subfolder1}
{subfolder1}

echo {subfolder1,subfolder2}
subfolder1 subfolder2

echo subfolder{1}
subfolder{1}

echo subfolder{1..2}
subfolder1 subfolder2

A: {subfolder1} evaluates to {subfolder1}, since there are no alternatives. Use subfolder1 instead.

A: Braces will only expand if they have coma separated strings, for e.g. {abc,def} or range, for e.g. {a..e} specified between them.
In your case you can just write subfolder1 without enclosing it in braces as there is no need for that
cat ./{mainfolder1,mainfolder2,mainfolder3}/subfolder1/book.txt > out$var


text:
Q: Lost messages with aSmack i'm using aSmack in my Android app to receive messages from my Desktop-Jabber-client. This works fine and even if my android phone is offline (after the connection was closed properly) it will receive the offline messages after the next login.
But when i enter the airplane-mode on the phone or shutdown the phone so that the connection is abruptly closed (without calling disconnect() on the Connection-object) the phone stays "online" in the contact-list of my Desktop-Jabber-client for a while and i can send messages to it. However these messages never arrive. Even though the phone logs in to the server again. These messages are lost.
Does anyone know how to fix this issue? Losing messages in a chat is not an option. :)
EDIT: Added Test-Code
BroadcastReceiver: http://pastebin.com/cFLzGXgy
Service: http://pastebin.com/wLpQCQfT
The first one is a BroadcastReceiver starting the service (second URL) each time the phone is connected to a network.
PS: This is only a test-code! You must change the server/username/password if you want to use/test it.

A: You can try to send delivered message from client b to client A when the message arrival. The problem is if the client A is offline (no connection break) the delivered confirm don't send until the user receives the message and the client B can't re-send the message.

A: you can try to send acknowledgement of receiving the message using Smackx Message Events
this will assure the message is delivered else you take corrective action.

A: this problem occurs when your connection broke.
You need "Stream Management" XEP-198 enabled connections to achieve this messages. refer to this blog : http://op-co.de/blog/posts/XEP-0198/ Basically it allows for stanza acknowledgement and stream resumption, which is exactly what you want to do in case.so you should wait till smack will 4.1 release.


text: Q: dummies package in R After creating dummy variables for all the categorical variables in the dataset, I'm able to view only the dummy variables and not the original factor varaibles in the new dataset .How do i get to view the original factor and dummy variables created in the same dataset ?


text:
Q: JavaScript Child Theme / Parent Theme Link I'm working on building this site and have an issue with the nav/floating nav section which I can fix within the parent theme. However, I'm struggling to get it all linked up in the child theme.
The JS itself is located in /javascript/gdlr-script.js with it being hooked in via /include/gdlr-include-script.php - so naturally, I've made a carbon copy of the structure in my child theme and changed the include file to;
// include theme script / style
$array['script']['gdlr-script'] = GDLR_PATH . '/flawless-v1-15-child/javascript/gdlr-script.js';

Enqueue:
// register the necessary script depends on the condition of that page
if( !is_admin() ){
    add_filter('gdlr_enqueue_scripts', 'gdlr_regiser_use_script');
}

if( !function_exists('gdlr_regiser_use_script') ){
    function gdlr_regiser_use_script($array){
        global $theme_option, $gdlr_post_option;

Naturally, that points to the JS file I want it to use, but it doesn't seem to work. Am I missing something here?
I can fix it within the parent theme, so I know my code is right pertaining to the JS, as I've had it working. Something just doesn't add up. Is there a reason that this wouldn't overwrite the parent folders?


text:
Q: Alert dialog reloads every time the textfield is clicked I am including an AlertDialog when the app user is not registered in Cloud Firestore:
class MuroScreen extends StatefulWidget {
  const MuroScreen({Key? key}) : super(key: key);

  @override
  _MuroScreenState createState() => _MuroScreenState();
}

class _MuroScreenState extends State<MuroScreen> {

  CollectionReference userRef = FirebaseFirestore.instance.collection('clientes');

  Future<void> salir() async {
    await FirebaseAuth.instance.signOut().catchError((error){
      print(error.toString());
    });
    Navigator.of(context).push(MaterialPageRoute(builder: (c)=>MyHomePage001()),);
  }

  Future<void> verificarUsuario() async{
    DocumentSnapshot snapshotUser = await userRef
        .doc(FirebaseAuth.instance.currentUser!.phoneNumber)
        .get();

    print("existe?"+snapshotUser.exists.toString());
    if(snapshotUser.exists){
      //ya existe
      print("si  EXISTE");
    }
    else {
      //no existe
      print("no  EXISTE");
      var nameController = TextEditingController();
      Alert(
          context: context,
          title: "LOGIN",
          content: Column(
            children: <Widget>[
              TextField(
                decoration: InputDecoration(
                  icon: Icon(Icons.account_circle),
                  labelText: 'Username',
                ),
              ),
              TextField(
                obscureText: true,
                decoration: InputDecoration(
                  icon: Icon(Icons.lock),
                  labelText: 'Password',
                ),
              ),
            ],
          ),
          buttons: [
            DialogButton(
              onPressed: () => Navigator.pop(context),
              child: Text(
                "LOGIN",
                style: TextStyle(color: Colors.white, fontSize: 20),
              ),
            )
          ]).show();

    }

  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    verificarUsuario();

  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text("Home"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            margin: EdgeInsets.all(65),
            width: double.infinity,
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                primary: Colors.red,
              ),
              onPressed: ()  {
                salir();

              },
              child: Text("Logout",style: TextStyle(color:Colors.white,fontSize: 16, fontWeight: FontWeight.bold),),
            ),
          )

        ],

      ),
    );
  }
}

Alert is a rflutter_alert widget.
The issue is that every time I click on a textfield inside the alert widget, the screen reloads and shows the alert again without showing the keyboard, it reloads again.

A: You are calling the verificarUsuario(); in init() which doesn't have a context. The alert needs a context from build method to show. Please add a button inside the scaffold and open this alert after passing the the context as an argument. It should work.