text:
Q: Syncing data between services using Kafka JDBC Connector I have a system with a microservice architecture. It has two services: Service A and Service B each with it's own database like in the following diagram.

As far as I understand having a separate database for each service is a better approach. In this design each service is the owner of its data, it's responsible for creating, updating, deleting and enforcing constraints.
In order to have Service A data in Database B I was thinking of using JDBC Kafka Connector, but I am not sure if Table1 and Table2  in Database B should enforce constraints from Database A.
If the constraint, like the foreign key from Table2 to Table1 should exist in Database B then, is there a way to have the connector know about this?
What are other common or better ways to sync data or solve this problem?
The easiest solution seems to sync per table without any constraints in Database B. That would make things easier but it could also lead to a situation where Service's A data in Service B is inconsistent. For example having entries in Table2 that point to a non-existing entry in Table1

A:
If the constraint, like the foreign key from Table2 to Table1 should
exist in Database B then, is there a way to have the connector know
about this?

No unfortunately the "Kafka JDBC Connector" does not know about constraints.
Based on your question I assume that Table1 and Table2 are duplicated tables in Database B which exist in Database A. In Database A you have constraints which you are not sure you should add in Database B?
If that is the case then I am not sure if using "Kafka JDBC Connector" to sync data is the best choice.
You have a couple options:

*

*Enforce the usage of Constraints like Foreign Keys in Database B but you would need to update it from your application level and not through "Kafka JDBC Connector". So for this option you can not use "Kafka JDBC Connector". You would need to write some small service/worker to read the data from that Kafka topic and populate your database tables. This way you control what is saved to the db and you can validate the constraints even before trying to save to your database. But the question here is do you really need to have the Constraints? They are important in micro-service-A but do you really need them in micro-service-B as it is just a copy of the data?

*Not use constraints and allow temporary inconsistency. This is common in micro-services world. When working with Distributed systems you always have to think about the CAP Theorem. So you take into account that some data might at some point be inconsistent but you have to make sure that you will eventually bring it back to consistent state. This means you would need to develop on your application level some cleanup/healing mechanism which will recognize this data and correct it. So Db constraints do not necessary have to be enforced on data which the micro-service does not own and is considered as External data to that micro-service Domain.

*Rethink your design. Usually we duplicate data in micro-service-B from micro-service-A in order to avoid coupling between the services so that the service micro-service-B can live and operate even when the micro-service-A is down or not running for some reason. We also do it to reduce load from micro-service-B to micro-service-A for every operation which needs data from Table1 and Table2. Table1 and Table2 are owned by micro-service-A and micro-service-A is the only source of truth for this data. Micro-service-B is using a duplicate of that data for its operations.
Looking at your databases design following questions might help you figuring out what would be the best option for you system:
Is it necessary to duplicate the data in micro-service-B?
If I duplicate the data do I need both tables and do I need all their columns/data in micro-service-B? Usually you just store/duplicate only a subset of the Entity/Table that you need.
Do I need the same table structure in micro-service-A as in micro-service-A? You have to decide this based on your Domain but very often you Denormalize your tables and change them in order to fit the needs of micro-service-B operations. As usually all these design decisions depend on your application Domain and use case.


text:
Q: InputAccessoryView with UITextView on iPad I am using a UIView combined out of several views that one of them is UITextView.
When UITextView becomes first responder I set the UIView to be its InputAccessoryView.
The keyboard goes up fine with its accessory view.
The problem is that it look like the UITextView is the first responder because text can be typed  inside immediately (without clicking the cursor in) but when trying to dismiss the keyboard it won't go down and even if navigating back the keyboard will remain up.
Only when I click again on the UITextView, I can dismiss the keyboard and when I navigate back the keyboard goes down.
Does anyone has any idea , what is going on?
I think there might be some recursion with the UIResponder, since the UITextView is inside its own inputAccessoryView, any ideas how can I solve this?

A: I also had this problem.  Solved it with:
[self.view endEditing:YES];

A: I find the cause is that when being set as inputAccessoryView, the UITextView is not the FirstResponder now. Anyway if you touch the UITextView again, it becomes the first responder, and then everything goes OK.
So my (ugly) solution on iphone is:

*

*Observe UIKeyboardDidShowNotification:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];

*After receiving UIKeyboardDidShowNotification, send becomeFirstResponder to the UITextView again(in keyboardDidShow:).
I have tested putting the code into textViewShouldBeginEditing: but at that time, the inputAccessoryView is not shown on screen, so it still can not become the first responder?
@takeshi-kaga I have tried your way, but it does not work.Could you share up more details?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to assign speed parameter to callback functions I've been trying to figure out how to assign speed to a callback function, but couldn't.
In this program.
HTML:
<button type="button" id="trigger">Try</button>

CSS:
body
{
position: absolute;
background-color: white;
height: 1000%;
}
#box
{
position: absolute;
height: 300px;
width: 400px;
top: 100px;
left: 0px;
margin: 0px;
padding: 0px;
border-color: black;
background-color: black;
opacity: 0;
}
#bottom
{
position: absolute;
bottom: 0px;
height: 100px;
width: 100%;
background-color: black;
}

JS:
$(document).ready(function () {
    $("#trigger").click(function () {
        var ele = document.getElementById('bottom');
        var pos = ele.getBoundingClientRect();
        var x = pos.left;
        var y = pos.top;
        $("#box").animate({
            left: "100px",
            opacity: "1"
        }, "slow", function () {
            window.scrollTo(x, y);
        }, "slow");
    });
});

On removing the speed from callback, it works but with it no success.
How to assign speed to it, thanks in advance.
Fiddle: http://jsfiddle.net/9C8kr/

A: You've added the speed two times, the last one is not valid.
If you want to animate the scrolling, then do so
$(document).ready(function () {
    $("#trigger").click(function () {
        var ele = document.getElementById('bottom');
        var pos = ele.getBoundingClientRect();
        var x   = pos.left;
        var y   = pos.top;
        $("#box").animate({
            left: "100px",
            opacity: "1"
        }, "slow", function () {
            $('html, body').animate({
                scrollLeft : x,
                scrollTop  : y
            }, 'slow');
        });
    });
});

FIDDLE


text:
Q: Style of application changed after upgrading to supportlib:v7 After i upgraded support library from v4 to v7 the syle of Buttons changed.
Even when use an ImageButton and set View.setVisibility(View.Gone) it stills shows the location of it by highlighting like picture below.

   <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="2"
            android:background="#F44336" >

            <TextView
                android:id="@+id/txtTitle"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:layout_weight="2"
                android:background="#E53935"
                android:gravity="center"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#ffffff" />

            <ImageButton
                android:id="@+id/btnSearch"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:src="@drawable/find" />

        </LinearLayout>

A: You are seeing "location highlight" because colors of background and textview are different. Background is in this color:
android:background="#F44336"

and linear layout is:
android:background="#E53935"

Those colors are both red and very similar but yet different. Remove background from TextView and "location highlight" will be removed because only layout background color will stay.


text:
Q: Making a program to display 15 random, simple addition and subtraction problems in java I am working on a project where the desired output is:
Question 1: 12 + 0 = 12
Question 2: 6 + 12 = 18
Question 3: 3 + 8 = 11
Question 4: 11 - 0 = 11
Question 5: 8 + 7 = 15
Question 6: 8 - 3 = 5
Question 7: 8 - 2 = 6
Question 8: 12 - 9 = 3
Question 9: 0 + 10 = 10
Question 10: 4 + 5 = 9
Question 11: 2 + 1 = 3
Question 12: 1 + 12 = 13
Question 13: 12 + 0 = 12
Question 14: 10 - 1 = 9
Question 15: 11 - 8 = 3

Where the operands and operators are randomized. I need to use two different classes in this project and i am having the most difficulty with the programmer defined class called Questions, containing the accessor methods and instance variables.
Addition - two operands, both in the range 0-12
Subtraction - two operands, the first in the range 6-12, and the second, less than or equal to the first operand. (This is to avoid negative numbers)
Generate a class that randomly generates addition or subtraction problems
SPECS:
3 instance variables: int operand1, int operand2, char operator
3 accessor methods: getOperand1, getOperand2, getOperator**
Also a toString method that returns a string containing the question(but not the answer) The format should be operand1, a space, operator, a space, operand2, a space and an equal sign.
So far i have this:
package proj3;

public class Question {

private int operand1;
private int operand2;
private char operator;

public static int operand1(){
    int num;
    num = (int)(Math.random() * 13);
    return num;
}
public static int operand2(){
    int num;
    num = (int)(Math.random() * 13);
    return num;

}
public String toString(){
    System.out.println(operand1 + operator + operand2 + "=");
    return null;
    }

}
I am not sure if i did the operand1 method correctly or not, also i am not sure how to go about creating the rest of the methods in this class. Any help is appreciated. Thank you.

A: Each Question instance will represent one question. Therefore you should generate the random values in the constructor, when the instance is created:
public Question() {
    // generate the random values and store them in instance variables
}

*

*first generate the operator

*based on the operator, you can generate the operands

*assign the generated values into the instance variables

The accessor methods should be instance methods, not static, and they should just return the corresponding instance variables.
toString() shouldn't print anything - it should just return the String, instead of null as you currently have. Also you should add some spaces to the string, so that it has the desired format.
So your class will look like this:
public class Question {
    private int operand1;
    private int operand2;
    private char operator;

    public Question() {
        // generate the random values and store them in instance variables
    }

    public int getOperand1() {
        return operand1;
    }
    public int getOperand2() {
        return operand2;
    }
    public char getOperator() {
        return operator;
    }

    public String toString() {
        return operand1 + " " + operator + " " + operand2 + " =";
    }
}

If you create an instance of Random, you can use more convenient methods to obtain random values:
Random r = new Random();
boolean randomBoolean = r.nextBoolean();
int randomInt = r.nextInt(13);

UPDATE:
In your attempt you did
int num;
num = (int) (Math.random() * 2);

That creates a local variable num and assigns a random number in the range 0..1. This variable is local to the constructor, it isn't stored anywhere else. What you need to do is assign values to the instance variables operand1, operand2 and operator.
First you decide the operator by getting a random boolean:
Random r = new Random();
if (r.nextBoolean()) {
    // addition
} else {
    // subtraction
}

Then in each branch of the if you generate the appropriate random values and store them to the instance variables. Also store the operator.
As an example:
To generate a number 0..99, you would use r.nextInt(100).
To generate a number 80..99, you would use r.nextInt(20) + 80.
I will leave the last details to you:
public Question() {

    Random r = new Random();

    if (r.nextBoolean()) {
        operator = '+';
        operand1 = r.nextInt(13);
        operand2 = // your code
    } else {
        operator = '-';
        operand1 = // your code
        operand2 = // your code
    }
}

You can test the output like this:
Question q = new Question();
System.out.println("first operand: " + q.getOperand1());
System.out.println("full question: " + q); // toString() will be automatically used here

A: You'd probably want 2 methods for each operand, a getter method - getOperand1() and a generateOperand1() (which is what you're calling operand1() above)
For random generation, you could take an Enum argument typeOfOperation, and then using a switch statement you could generate the operands accordingly.
E.g.
void generateOperand1(OperationEnum typeOfOperation) {

  switch (typeOfOperation) {

    case OperationEnum.ADDITION
        operand1 = // logic to generate random number
        break;
    case OperationEnum.SUBTRACTION
        operand1 = // logic to generate random number
  }
}

Similarly, you can create a generateOperator depending on the type of operation.


text:
Q: Why one method of reading string in C using char* pointer works while other doesn't? I am reading a string in C using the pointers, through the following two methods, both are exactly same(at least they appear to me). The only difference is in one method I have made a dedicated function to do the job.
Method 1: // Works as expected
#include <stdio.h>

int main()
{
    char *str;
    char delimiter='.';
    int len=0;

    scanf("%c",(str+len));
    while(*(str+len)!=delimiter)
    {
        ++len;
        scanf("%c",(str+len));
    }
    ++len;
    *(str+len)='\0';

    printf("%s",str);

    return 0;
}

Method 2: // Doesn't work, nothing gets printed on the screen
#include <stdio.h>

int readString(char *str,char delimiter)
{
    int len=0;

    scanf("%c",(str+len));
    while(*(str+len)!=delimiter)
    {
        ++len;
        scanf("%c",(str+len));
    }
    ++len;
    *(str+len)='\0';

    return len;
}

int main()
{
    char *str;

    int len=readString(str,'.');

    printf("%s",str);

    return 0;
}

I am completely clueless about what I am doing wrong.
While further playing with the code in Method 2, I observed if I just declare a variable(even useless) with initialisation(like int useless=-1;) between lines char *str; and int len=readString(str,'.'); the code works fine.
This added further to my headache.
Can someone explain what is really going on?
My guess is it has to do something with dangling pointers, but then if that was the case Method 1 should have also failed.

A: In the first code
 scanf("%c",(str+len));

you're trying to write into (access) a memory location which is invalid. Notice that str actually is uninitialized, i.e., it does not point to any valid memory location. So, the program invokes undefined behaviour and the outcome cannot be justified in any way.
In the second code, the same problem is present, so the behaviour is undefined again.


text:
Q: Stack overflow error / unending recursion I am coding a Huffman encoding tree and I am getting this error.
5:1
5:4
5:2
5:1
5:4
5:2
5:1
5:4
5:2
5:1
Exception in thread "main" java.lang.StackOverflowError
at sun.nio.cs.SingleByteEncoder.encodeLoop(SingleByteEncoder.java:130)
at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:544)
at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:252)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:106)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:190)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:111)
at java.io.PrintStream.write(PrintStream.java:476)
at java.io.PrintStream.print(PrintStream.java:619)
at java.io.PrintStream.println(PrintStream.java:756)
at HuffmanNode.buildTree(hw4.java:65)
at HuffmanNode.buildTree(hw4.java:66)
at HuffmanNode.buildTree(hw4.java:66)
at HuffmanNode.buildTree(hw4.java:66)
at HuffmanNode.buildTree(hw4.java:66)

Obviously I have an infinite recursive method at buildTree(), however I don't understand what it is doing.
public void buildTree(HuffmanNode node) {
    if (node.compareTo(this) <= 0 && left != null) {
        System.out.println(node.getCount() + ":" + this.count);
        left.buildTree(node);
    }
    else if (node.compareTo(this) <= 0 && left == null) {
        this.left = node;
        node.parent = this;
    }
    else if (node.compareTo(this) > 0 && right != null) {
        System.out.println(node.getCount() + ":" + this.count);
        right.buildTree(node);
    }
    else if (node.compareTo(this) > 0 && right == null) {
        this.right = node;
        node.parent = this;
    }
}

My full code and input file can be seen here.

A: After first step, your tree looks like this:
root
/  \
    -
   / \
  M   Z

When you do second step you attach new result node to Z, which is wrong. After second step your tree is broken and third step goes to infinite recursion.
EDIT: ok, i just read the algorithm once again and I think all you need to do is to create result node. Just remove these lines:
        if (root == null) {
            root = result;
        } else {
            root.buildTree(result);
        }

Then when your loop finishes you will have only one node in huffmanList, which is the root:
    while (huffmanList.size() > 1) {
        HuffmanNode x = huffmanList.poll();
        HuffmanNode y = huffmanList.poll();
        HuffmanNode result = new HuffmanNode("-", x.getCount() + y.getCount(), null, x, y);
        huffmanList.add(result);
    }
    huffmanList.poll().genCode(" ");

A: In the setParent(HuffmanNode right) you do this.left=left which does absolutely nothing. This must be your error


text:
Q: How can I add variable names to the end of a file? I have created a form that submits the data to a filename on the server.  The form submit is working fine, it generates the requested file called "we_input_.sts".
I am trying to use the following code to grab two variables from the form "bfstnme" and "gfstnme"and attach them to the filename eg "wed_import-Jane_Bill.sts
This is the amended code: However I am still unable to get it to work.
I am trying different ideas to get this to work correctly.   I have tried moving the code around but I'm still obviously missing something.  The last line before the $savestring== is "$fp=fopen("wed-import-.sts", "a+");
The last lines after the $savestring are : fwrite($fp,$savestring); fclose($fp);
<?php
$bfirstname = $_POST['bfstnme'];
$gfirstname = $_POST['gfstnme'];
$file = 'wed_import_.sts';
$current = file_get_contents($file);
$new_file = 'wed_input_'.$bfirstname.'&'.$gfirstname.'.sts';
file_put_contents($new_file, $current);
?>

A: Here is the way I have solved it using the valuable assistance of all concerned.
$names .= ("$bfstnme" . "$gfstnme");
$fp = fopen("wed_import_($names).sts", "a+");

The results of the above give me a filename called:
"wed_Import_[JaneBill].sts.  I only need to work out how to put an amperstand (&) betwen the names.
Thank you to all.

A: Why you don't name the file before writing to it?
<?php
   $gfirstname = $_POST['gname'];
   $bfirstname = $_POST['bname'];
   $file = 'wed_input_Bride_Groom.sts';
   // Opens the file to get existing content hopefully
   $current = file_get_contents($file);
   // Appends bride and groom first names to the file hopefully
  $current .= ("gfirstname" . "bfirstname");
  $new_file = 'wed_input_'.$gfirstname.'_'.$bfirstname.'.sts';
  // Write the contents back to the file
 file_put_contents($new_file, $current);
 ?>

A: If you want put the info inside the file you must change the + by a . like this:
$current .= ("gfirstname" . "bfirstname");
If you want change the name, you must do something like @Jay_P says

A: Let's assume you have the names in a variable called $names.  You can easily append the text with the FILE_APPEND flag like this:
file_put_contents('wed_input_Bride_Groom.sts', $names, FILE_APPEND);


text:
Q: How to improve my jquery checkbox script I have made a function that if i check a checkbox an text will be added to an textarea.
I have several checkboxes, so i dont want the textarea to get empty when i uncheck any of the checkboxes. my code works, but the problem is the code is really awfully coded and makes loading time too long since this is for a mobile site i need to shorten it, any help is appreciated.
$(document).ready(function () {
    $('#checkbox-6').change(function () {
        if ($(this).is(':checked')) {
            $('#append').append(' Till - Hiss finnes ')
        } else {
            var thiss = $('#append');
            thiss.html(thiss.html().replace(/ Till - Hiss finnes /ig, ""));
        }
    });
    $('#checkbox-7').change(function () {
        if ($(this).is(':checked')) {
            $('#append').append(' Behöver hjälp med uppackning ')
        } else {
            var upack = $('#append');
            upack.html(upack.html().replace(/ Behöver hjälp med uppackning /ig, ""));
        }
    });
    $('#ch1').change(function () {
        if ($(this).is(':checked')) {
            $('#append').append(' Från - Hiss finnes ')
        } else {
            var fhiss = $('#append');
            fhiss.html(fhiss.html().replace(/ Från - Hiss finnes /ig, ""));
        }
    });
    $('#ch2').change(function () {
        if ($(this).is(':checked')) {
            $('#append').append(' Packning ')
        } else {
            var pack = $('#append');
            pack.html(pack.html().replace(/ Packning /ig, ""));
        }
    });
    $('#ch3').change(function () {
        if ($(this).is(':checked')) {
            $('#append').append(' Vind Källare Förråd ')
        } else {
            var attic = $('#append');
            attic.html(attic.html().replace(/ Vind Källare Förråd /ig, ""));
        }
    });
    $('#ch4').change(function () {
        if ($(this).is(':checked')) {
            $('#append').append(' Flyttstädning ')
        } else {
            cleaning = $('#append');
            cleaning.html(cleaning.html().replace(/ Flyttstädning /ig, ""));
        }
    });
    $('#ch5').change(function () {
        if ($(this).is(':checked')) {
            $('#append').append(' Behöver flyttkartonger ')
        } else {
            var boxes = $('#append');
            boxes.html(boxes.html().replace(/ Behöver flyttkartonger /ig, ""));
        }
    });
});

Thanks!

A: function min(id, append, unpack)
{
    $(id).change(function() {
        if ($(this).is(':checked')) {
            $('#append').append(append)
        } else {
            var thiss = $('#append');
            thiss.html(thiss.html().replace(unpack, ""));
        }
    });
}

$(document).ready(function() {
    min('#checkbox-6', ' Till - Hiss finnes ', / Till - Hiss finnes /ig);
    min('#checkbox-7', ' Behöver hjälp med uppackning ', / Behöver hjälp med uppackning /ig);
    // ETC
});

You just need to think like a programmer and see what everything has in common.

A: You can try this.
var texts = {
   "ch1": " Från - Hiss finnes ",
   "ch2": " Packning ",
   "ch3": " Vind Källare Förråd ",
   "ch4": " Flyttstädning ",
   "ch5": " Behöver flyttkartonger ",
   "checkbox-6": " Till - Hiss finnes ",
   "checkbox-7": " Behöver hjälp med uppackning ",
}

$(document).ready(function(){
   $(':checkbox').change(function(){
      var $textArea = $('#append');
      if(this.checked){
          $textArea.append(texts[this.id])
      }else{
           $textArea.html($textArea.html().replace(texts[this.id], ""));
      }
    });
});

A: There are many minification tools available, I tend to use Google's Closure Compiler. Here's a link to an online version which you can play around with.


text:
Q: How to extract commit file from commit id in git? I want to extract the commit file before the commit and the after the commit only using one commit id. Is there any way to extract this?
commit 471d4d60dc21fbccb8c6b4616a00238c245f78f6
Author: Gilles Sadowski <gilles@harfang.homelinux.org>
Date:   Mon Oct 28 01:51:42 2019 +0100

MATH-1500 (unit tests).
src/test/ ... linalg/FieldLUDecompositionTest.java

commit 9988a5b3c4779eadfad9ea0c4925f5b327317814
Author: Gilles Sadowski <gilles@harfang.homelinux.org>
Date:   Sun Oct 27 15:11:56 2019 +0100

Code upgraded following MATH-1500.
src/main/... nonstiff/AdamsNordsieckTransformer.java

In this case i want to extract file name "FieldLUDecompositionTest" before the commit and after the commit only using one commit id which is "471d4d60dc21fbccb8c6b4616a00238c245f78f6"

A: The proper way to extract/restore a file from a commit is, with Git 2.23+ (August 2019) to use git restore (less confusing than git checkout)
git restore <SHA1>

To restore only one specific file from that old commit:
git restore <SHA1> -- path/to/file

That would update only your working tree by default.

Getting the previous SHA1 is easy:
471d4d60dc21fbccb8c6b4616a00238c245f78f6~

Git the next SHA1 is more complex: see "How do I find the next commit in git? (child/children of ref)":
git log --format=%H --reverse --ancestry-path ${1:-HEAD}..${2:\"$(git rev-parse --abbrev-ref HEAD)\"} | head -1

More in torek's answer)
git rev-list --topo-order --ancestry-path --reverse <id1>...<id2> | head -1

So you can make a script which will get the parent and child of a given commit, and use git restore to get/see the files of those commits.

A: You just move your head to the desired commit and copy the file to another location.
The procedure would be the following:

*

*git checkout 471d4d60dc21fbccb8c6b4616a00238c245f78f6 - you are now at the point where the file was not modified

*Copy the file to another location.

*git checkout 9988a5b3c4779eadfad9ea0c4925f5b327317814 - this is the latest commit from your history

*Copy the modified file to new location.

If you want more information about moving the head on a branch, you can read here.


text:
Q: openpyxl Warning (from warnings module) python Actualmente tengo un archivo de excel con dos hojas, en la primera (TD) tengo varias formulas que se encargan de hacer algunos cálculos con los datos de la hoja 2(Base GRAL), la segunda hoja la alimento con  el resultado de una consulta SQL, para esto estoy usando openpyxl, el cual hace el ejercicio de poblar la hoja 2(Base GRAL), pero al terminar me esta ocacionando dos situaciones, la primera me daña todas las formulas de la primer hoja, por ejemplo tengo esta formula
=CONTAR.SI.CONJUNTO('Base GRAL'!$F:$F;"VENDIDA";'Base GRAL'!$I:$I;TD!$B5)
,que despúes de ejecutarse me daña la referencia quedando de este modo:
=CONTAR.SI.CONJUNTO('Base GRAL'!#¡REF!;"VENDIDA";'Base GRAL'!#¡REF!;TD!$B5).
y lo segundo me arroja este error:
Warning (from warnings module):
  File "C:\Program Files (x86)\Python310-32\lib\site-packages\openpyxl-3.0.10-py3.10.egg\openpyxl\comments\shape_writer.py", line 74
FutureWarning: The behavior of this method will change in future versions. Use specific 'len(elem)' or 'elem is not None' test instead.

Este es mi código:
def export():
    dataExport = []
    base = Base_excel(dataExport)

    EjecutarMacro(ruta = "/Estructura_Inf.xlsm",archivo = "Estructura_Inf",modulo = "Módulo1",macro = "Limpiar",seg = 10)

    l_Estructura = openpyxl.load_workbook("/Estructura_Inf.xlsm",read_only = False, keep_vba = True)
    h_Estructura = l_Estructura.worksheets[1]

    print(h_Estructura)

x = 0
for row in base:
    if x >0:
        h_Estructura.append(row)
    x = x + 1

l_Estructura.save("/Estructura_Inf.xlsm")
l_Estructura.close()


text:
Q: How do you generate a histogram in NetLogo? I have a breed called players. Each player-owns a player-strategy. There are 6 possible player-strategies. When I write
histogram [player-strategy] of players
nothing appears on my plot.
I have one plot with one pen -- and don't set either the plot or penname. plot-name returns the plot. pen-mode is bar. interval is 1.0
I don't know how to ask for the current penname. But since the plot has only one pen it shouldn't matter.
The histogram command is in both plot-update and pen-update. I've tried it in both together or one at a time. I also tried in code. Makes no difference.
What do I have to do to get a histogram to appear?

A: OK, here is what I think you are after.
If you create the following plot:

And write the following code:
extensions [table]
breed [players player]
players-own [player-strategy]

to setup
  clear-all
  create-players 100 [ set player-strategy one-of ["a" "b" "c" "d" "e"] ]
  reset-ticks
end

to update-strategy-plot
  set-current-plot "Player strategies"
  clear-plot
  let counts table:counts [ player-strategy ] of players
  let strategies sort table:keys counts
  let n length strategies
  set-plot-x-range 0 n
  let step 0.05 ; tweak this to leave no gaps
  (foreach strategies range n [ [s i] ->
    let y table:get counts s
    let c hsb (i * 360 / n) 50 75
    create-temporary-plot-pen s
    set-plot-pen-mode 1 ; bar mode
    set-plot-pen-color c
    foreach (range 0 y step) [ _y -> plotxy i _y ]
    set-plot-pen-color black
    plotxy i y
    set-plot-pen-color c ; to get the right color in the legend
  ])
end

You should get the following plot:

I believe this should answer your previous question as well.
(Note that I've put the plotting code in a code tab procedure, but you could just as well stick it in the "Plot update commands" field.)

A: I know it is a very old question, but in case anyone lands here on a search. The current version of NetLogo comes with example code for histogram usage: look in the file menu under 'Models Library'; see 'Code Examples'/'Histogram Example'.


text:
Q: Getting MessagingException in Mulesoft I am getting this weird exception while debugging the mule code in Anypoint studio. Error occurs when 'Transform Message' message processor is getting executed.
org.mule.api.MessagingException: com/mulesoft/flatfile/schema/FlatFileParserBase (java.lang.NoClassDefFoundError).
Any idea why this is happening?

A: It looks like there was problem with Schema or any FFD you are using.or You are not locating correct ffd for this.
Can you please attached Dwl code.
Thanks,
Manish Yadav


text:
Q: javascript not working if input type is not present I have a table which contain input types such as checkbox, text as below
var inputBoxes = table_check.getElementsByTagName('input'); //modified to get only input tags present within the table

 for(var i=0; i<5; i++) {
Nos1=parseInt(inputBoxes[i+1].value);item_row_no=1;
if(inputBoxes[i].value){alert('No Input Box');} //fails at this if clause
else{Nos2=0;}

If there is less than 5 Input Types present inside the table it should throw alert.
Excepted result : No Input Box from alert
Actual result : <nothing thrown> if input type is less than 5;
The above script is working fine if there is exactly 5 input types inside the table.

A: Your question is not clear. If you just want to add a condition based on the number of input types, you can just use like given below.
var inputBoxes = table_check.getElementsByTagName('input'); //modified to get only input tags present within the table
if(inputBoxes.length<5){
  alert('No Input Box');
}

A: You should be using i<inputBoxes.length as your for condition.
for(var i=0; i<inputBoxes.length; i++) {
   Nos1=parseInt(inputBoxes[i+1].value);
   item_row_no=1;
   if(inputBoxes[i].value){
      alert('No Input Box');
   } else {
      Nos2=0;
   }
}

If for whatever reason you want to keep the i<5 condition you would need to check the existence of the array element and not the .value, you should have been getting errors on the console because of the way your if was setup. Use the below:
if(!inputBoxes[i]){
   console.log("Input Box "+ i +" Does Not Exist");
} else {
   Nos2=0;
}

A: inputBoxes is an HTMLCollection.
Turn it into an array like so:
var inputBoxes = document.getElementsByTagName('input');
inputBoxes = Array.prototype.slice.call(inputBoxes);

Then you can check if the inputBox is defined like so
if(inputBoxes[i] == undefined){
  alert('No Input Box');
}


text:
Q: How to develop Windows 8 metro-style JS apps outside Visual Studio? I run Windows 8 on a VM.
In fact I would like to develop locally (not on a VM).
Is there a way to run JS app in a browser rather than via Visual Studio?
Here is the what happens if I run default.htm in a browser:

Note the filenames starting with // and /. Removed "/" and I have copied SDK so all the files are available locally:
c:\Program Files (x86)\Microsoft SDKs\Windows\v8.0\ExtensionSDKs\Microsoft.WinJS.1.0\1.0\DesignTime\CommonConfiguration\neutral\Microsoft.WinJS.1.0\

On this occasion I get following set of errors:

I suspect some other files are missing, see solution explorer for the sample project:

I'm getting more and more confused with TWO base.js files. All I want to do is to develop Windows 8 JS app just as regular web-app in a browser. This will probably save me and many other developers a lot of time not have to run via Visual Studio.
Here is the article - http://msdn.microsoft.com/en-us/library/windows/apps/Hh781229(v=win.10).aspx - How to load file resources (Windows Store apps using JavaScript and HTML) - however this isn't much help to me. Any suggestions appreciated :)
Just to clarify: I would like to publish to Windows 8 store. Only for development I would like to use browser.

A: It will not be possible to run windows 8 apps in a browser.  They depend on a lot of stuff which is only provided by WinRT.  The WinRT framework is only available to apps running either in the simulator or when as app is run on the Windows App side of Windows.

A: http://dougseven.com/2011/10/24/language-choice-in-windows-8-is-not-about-portability/

Some of the JavaScript is likely reusable, if it isn't tightly coupled
  to WinJS or WinRT. But that's it. Most of what makes the app work is
  dependent on WinRT, so its not portable – WinRT only runs on Windows 8.

So difficult to accept that I cannot run Win8 JS app directly in a browser :(


text:
Q: Apache Proxy for Node.js and Wordpress on same "Domain" but different paths Here is the case.
I have a Wordpress website running on my main domain say http://www.example.com.
.htaccess is enabled on server and I am using Wordpress permalinks to generate pretty URLs.
Now I have another application in Node.js (Express) which I have deployed on same server and is running on port number 3000. So if I put http://www.example.com:3000 it triggers my Expressjs app. and it is running flawlessly.
What I want is to run the Node.js application on a specific path from the same domain. For example, if I hit, http://www.example.com/node it should take user to my Node.js app which it is taking quite fine if I use Apache mod_proxy. But this works only for the / route of my Expressjs router.
But I also have several other routes e.g. /subscribe, /confirm but none of them work.
Following is my Apache config which I tried to make work by giving multiple ProxyPass directives but it doesn't work.
ProxyPass /node http://127.0.0.1:3000/
ProxyPassReverse /node http://127.0.0.1:3000/
ProxyPass /node/subscribe http://127.0.0.1:3000/subscribe
ProxyPassReverse /node/subscribe http://127.0.0.1:3000/subscribe

The Express router is pretty basic and uses following app configuration:
var router  = express.Router();
app.use("/",router);

router.get("/",function(req,res){
   res.sendFile(templatepath + "index.html");
});

router.get("/subscribe",function(req,res){
   res.sendFile(templatepath + "subscribe.html");
});

router.get("*",function(req,res){
   res.sendFile(templatepath + "404.html");
});

When I try to load http://www.example.com/node/subscribe it simply loads the * route and displays the 404.html template.

A: Finally got it working by modifying the Apache configuration file as follows:
ProxyPreserveHost On
RewriteEngine On
ProxyPass ^/node/(.*) http://127.0.0.1:3000/$1 [P,L]
ProxyPassReverse /node/ http://127.0.0.1:3000/


text:
Q: Show that there exists $E\subset [0,1]$ such that $m^*(E)=m^*([0,1]\setminus E)=1$. Show that there exists $E\subset [0,1]$ such that
$$m^*(E)=m^*([0,1]\setminus E)=1$$
I have thought to use the Theorem: $A\subset R$ with the property that $A\cap B$ is unmeasurable for every Legesgue measurable set $B$ with $m(B)>0$
But I have trouble to considering why the outer measure of a vitali set can be any number.


text:
Q: How to get all field details in a django LogEntry() I have a LogEntry items I'dlike to call one by one to make a table. So far I have managed to get it working partially with this.

    User
    Date
    Log
    Item Affected
    Item ID

  {% for log in logs %}

      {{ log.user}} - {{ log.user_id }}
      {{ log.action_time|date:"d/m/Y - g:ia" }}
      {{ log }}
      {{ log.object_repr }}
      {{ log.object_id }}
      {{ log.change_message }}

  {% endfor %}

{{ log.change_message }}	 Gives me data in this format.
[{"changed": {"fields": ["Borrower id"]}}]

When I try
{% for log in logs %}
    {{ log }}
{% endfor %}

I get data in this format. Changed "Smart Maths:-MAT/1663/21" — Changed Borrower id.
What would I call in my template in order to get this last part only???? Changed Borrower id
This is my view
def admin_main(request,object=Issue):
    LogEntry.objects.log_action(
        user_id=request.user.id,
        content_type_id=ContentType.objects.get_for_model(Issue).pk,
        object_repr=str(object.book_id),
        object_id=object.id,
        change_message="Items added",
        action_flag=ADDITION)
    logs = LogEntry.objects.exclude(object_id__icontains='django.db.').exclude(object_id__icontains = 'property object').order_by('-action_time')[:40]

    return render(request,'libman/returns_history.html', {"logs":logs})


text:
Q: Google API Client connect results in INTERNAL_ERROR Trying to connect to the Drive API, I've implemented code that matches what's in the Drive Quickstart project, but something's still not right. When calling connect(), my onConnectionFailed method is called with status SIGN_IN_REQUIRED, and I then call result.startResolutionForResult. This presents a small dialog prompting me to select an account. After selecting my account, onActivityResult shows a status of RESULT_OK, but my onConnected method is not called and instead I'm right back in onConnectionFailed with a status this time of INTERNAL_ERROR, and I am not connected. Any ideas on where to look next?
I'm pretty sure that I set up my OAuth credentials with my SHA1 fingerprint from debug.keystore, package name, etc. I noticed that when I set up the credentials in the console, it informed me that my Client ID was something like "myapp-1234". Am I supposed to do anything with this?

A: You can't set up OAuth credentials and immediately run your app for authorization. It apparently takes some time for the registration to make it to the appropriate servers. I went back a couple hours later and everything started working.


text:
Q: $window.on() not working in ES6 javascript I am trying to write some ES6 code that should allow me to do a show hide sticky footer.
My code runs up to a point, but then stops and i cannot fathom why. Am i using the arrow notation incorrectly? I have googled but am not sure i'm asking the right question so not finding anything of use.
const showFoot = {
    init: () => {
      showFoot.initShowFoot();
    },
    initShowFoot: () => {
      const $hero = $('.block--course .jumbotron');
      const $footer = $('.footer--bottom');
      console.log('were initing');
      $(window).on('scroll', () => {
        console.log('were scrolling');
        const yPos = window.pageYOffset;
        if ($footer.is(':visible') && yPos < ($hero.offset().top + $hero.outerHeight())) {
          $footer.fadeOut();
        }

        if (!$footer.is(':visible') && yPos > ($hero.offset().top + $hero.outerHeight())) {
          $footer.fadeIn();
        }
      });
    },
  };

And i get in the console only "were initing".
I do not get "were scrolling". I'm not able to see why this wont give me a console output when i scroll!
Any help would be really gratefully recieved.

A: Turns out the JS code was absolutely fine, but the <body> element had the css overflow-x: hidden on it so the scrolling wasn't being registered on $(window) but i guess would have been on $('body').


text:
Q: Linear Gradient SVG 3 colors increase the width of the middle color I have a linear gradient with the below code
<svg width="120" height="240" >
  <linearGradient id="dsp" x1="0" x2="0" y1="0" y2="1">
    <stop class="stop1" offset="0%"/>
    <stop class="stop2" offset="50%"/>
    <stop class="stop3" offset="100%"/>
  </linearGradient>
  <style type="text/css">
    .stop1 { stop-color: red; }
    .stop2 { stop-color: yellow; stop-opacity: 0.7; }
    .stop3 { stop-color: green; }
  </style>

Now I want to increase the height of the middle color that is the yellow color.
I tried to increase the offset value of yellow color but instead of increasing the width the color band shifts downwards.
I want that the red and green should contain only 10% of the height of the SVG in below format
Red >> 15%
yellow >>  70%
green >> 15%

This is the color distribution expected.

A: just add two more stops in between the start/end stop and the middle...
EDIT based on squeamish ossifrages comment

.stop1 { stop-color: red; }
    .stop2 { stop-color: yellow; stop-opacity: 0.7; }
    .stop3 { stop-color: green; }
<svg width="120" height="240" >
  <linearGradient id="dsp" x1="0" x2="0" y1="0" y2="1">
    <stop class="stop1" offset="0%"/>
    <stop class="stop2" offset="20%"/>
    <stop class="stop2" offset="80%"/>
    <stop class="stop3" offset="100%"/>
  </linearGradient>
  <rect x="0" y="0" width="240" height="120" fill="url(#dsp)"/>
</svg>


text:
Q: How to handle onChange event that sets the state in React? I am learning React and in the below code I get ...cannot update during an existing state transition....  While looking to fix it, I read in SO that setState should not be used within render() as it calls render() repeatedly resulting in infinite loop.  But I dont know how to fix it.
import React from 'react';
import ReactDOM from 'react-dom';

export default class CheckBox extends React.Component{
    constructor() {
        super();
        this.state = {isChecked: false};
    }
    handleChecked () {
        this.setState({isChecked: !this.state.isChecked});
    }
    render(){
        var txt;
        if (this.state.isChecked) {
            txt = 'checked'
        } else {
            txt = 'unchecked'
        }
        return(

            <input type="checkbox" onChange={this.handleChecked()}/>

This box is {txt}

        );
    }
}

ReactDOM.render(<CheckBox/>, document.getElementById('hello'));

A: You should pass to onChange reference to function but not call it., in your example you are calling handleChecked(because there is () after function) and result pass to onChange however result in this case will be undefined so onChange looks like onChange={ undefined }. Also, you can't set state during the initial render, but you are trying to do it with this.handleChecked() which contains this.setState.
export default class CheckBox extends React.Component{
  constructor() {
    super();
    this.state = {isChecked: false};

    // set this (with .bind),
    // because you need get methods from CheckBox, like .setState
    this.handleChecked = this.handleChecked.bind(this);
  }

  handleChecked () {
    this.setState({isChecked: !this.state.isChecked});
  }

  render(){
    var txt;
    if (this.state.isChecked) {
      txt = 'checked'
    } else {
      txt = 'unchecked'
    }

    // remove () after handleChecked because you need pass
    // reference to function
    // also add return statement before

    return

       <input type="checkbox" onChange={ this.handleChecked }/>

This box is {txt}

  }
}

Example


text:
Q: Let $X$ be a set of $5$ elements. Find the number of ordered pairs $(A,B)$ of subsets of $X$ such that $A, B\neq \emptyset$ and $A\cap B=\emptyset$ I know this question involves use of combinatorics, but all the solutions I have seen just give the equation without explaining it. Can I get an explanation, because I know the answer and I know the method, I just don't know how to apply.

A: Let us first find all possibilities such that $A \cap B = \varnothing$.
To create such a pair, each element in $X$ has exactly $3$ possibilities: It is in only $A$, or only $B$, or in neither.
This gives you that there are $3^5 = 243$ ordered pairs $(A, B)$ such that $A \cap B = \varnothing$.
Now, we count the possibilities where one of them is empty. If $A = \varnothing$, then there are exactly $2^5$ possibilities for $B$. ($2^5$ is the total number of subsets of $X$.)
Similarly, if $B = \varnothing$, then there are $2^5$ choices for $A$.
Thus, in total there are $2^5 + 2^5 - 1 = 63$ cases where $A = \varnothing$ or $B = \varnothing$. (The $-1$ is for the double counting of the case $A = B = \varnothing$.)
Thus, the desired answer is $243 - 63 = \boxed{180}.$

A: If $|A| = k>0$ then you have ${5\choose k}$ possibilities for $A$ and $2^{5-k}-1$ possibilities for $B$ since $B\subseteq X\setminus A$ and $B\ne \emptyset$. So you have to sum (use binomial theorem): \begin{align}\sum _{k=1}^5{5\choose k}(2^{5-k}-1) &= \color{red}{\sum _{k=1}^5{5\choose k}2^{5-k}}
-\color{blue}{\sum _{k=1}^5{5\choose k}}\\
&=\color{red}{(2+1)^5-2^5} -\color{blue}{(1+1)^5+1} \\&= 3^5-2^6+1\\ &= 243-64+1 =180 \end{align}


text:
Q: How to create a correct entity-relationship diagram (ERD) about a video game profits scenario I'm starting to build my application database, and I'm really new to the this world, so I have a lot of doubts about my ERD and if its entity types and relationships are ok.
This is an application that calculates how much me and my friends profit in a video game and saves all the data so we can check it later. I'll explain it a bit so you can understand the ERD.
We want to save this data about every Hunt:

*

*Where the HUNT was (RESPAWN)

*How many people we were (1 to 4)

*The date of the HUNT

*How much everyone WASTE (Knight, Druid, Paladin, Sorcerer and the
Total)

*The loot value

*The HUNT balance

*How many profit we did (each one of us)

*The amount of money everyone have to recieve (paying waste + profit
-> TRANSFER)

*And if the HUNT is already paid or not

I'm already doing all the math and saving this data in a .txt file for the moment, but I want to take the next step and build a decent database, and to make sure the following diagram is ok:

Are some relationships wrong? Do you think I should add more entity types, properties, etc.?

A: A question I have is what is the significance of the _EK/_ED columns? I can assume they are separate columns for each person in your party? If that is so, this design would have a lot of NULL values for whenever there isn't 4 people in a hunt, and will outright prevent accounting for a 5 person hunt. I hesitate to suggest a more flexible design until I can better understand what exactly each column is for. I would be happy to expand on what you have if you could post some sample data, such as from a hunt or two, along with a quick explanation of where the information is coming from.
I would also review the datatypes chosen. SMALLINT is fine for key id fields, but it would be best to choose a DATE or DATETIME for your hunt date, instead of varchar. The Paid column has two issues that I see. Including a question mark is not encouraged, instead keep it to alpha-numeric and maybe underscores. If the only two options for that field are Yes/No, then it can be a bit datatype. That way you only store 0 for no, and 1 for yes. That saves a lot of space compared to varchars, and prevents you from having "Yes","YES", and "yes", which are all seen as different depending on your chosen software.


text:
Q: Can I re-open my popup after user grants permisisons? I'm testing edge cases for my chrome extension; handling cases where the user has not yet granted the permissions I need.
My popup calls chrome.identity.getAuthToken and, as expected, the user is show the chrome permissions screen and asked to approve.
But, as a side-effect, this closes my popup. I'd like to either keep the popup open, or re-open it after permission has been granted. Is this possible?

A: 'Popup' is ambiguous.
A page action can be triggered dynamically using chrome.pageAction.show(integer tabId).
A browser action cannot.
I don't know about chrome.identity.getAuthToken but e. g. chrome.permissions.request does not close a page action.
I don't think there is a way to stop it closing either. E. g. a beforeUnload event listener does not seem to work.


text:
Q: VisualAge cpprbi40.dll doesn't work in Windows 10 version 20h2 I developed some applications in VisualAge for Windows in C++ many years ago. The application is running in the Windows 10 Version 2004, but not in the version 20H2 anymore.
I get the error message ccprbi40.dll cannot executed, error status 0xc0000005.
Do you have any idea, what was changed, and how can I bring to work in the 20H2 version?


text:
Q: How to append subset data-frame to another empty data-frame in for loop python I'm having one empty data-frame and a list of columns in list1. I want append the subset data-frame to empty in a for loop.
df

    A1 A2  B1   B2
0   1  11  21   31
1   2  12  22   32
2   3  13  23   33
3   4  14  24   34

empty_df = pd.DataFrame()

listl = [['A1','A2'],['B1','B2']]

for columns in list1:
    empty_df = empty_df.append(df[columns])

Here when I executed above code I'm getting shape(16X4), where I should get shape(16X1) Which should look like.
df

0  1 11
1  2 12
2  3 13
3  4 14
4  21 31
5  22 32
6  23 33
7  24 34

Also is it possible to add another column which describes previous column names like...
df
0  1 11 A
1  2 12 A
2  3 13 A
3  4 14 A
4  21 31 B
5  22 32 B
6  23 33 B
7  24 34 B

A: listl = [['A1','A2'],['B1','B2']]
names = ["A", "B"]                   # or [a_list[0][0] for a_list in listl]

result = pd.DataFrame()

for name, cols in zip(names, listl):
    df_to_concat = df.loc[:, cols]
    df_to_concat.columns = [f"col{j}" for j in range(len(cols))]
    df_to_concat["name"] = name
    result = pd.concat([result, df_to_concat]).reset_index(drop=True)

First we get the df to concatanate, then rename its columns to ease the concatanatetion process, then put a name column to it to signal where it came from and lastly concatanate with what we already have in result (and reset the index to have a 0..N index).
>>> result

   col0  col1 name
0     1    11    A
1     2    12    A
2     3    13    A
3     4    14    A
4    21    31    B
5    22    32    B
6    23    33    B
7    24    34    B


text:
Q: Unregister font with GraphicsEnvironment? I recently found out how to register a TTF font with the local GraphicsEnvironment, s.t., for my use case (SVG-to-PNG transcoding), Apache Batik may recognize the font:
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;

// [...]

GraphicsEnvironment lge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
    Font font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
    lge.registerFont(font);
} catch (FontFormatException e) {
    logger.warn(e.getMessage(), e);
} catch (IOException e) {
    logger.warn(e.getMessage(), e);
}

However, I was wondering if I could unregister any pre-existing fonts in order to guarantee that only the fonts I register will be used in transcoding.
There is no GraphicsEnvironment#unregisterFont(...), how could I achieve this instead?
PS: I don't want to subclass GraphicsEnvironment, as I cannot assume the presence any specific subclass, like  sun.awt.Win32GraphicsEnvironment.
EDIT:  Some more infos:

*

*As sun.font.FontManager changes with Java7 (from class to interface, and whatnot), I'd rather not use any workaround relying on it.

*My JVM is the Oracle JVM.

A: This cannot be done without reflection of private static variables and such... are you sure you need to do this?
Check out the source code to sun.font.FontManager.registerFont, it may already have the safety you desire. (This is the method that does the actual work when you call GraphicsEnvironment.registerFont)
public boolean registerFont(Font font) {
    /* This method should not be called with "null".
     * It is the caller's responsibility to ensure that.
     */
    if (font == null) {
        return false;
    }

    /* Initialise these objects only once we start to use this API */
    synchronized (regFamilyKey) {
        if (createdByFamilyName == null) {
            createdByFamilyName = new Hashtable<String,FontFamily>();
            createdByFullName = new Hashtable<String,Font2D>();
        }
    }

    if (! FontAccess.getFontAccess().isCreatedFont(font)) {
        return false;
    }
    /* We want to ensure that this font cannot override existing
     * installed fonts. Check these conditions :
     * - family name is not that of an installed font
     * - full name is not that of an installed font
     * - family name is not the same as the full name of an installed font
     * - full name is not the same as the family name of an installed font
     * The last two of these may initially look odd but the reason is
     * that (unfortunately) Font constructors do not distinuguish these.
     * An extreme example of such a problem would be a font which has
     * family name "Dialog.Plain" and full name of "Dialog".
     * The one arguably overly stringent restriction here is that if an
     * application wants to supply a new member of an existing family
     * It will get rejected. But since the JRE can perform synthetic
     * styling in many cases its not necessary.
     * We don't apply the same logic to registered fonts. If apps want
     * to do this lets assume they have a reason. It won't cause problems
     * except for themselves.
     */
    HashSet<String> names = getInstalledNames();
    Locale l = getSystemStartupLocale();
    String familyName = font.getFamily(l).toLowerCase();
    String fullName = font.getFontName(l).toLowerCase();
    if (names.contains(familyName) || names.contains(fullName)) {
        return false;
    }

    /* Checks passed, now register the font */
    Hashtable<String,FontFamily> familyTable;
    Hashtable<String,Font2D> fullNameTable;
    if (!maybeMultiAppContext()) {
        familyTable = createdByFamilyName;
        fullNameTable = createdByFullName;
        fontsAreRegistered = true;
    } else {
        AppContext appContext = AppContext.getAppContext();
        familyTable =
            (Hashtable<String,FontFamily>)appContext.get(regFamilyKey);
        fullNameTable =
            (Hashtable<String,Font2D>)appContext.get(regFullNameKey);
        if (familyTable == null) {
            familyTable = new Hashtable<String,FontFamily>();
            fullNameTable = new Hashtable<String,Font2D>();
            appContext.put(regFamilyKey, familyTable);
            appContext.put(regFullNameKey, fullNameTable);
        }
        fontsAreRegisteredPerAppContext = true;
    }
    /* Create the FontFamily and add font to the tables */
    Font2D font2D = FontUtilities.getFont2D(font);
    int style = font2D.getStyle();
    FontFamily family = familyTable.get(familyName);
    if (family == null) {
        family = new FontFamily(font.getFamily(l));
        familyTable.put(familyName, family);
    }
    /* Remove name cache entries if not using app contexts.
     * To accommodate a case where code may have registered first a plain
     * family member and then used it and is now registering a bold family
     * member, we need to remove all members of the family, so that the
     * new style can get picked up rather than continuing to synthesise.
     */
    if (fontsAreRegistered) {
        removeFromCache(family.getFont(Font.PLAIN));
        removeFromCache(family.getFont(Font.BOLD));
        removeFromCache(family.getFont(Font.ITALIC));
        removeFromCache(family.getFont(Font.BOLD|Font.ITALIC));
        removeFromCache(fullNameTable.get(fullName));
    }
    family.setFont(font2D, style);
    fullNameTable.put(fullName, font2D);
    return true;
}


text:
Q: How can you create Shortcuts from an Android Widget? I'm trying to add a new widget functionality to my app, which allows you to create pinned shortcuts from a 'shortcut widget.'
Normally shortcuts in Android are created like in the video below. You long-press the application, select a shortcut, and then you can pin the shortcut onto the homescreen. My app currently implements shortcuts like this following Android developer guidelines.

However, I noticed the Settings app allows you to create many more shortcuts for your app, by allowing shortcuts to be created through the Settings widget like in the video below.

I would like to give users of my app the ability to create shortcuts for the many features in my app, however, most launchers can only display four shortcuts from long-pressing.
Does anyone know how the to implement a App Widget that allows you to create many shortcuts, like the Settings app has implemented?

A: Though it is added from the App widget section, it's not even related to appwidgetprovider. If you're trying to create an app widget, then you're on the wrong path.
I've grabbed some code from my existing projects, hope this helps :)
1.add required permission to AndroidManifest.xml
    <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>

2.add intent-filter <action android:name="android.intent.action.CREATE_SHORTCUT"/> , so your
AndroidManifest.xml should be something like this:
    <activity
        android:name=".ui.SetupWizardActivity"
        android:label="@string/create_shortcut_label">
        <intent-filter>
            <action android:name="android.intent.action.CREATE_SHORTCUT"/>
        </intent-filter>
    </activity>

with those lines added, when the user drags the activity from the widget section to home, the desired activity will be opened.
3.Here's the code used to create a shortcut:
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import androidx.annotation.DrawableRes;
import androidx.core.content.pm.ShortcutInfoCompat;
import androidx.core.content.pm.ShortcutManagerCompat;
import androidx.core.graphics.drawable.IconCompat;

public class ShortcutCreator {

    public static void vCreateShortcutByActivityClass(Context context, String strShortcutID, Class<?> ActivityClass, String strLabelName, @DrawableRes int resourceID){

        if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)){
            Intent intent = new Intent(context, ActivityClass).setAction(Intent.ACTION_MAIN);
            ShortcutInfoCompat sic =
                    new ShortcutInfoCompat.Builder(context, strShortcutID).setIntent(intent).setShortLabel(strLabelName).setIcon(IconCompat.createWithResource(context, resourceID)).build();
            ShortcutManagerCompat.requestPinShortcut(context, sic, null);

        }else{

            Toast.makeText(context, "Device doesn't support creating shortcuts.", Toast.LENGTH_SHORT).show();

        }
    }

}

Note: ShortcutID is used to determine if there're duplicated shortcuts.
4.Now you can do the following modification to your desired activity to call the code for creating shortcut(the activity that displays
many options for creating different shortcuts):
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            final String strIntentAction = getIntent().getAction();
            if (TextUtils.equals(strIntentAction,Intent.ACTION_CREATE_SHORTCUT)) {
                setContentView(R.layout.activity_shortcut);
                //display selections here and let user choose shortcut
                //...deleted
                vCreateShortcutByActivityClass(this, "ID_0", SetupWizardActivity.class, "App Settings", R.mipmap.ic_launcher);
                finish();
                return;
            }

            setContentView(R.layout.activity_main);
            //codes of your activity opened from launcher
            //...deleted
        }

or you can also create a new blank activity for creating a "single"
shortcut, without calling setContentView(), if you only need to
create one shortcut:
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            vCreateShortcutByActivityClass(this, "ID_0", MainActivity.class, "App Settings", R.mipmap.ic_launcher);
            finish();
        }

Note : For devices under Android Nougat(7.1), the target activity that the shortcut tries to open must contain at least one intent-filter tag(can be any, consider adding <category android:name="android.intent.category.DEFAULT"/> for hidden activities), otherwise the shortcut may display "app is not installed".


text:
Q: Creating subsets of a data frame, saving output to workplace, and dynamically naming data frames I have a data frame which needs to be subset-ed into 20 unique data frames based on a categorical variable. I am aware that you are able to do so by utilizing the "subset" function as such:
df.# <- subset(df,categorical_variable == #)
However, I would like to automate this process by creating a a function which loops through the possible range of responses in the categorical variable (1:20), dynamically setting the name of the data frame, and creating subsets based on the current value of "i."
Here is a stylized version of what I would want:
create_subsets <- function(df) {
                  x <- 1:20
                  for(i in seq_along(x)) {
                      paste(df,x[i],sep=".") <<- subset(df,categorical_variable == x[i])
                  }
              }

I understand that the above function is impossible, specifically the section where I set the paste function equal the subset function-the point is to illustrate my aim. How can I dynamically name the subsets, and save them to the workplace?
Thank you.


text:
Q: Time series representing with other time series in R Y | X1 | X2 | X3 | X4 | X5
and there are 10 rows. each column represents a time series data. What I want to do is, I want to combine all X columns with some weights to represent column Y. So, in this case, I just want an 5 output that represents the weight from X1 to X5.
Is it possible to make this calculation in R? what should be the initial step that I should take?
After finding this I will try to add some constraints like choosing maximum 3 different series. I am trying to use optim function but I could not find a way.
Any help is appreciated.
thanks


text:
Q: How do launcher apps uninstall apps in the background? Background
I have a spare time app that one of its main features is to easily uninstall apps.
The problem
I'm using a very basic API for uninstalling apps, which for the user seems like 2 steps: confirm uninstalling, and seeing some dialog showing the uninstall-process.
I've noticed that on some launcher apps (such as Nova launcher and Pixel Launcher), upon uninstall, they show only one step, of confirmation of uninstalling the chosen app.
Here's how it looks via my app and from the normal, built in screen of app-info. First you see this:

and then this:

However, on the launcher, you see just this:

And shortly after, the app is gone without you seeing anything in between.
What I've found
Only way I know of uninstalling an app in the background, is by using root, but that's not what those apps do.
Here's what I use for the normal uninstall procedure:
public static Intent prepareUninstallAppIntent(@NonNull final Context context, @NonNull final String packageName) {
    final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, Uri.fromParts("package", packageName, null));
    intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
    intent.putExtra("android.intent.extra.UNINSTALL_ALL_USERS", true);
    return null;
}

The questions

*

*How do the launcher apps only show the confirmation dialog alone, and perform the uninstall in the background?

*Is it a new API? If so, from which version? And where can I read about it?
EDIT: this doesn't matter anymore. Got to see how it works.

I've now found, by looking at Lawnchair launcher app code, that it's a bit similar to what I did:
public static boolean startUninstallActivity(
        final Launcher launcher, ItemInfo info, DropTargetResultCallback callback) {
    Pair<ComponentName, Integer> componentInfo = getAppInfoFlags(info);
    ComponentName cn = componentInfo.first;

    final boolean isUninstallable;
    if ((componentInfo.second & AppInfo.DOWNLOADED_FLAG) == 0) {
        // System applications cannot be installed. For now, show a toast explaining that.
        // We may give them the option of disabling apps this way.
        Toast.makeText(launcher, R.string.uninstall_system_app_text, Toast.LENGTH_SHORT).show();
        isUninstallable = false;
    } else {
        Intent intent = new Intent(Intent.ACTION_DELETE,
                Uri.fromParts("package", cn.getPackageName(), cn.getClassName()))
                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        intent.putExtra(Intent.EXTRA_USER, info.user);
        launcher.startActivity(intent);
        isUninstallable = true;
    }
    if (callback != null) {
        sendUninstallResult(
                launcher, isUninstallable, componentInfo.first, info.user, callback);
    }
    return isUninstallable;
}

It works there the same as on other launchers, so, to me it seemed they added the part of uninstalling for current user (got it using android.os.Process.myUserHandle(); ) .
But I tried it anyway. Seems to work, so what I tried then is to remove more and more code till I got something that works without weird things.
Here's the minimal code:
    final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, Uri.fromParts("package", packageName, null));

and you just use startActivity, instead of startActivityForResult.
Yes. It's that short, and I wonder how long I've missed using this...
But now I got other questions:

*

*What is the cn.getClassName() and the Intent.EXTRA_USER used for?

*From which version of Android will this code uninstall the app in the background?

*Is there any difference between ACTION_UNINSTALL_PACKAGE and ACTION_DELETE here?

*I removed all flags and it still seem to do the same exact job, without a task that's in the history. Are they really needed?

*Are there more ways to uninstall apps? Maybe in a batch?


text:
Q: What could be wrong with this function? I wrote the following to manually make changes to a button when clicked
const links = document.getElementsByTagName('a');

links.addEventListener('click', () => {
  links.classList.add('clickedLink');
})

..but the threw an error

TypeError: links.addEventListener is not a function
at /script.js:4:7'

..what seems to be the problem?

A: It says getElements,hence more elements,so you should run a loop for adding the event listeners on each element
for(let link of links){
link.addEventListener...
}


text:
Q: VBA Code to Save PPT Slides as PNG Files While Ignoring Hidden Slides I have a PPT than can have any number of slides, any one of which may be hidden when needed. I have a macro written to save the presentation as png images, but it will save every slide (including hidden slides) as separate images. I want it to save all EXCEPT the hidden slides. Does anyone know of a way to either Export or SaveAs that will skip over the hidden slides? When I export it as a PDF it will automatically ignore the hidden slides, but that is not the case with png files.
Code that saves all slides, including hidden slides:
ActiveWindow.Presentation.SaveAs filenamepng, ppSaveAsPNG 'Save the.png files for each slide.

I see there are options to not "print" hidden slides, but I see no similar options for saving png images. Thanks for any help you can give me!

A: Thanks to SteveRindsberg's comment I was able to come up with the following code that solved the problem.
Dim sld As Slide
Dim shp As Shape

    i = 1

For Each sld In ActivePresentation.Slides
    For Each shp In sld.Shapes
    On Error Resume Next
        If ActivePresentation.Slides(i).SlideShowTransition.Hidden = msoFalse And shapeName(ActivePresentation.Slides(i), "NameofShapeonSlide") Then
            ActivePresentation.Slides(i).Export filenamepng & "SlideName" & i & ".png", "PNG"

        End If
    i = i + 1
    Next
Next


text:
Q: How to force an Access query datasheet to refresh its data I am new on access and what I am trying to do is a select with a criteria so I created a query with the wizard and seted the criteria with a text from a form ([Forms]![Form1]![Transacao]) and created a button to run the query at the first time works great but when I type something else and click the button the datas do not refresh. What I have to do to refresh? I've tryed to add refresh on the event click of the button and did not work.
Thanks in advance for your help.

A: In Access, a query is usually opened in a default Datasheet view.  This default datasheet is contained in a window (or tab) that is only accessible using Macros or DoCmd in VBA.
Once a query window is open, its data will not necessarily update automatically when new records are added to the underlying table(s).  The datasheet needs to be "requeried".  (Incidentally, the term "refresh" is usually reserved to mean "redrawing" a window on the screen and has nothing to do with the data.  This is especially the case in programming and development environments which deal with data and drawing/painting windows and controls on the screen.)
Here is one way to force a query to update its data (when open in its default datasheet view):
DoCmd.OpenQuery "QueryName"
DoCmd.Requery

Calling OpenQuery should also activate the query window if it is already open.  If you find that the windows does not activate, you can also call DoCmd.SelectObject acQuery, "QueryName" before DoCmd.Requery.
The DoCmd methods correspond to Macro actions, so if the query is activated by a Macro, just add the Requery action to the macro after the OpenQuery or SelectObject actions.  Leave the Control Name parameter of the Requery action blank to force the entire query to updated.

A: I know this question is a bit stale at this point, but since I couldn't find a suitable answer to this question and the above answer didn't work for me (and still hasn't been accepted), I thought I'd offer my solution for those few poor saps still stuck developing applications in Access. My use case was slightly different (changing the underlying SQL of a query, then opening/refreshing it), but the same principle could be applied. The gist is to first check to see if the query is open and close it if it is. Then open it up again.
To do this, paste this code into a VBA module:
Public Function open_or_refresh_query(query_name As String, Optional sql_str As String = "")
' Refresh or open an existing query
' query_name: Name of the query
' sql_str: optional new SQL string if changing the underlying SQL. If not given,
'   the query will open with its existing SQL string

    On Error GoTo err_handler

    Dim qdf As QueryDef
    ' Loop through each query in the DB and find the one of interest by name
    For Each qdf In CurrentDb.QueryDefs
        If qdf.Name = query_name Then
            ' If the query is open, close it
            If SysCmd(acSysCmdGetObjectState, acQuery, query_name) <> 0 Then
                DoCmd.Close acQuery, query_name, acSaveNo
            End If
            Exit For
        End If
    Next qdf

    Set qdf = CurrentDb.QueryDefs(query_name)

    ' Reset the SQL if new SQL string was given
    If Len(sql_str) > 0 Then qdf.sql = sql_str

    ' Close the QueryDef object to release resources
    qdf.Close

    ' Open the query in default datasheet view
    DoCmd.OpenQuery query_name

exit_function:
    Exit Function

err_handler:
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Error"
    Resume exit_function

End Function

At this point you could call this function from any other VBA code in your project. To open/refresh a query from a macro as the OP wanted to do, create a new macro and add a RunCode action with open_or_refresh_query("my_query") in the Function Name field, changing my_query to the name of your query.


text:
Q: Select statement between two java.sql.Date my code is:
    java.sql.Date fromDate= new java.sql.Date(date1);
    java.sql.Date toDate= new java.sql.Date(date2);

    String select = "SELECT * FROM Table WHERE Date between " + fromDate+ " and" + toDate;

I´m using Derby database, and I have to run this query but return error. How can I do? Thanks.

A: First, stop building SQL like that. It's vulnerable to SQL injection attacks, conversion issues (which is probably the problem here) and it's hard to read.
Use parameterized SQL instead:
// TODO: Close the statement, e.g. using a try-with-resources statement
// or a finally block.
PreparedStatement statement =
    conn.prepareStatement("SELECT * FROM Table WHERE Date between ? and ?");
statement.setDate(1, fromDate);
statement.setDate(2, toDate);
ResultSet results = statement.executeQuery();
// Use the results

This may well be enough to fix the problems immediately. If it's not, please give more details.

A: Use PreparedStatement. The JDBC tutorial includes plenty of examples.
While we are on the subject, this may be a good time to learn about SQL injection attacks (obligatory xkcd reference).


text:
Q: PHP neglecting .00 values i.e float values and converting it in int automatically I'm Just fetching values from MySQL Database in php and in return it just neglecting .00 in last and converting float values in integer in php. but in my database all values are in float.. see my database screenshot

my php code below
    public function GetSchemes(){
    include "../includes/config.php";

    if($_SERVER['REQUEST_METHOD'] == 'POST') {

        $sql = "SELECT * FROM ticket_info";

        $post = $this->get_list_result($sql);
                $respon = array(
                    'status' => 'ok','scheme' => $post
                );
                $this->response($this->json($respon), 200);
    }

}

   public function get_list_result($query) {
    $result = array();
    $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
    if($r->num_rows > 0) {
        while($row = $r->fetch_assoc()) {
            $result[] = $row;
        }
    }
    return $result;
}

and I'm getting these values
{
"status": "ok",
"scheme": [
    {
        "id": 1,
        "ticket_type": "Bumper",
        "ticket_name": "p1",
        "mrp": 250,
        "selling_price": 225,
        "series": 2,
        "booklet": 20
    },
    {
        "id": 2,
        "ticket_type": "Bumper",
        "ticket_name": "p2",
        "mrp": 200,
        "selling_price": 190,
        "series": 10,
        "booklet": 1
    },
    {
        "id": 5,
        "ticket_type": "Daily",
        "ticket_name": "p3",
        "mrp": 6,
        "selling_price": 5.5,
        "series": 5,
        "booklet": 5
    },
    {
        "id": 6,
        "ticket_type": "Daily",
        "ticket_name": "p4",
        "mrp": 6,
        "selling_price": 5.5,
        "series": 25,
        "booklet": 1
    },
    {
        "id": 7,
        "ticket_type": "Daily",
        "ticket_name": "p5",
        "mrp": 6,
        "selling_price": 5.5,
        "series": 50,
        "booklet": 1
    },
    {
        "id": 8,
        "ticket_type": "Daily",
        "ticket_name": "p6",
        "mrp": 6,
        "selling_price": 5.5,
        "series": 100,
        "booklet": 1
    },
    {
        "id": 9,
        "ticket_type": "Daily",
        "ticket_name": "p7",
        "mrp": 6,
        "selling_price": 5.5,
        "series": 200,
        "booklet": 1
    }
]

}
See in API Result mrp should be 250.00 but its showing 250 and selling_price should be 225.00 but its showing 225 i.e .00 in last is missing... but In my database.. .00 values are saved..
Why PHP is neglecting .00 values at last... I want to use .00 values
Thanks

A: Float values are represented in JSON without any formatting. If you want to keep the formatting, you'll need to use number_format() or sprintf() and convert the floats to strings before using json_encode().
while ($row = $r->fetch_assoc()) {
    $row['mrp'] = number_format($row['mrp'], 2);
    $row['selling_price'] = number_format($row['selling_price'], 2);
    $result[] = $row;
}

You can use JSON_PRESERVE_ZERO_FRACTION with json_encode(), but that will just ensure the number is encoded as a float, not apply formatting with a specific number of decimal places, so for numbers with .00, you'll just see .0 in the JSON.
I'm referring to trailing zeroes as formatting because as far as a float is concerned, 250.00 and 250 are the same thing.

A: Verify the serialize-precision and precision directives in the php.ini file. You may need to configure this value.
https://www.php.net/manual/en/ini.core.php#ini.serialize-precision
https://www.php.net/manual/en/ini.core.php#ini.precision
Also you can try to pass those values to string, enclosing them in double quotes.


text:
Q: Group by date and take the last one This is my table :

What I'm trying to do, is to take the last disponibility of a user, by caserne. Example, I should have this result :
id    id_user    id_caserne    id_dispo    created_at
31    21         12            1           2019-10-24 01:21:46
33    21         13            1           2019-10-23 20:17:21

I've tried this sql, but it does not seems to work all the times :
SELECT * FROM
    ( SELECT id, id_dispo, id_user, id_caserne, MAX(created_at)
    FROM disponibilites GROUP BY id_user, id_caserne, id_dispo
    ORDER BY created_at desc ) AS sub
GROUP BY id_user, id_caserne

What am I doing wrong ?

A: I would simply use filtering in the where clause using a correlated subquery:
select d.*
from disponibilites d
where d.created_at = (select max(d2.created_at)
                      from disponibilites d2
                      where d2.id_user = d.id_user
                     );

EDIT:
Based on your comments:
select d.*
from disponibilites d
where d.created_at = (select max(d2.created_at)
                      from disponibilites d2
                      where d2.id_user = d.id_user and
                            d2.id_caserne = d.id_caserne
                      where date(d2.created_at) = date(d.created_at)
                     );

A: You can use a correlated subquery, as demonstrated by Gordon Linoff, or a window function if your RDBMS supports it:
select * from (
    select
        t.*,
        rank() over(partition by id_caserne, id_user order by created_at desc) rn
    from disponibilites t
) x
where rn = 1

Another option is to use a correlated subquery without aggregation, only with a sort and limit:
select *
from mytable t
where created_at = (
    select created_at
    from mytable t1
    where t1.id_user = t.id_user and t1.id_caserne = t.id_caserne
    order by created_at desc
    limit 1
)

With an index on (id_user, id_caserne, created_at), this should be a very efficient option.

A: you can join your max(created_date) to your original table
select t1.* from disponibilites t1
inner join
    (select max(created_at), id_caserne, id
    from disponibilites
    group by id_caserne, id) t2
on t2.id = t1.id


text:
Q: Unable to display detailed startup error with Blazor In my Blazor-server app, one of the injected services will perform some system checking and throw an exception if the checking failed. The plan is to use this exception to remind the programmers that a certain condition is needed for the app to run correctly. However, Blazor simply shows

Error: The circuit failed to initialize.

in the browser console, and the message of my exception is nowhere to be found. Also, Visual Studio does not break on my exception in debug mode with the default breaking settings, supposedly because Blazor caught my exception. Therefore the only way I found so far that could actually display my exception is to change the breaking setting to "break on all runtime exceptions", but I don't think this is good enough since the future programmers on this project might not know it.
So is there any way I can configure Blazor to display the startup exception details or to stop catching my exceptions? I've tried
services.AddServerSideBlazor(options => {
    options.DetailedErrors = true;
});

but it's not helping. I don't think it's relevant to my case here.

A: One way of doing this is to add some custom code in your Startup.cs file, right at the end of your Configure method. By the point that the startup sequence gets that far, all your services should be registered including your testing service. To get access in the Configure method, first you need to add the service type and a variable name to the method signature, and then call your methods on the service at the end of the method. See below:
public void Configure(IApplicationBuilder app, ...other things,  ITestingService testService)
{
    // all your other startups configs

    testService.RunTestMethods();
}

the ITestingService represents your service to do the checking. The DI framework will pick up that you need that service in the Configure method and give you an instance of it, and then you can execute any methods that you need, throw or propagate exceptions and log them if needed, etc. the key here is that if you throw the exception before the end of the Configure method, the app will not start, so make sure to get your logging on even if it's a console log to scold a developer in the CLI that they need to correct something.


text:
Q: What is wrong with my multi process program? I'm doing a program with the objective of creating a process within a process 3 times(get a child process(1), a grand child process(2) and a grand grand child(3) process) and do actions in each process in reverse order of the creation order. Which means first I do the actions of (3) then the actions of (2) then of (1) then of the parent process. But the output is weird like doing 6 printfs and multiple processes saying they have the same pid.
Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
    pid_t mypid = getpid();
    pid_t child1_pid=fork();

    pid_t child2_pid=-1; //waiting for child1 to fork
    pid_t child3_pid=-1; //waiting for child2 to fork

    int status;

    if(child1_pid==0)
    {
        mypid=getpid();
        child2_pid=fork()

        if(child2_pid==0)
        {
            mypid=getpid();
            child3_pid=fork()

            if(child3_pid==0)
            {
                mypid=getpid();
                printf("3: Im %ld and my parent is %ld\n", mypid, getppid());
            }
            wait(&status);
            printf("2:Im %ld and my parent is %ld\n", mypid, getppid());
        }
        wait(&status);
        printf("1:Im %ld and my parent is %ld\n", mypid, getppid());
    }
    else
    {
        wait(&status);
        printf("\nIm the father and my pid is %ld\n", mypid);
    }
    return 0;
}

What I'm asking is what I'm doing wrong and where is my logic incorrect and maybe point me to some reading in the web.
Thanks in advance.

A: if(child1_pid==0)
    {
        mypid=getpid();
        child2_pid=fork()

        if(child2_pid==0)
        {
            mypid=getpid();
            child3_pid=fork()

            if(child3_pid==0)
            {
                mypid=getpid();
                printf("3: Im %ld and my parent is %ld\n", mypid, getppid());
            }
            wait(&status);
            printf("2:Im %ld and my parent is %ld\n", mypid, getppid());
        }
        wait(&status);
        printf("1:Im %ld and my parent is %ld\n", mypid, getppid());
    }

In this code the grand grand child will print 3 times: the printf inside its if and the outer 2 ones.
The grand child will print its printf and its outer one and so one.
Your new processes are continuing to execute the rest of your code normally which means it'll print the following printf's that exist in the code.
For the code to execute as you desire you must terminate execution in each grand child process and each father process must wait for its child to terminate prior to printing.
The following should work as you desire.
if(child1_pid==0)
{
    mypid=getpid();
    child2_pid=fork()

    if(child2_pid==0)
    {
        mypid=getpid();
        child3_pid=fork()

        if(child3_pid==0)
        {
            mypid=getpid();
            printf("3: Im %ld and my parent is %ld\n", mypid, getppid());
            return 0;
        }
        waitpid(child3_pid,&status,0);
        printf("2:Im %ld and my parent is %ld\n", mypid, getppid());
        return 0;
    }
    waitpid(child2_pid,&status,0);
    printf("1:Im %ld and my parent is %ld\n", mypid, getppid());
}else
{
    waitpid(child1_pid,&status,0);
    printf("\nIm the father and my pid is %ld\n", mypid);
}
return 0;

The function waitpid waits for the  pid specified process to finish.
The function declarations is the following:
pid_t waitpid(pid_t pid, int *status,int options);

The value 0 for the options parameter used in the code shown before indicates that it should the default behavior (wait for the termination of the process).

A: Adding to DMH answer, you should also use write() instead of printf, as printf is buffering the output, so the results might be mixed at the end of the output
.
http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html


text:
Q: second dual of minimal tensor products of $C^*$-algebras Let $A$ be a unital $C^*$-algebras and $K(H)$ is $C^*$-algebras of compact operators on separable Hilbert space $H$. Is it true that $(A \otimes K(H))^{**}= A^{**} \overline{\otimes}B(H)$?

A: Yes (but maybe there is a more direct argument ? ):
$A$ and $K(A) = A \otimes K(H)$ are Morita equivalent so they have equivalente categories of representations, moreover this equivalence is implemented as following: any representation of $K(A)$ is of the form $H \otimes R$ with $R$ a representation of $A$.
$A^{**}$ can be constructed as the weak closure of $A$ into some "universal" representation of $A$, i.e. a representation $V$ such that any other representation is a direct sum of subrepresentations of $V$.
A universal representation of $A$ and of $K(A)$ corresponds to each other under the above equivalence (because being universal is a purely categorical property)
SO this mean that there is a representation $V$ of $A$ such that:
$A^{**}$ is the weak closure (double commutant) of $A$ into $B(V)$.
$K(A)^{**}$ is the weak closure of $A \otimes K(H)$ in $B(V \otimes H)$.
Because the commutant of $A \otimes K(H)$ is $A' \otimes \mathbb{C}$ (still because of the above equivalence of catégores: the commutant is the set of endomorphism of representations) and the bi-comutant of $A \otimes K(H)$ is indeed $A'' \otimes B(H)$ (for the spatial tensor product).


text:
Q: Marginal Distribution Function of Bernoulli #homework I am looking for a marginal distribution function for the following situation:
B is a random variable which represents the sum of D independent Bernoulli trials. The probability for success equals p. The amount of Bernoulli trials is a random variable (D), which behaves like a Poisson distribution function with parameter λ.
I have got a solution, but I am not sure if mine is correct.
d=0,1,2,3,4,5,6......
I could not upload the picture of my calculation so here is a link
Calculation
Thank you very much

A: Here is an equation that holds for all integers $b$:
$$ \underbrace{Pr[B=b]}_{\mbox{left-hand-side}} = \underbrace{\sum_{d=0}^{\infty} Pr[B=b|D=d]Pr[D=d]}_{\mbox{right-hand-side}} $$
Structural observations of this equation:

*

*The left-hand-side depends on a parameter $b$, and nothing else.

*The right-hand-side depends on a parameter $b$, and nothing else. While the right-hand-side also has a variable $d$, this is a "dummy variable" that is summed out, so that the overall value of the right-hand-side is only affected by the parameter $b$ (its value can change as different values of $b$ are plugged in).

Derivation of the equation:  Recall the law of total probability that for any event $\mathcal{A}$ and any collection of "mutually exclusive and collectively exhaustive" events $\{\mathcal{B}_0, \mathcal{B}_1, \mathcal{B}_2, ...\}$ we have:
$$ Pr[\mathcal{A}] = \sum_{i=0}^{\infty} Pr[\mathcal{A}|\mathcal{B}_i]Pr[\mathcal{B}_i] $$
In this case you can define the events $\mathcal{A}$ and $\mathcal{B}_i$ by:

*

*$\mathcal{A} \equiv \{B=b\}$

*$\mathcal{B}_i \equiv \{D=i\}$ for $i \in \{0, 1, 2, \ldots\}$. Note that these are indeed "mutually exclusive and collectively exhuastive."

Where to go from here:  Once you agree on the above equation, it remains only to compute:

*

*$Pr[D=d]$ for all relevant values of $d$ (of course, this is given to you: You are told that $D$ has a Poisson distribution)

*$Pr[B=b|D=d]$ (you must compute this for all relevant $b$ and $d$ values)
The conditional probabilities are indirectly given to you, since you are told that, given $D=d$, $B$ is the sum of $d$ i.i.d. Bernoulli random variables, and hence is a "famous" random variable (one that has a "name"). (Hint:  It is not "Gaussian" or "Bernoulli" but...).
Also notice that $Pr[B=23|D=4] = 0$, for obvious reasons, so you can restrict the summation to relevant terms.


text:
Q: Textarea value outside of textarea in modal : weird I have a modal which pops out a form, allowing an admin to edit/update a news story. It works just fine, updating the database and everything, only the 'Story' piece appears outside of the textarea box when in the modal window.
A few pictures will illustrate my point and confusion.

'Look YAY' is the current story, being pulled into the area underneath the textarea

adding in a new story

the new story is now in the database, but underneath the textarea box in the modal

yet on the actual form page it is where it is suppose to be
I've checked and rechecked my code, but my only thought is that jquery-UI is somehow interfering with the textarea since, by definition, the code within the modal is equivalent to that of the Edit News form.
Here is the form code for the story element
    Story<br/>
    <textarea name="edit_story"/><?php print $row['story'];?></textarea>

and the jquery which pops it open
$('.edit').click(function(event){
        //don't follow the link
        event.preventDefault();
        var $link = $(this).parent();
        //load in the html from the form at edit_news
        var formDOM = $("<div />").load($link.attr('href')+' #edit_form', function() {
                //clear the dialog box
        $('#dialog-edit').empty();
                // Append to the page
                $('#dialog-edit').append(formDOM);
                //make the dialog
                $('#dialog-edit').dialog({
                    autoOpen:false,
                    title:$link.attr('title'),
                    width:530,
                    height:465
                })
                //open it up
                $('#dialog-edit').dialog('open');
                $('#edit_form').submit(function(event){
                    //knock out its form processing
                    event.preventDefault();
                    $.ajax({
                type    : "post",
                        url     : $link.attr('href'),
                        data    : $(this).serialize(),
                        success : function() {
                            //close dialog
                    $('#dialog-edit').dialog('close');
                            }
                    })
                })
        })
    });

What is going on here?
if anyone has any ideas please toss them my way. It may very well be a n00bish programming error, which I will gracefully accept.

A: You are closing <textarea> tag before printing text into it. Fix:
<textarea name="edit_story"><?php print $row['story'];?></textarea>


text:
Q: Vue + typescript - TypeError: Object prototype may only be an Object or null: undefined TypeError: Object prototype may only be an Object or null: undefined
I got some error in my project.
I'm using vuejs, typescript and jest.
It's just simple code and I tried to unit test with jest, but It have some error. Here is my test code.
///<reference path="../../../../node_modules/@types/jest/index.d.ts"/>
// https://vue-test-utils.vuejs.org/kr/s
import { mount } from "vue-test-utils";
import HelloWorld from './HelloWorld.vue';

describe('[HelloWorld]', function () {
  let cmp: any;

  beforeEach(() => {
    cmp = mount(HelloWorld);
  });

  it("Check vue instance", () => {
    expect(cmp.isVueInstance()).toBeTruthy();
  });

  it("message is Hello", () => {
    expect(cmp.vm.msg).toEqual('Hello!!');
  });
});

and Here is vue file
   <template>

{{ msg }}

       <button @click="clickHandler">
         button
       </button>

   </template>

Here is error logs with picture.

A: You should set esModuleInterop = true for your tsconfig.json or your own tsconfig just for jest

A: For me, using import * as Vue from "vue" instead of import Vue from "vue" fixed the problem for my projects with a similar setup, i.e.:
//import Vue from "vue";
import * as Vue from "vue";
import Component from "vue-class-component";

interface HelloWorldInterface {
  msg: string;
  clickHandler(): void;
}

@Component
export default class HelloWorld extends Vue implements HelloWorldInterface {
  msg = "Hello!!";
  clickHandler() {
    window.alert(this.msg);
  }
}

It is a lot more cumbersome, but at least it works. I have setup a proof-of-concept example using vue-cli: https://codesandbox.io/s/mjvjw2xw39

A: The problem seems to be how Vue2 exposes itself, so import Vue from "vue" causes this error.
I fixed it by using 'vue-property-decorator' like this:
import { Vue, Component, Prop } from 'vue-property-decorator';

So what does 'vue-property-decorator' do? It imports and then exports Vue not as default but named export. I guess you could do that in your own code, if you wanted.
import Vue, { PropOptions, WatchOptions } from 'vue';
...
export { Component, Vue, mixins as Mixins };

A: Not
 it("message is Hello", () => {
    expect(cmp.vm.msg).toEqual('Hello!!');
  });

Should be
it("message is Hello", () => {
    expect(cmp.msg).toEqual('Hello!!');
  });

A: I solved the problem by removing lang="ts" from tag

A: Checkout this link below, it really helped me resolve CIRCULAR DEPENDENCY issue with the command
npx madge --circular --extensions ts ./
Link:
To Detect Circular Dependency in you package
Neverthless I'm still getting the Error..!! :(


text:
Q: php for two variables can't multiply I have a simple for loop with 2 variables.
I want $m variable to be multiplied by 1.5 in every pass.
But $m value remains the same. Here's the code:
for ($i=0, $m=60 ; $i < 30; $i++, $m*1.5) {
    echo $i." ".$m." " .$m/4 ."
";
}

The result is:
0 60 15
1 60 15
2 60 15
3 60 15
4 60 15
5 60 15
6 60 15
7 60 15
8 60 15
9 60 15

A: You are echoing $m and not $m*1.5.
$i++ is the same as $i =$i +1.
So the code at the end of the for is the one that is evaluated after every loop; $m is multiplied by 1.5 but the result isn't stored in it.
To fix this change:
$m* 1.5.
To:
$m =$m*1.5

A: for ($i=0, $m=60 ; $i < 30; $i++, $m*=1.5) {
echo $i." ".$m." " .$m/4 ."
";
}

A: You need to write
$m*=1.5

instead of $m*1.5.

A: You appear to have forgotten that $i++ is shorhand for $i = $i + 1.
What you need is the following:
for ($i=0, $m=60 ; $i < 30; $i++, $m = $m*1.5) {
    echo $i." ".$m." " .$m/4 ."
";
}

A shorter form of the same thing is:
for ($i=0, $m=60 ; $i < 30; $i++, $m *= 1.5) {
    echo $i." ".$m." " .$m/4 ."
";
}


text:
Q: Proof: $X$ is Hausdorff if and only if the diagonal $\Delta$ is closed in $X\times X$. Prove that $X$ is Hausdorff if and only if the diagonal $\Delta$ is closed in $X\times X$.
This exercise appeared on a previous exam in my course, and also in Munkres. Here's my attempt:
First I want to show the implication starting with assuming that $X$ is Hausdorff. Consider $(X\times X)\backslash \Delta$, then for any tuple $(x_1, x_2) \in (X\times X)\backslash \Delta$ we know $x_1\neq x_2$. Then there are neighbourhoods $U,V$ of $x_1,x_2$ respectively such that $U\cap V = \emptyset$. The set $U\times V$ is a basis element of $X\times X$ so it's in the product topology. So any tuple $(x_1, x_2) \in (X\times X)\backslash \Delta$ lies in an open set of $X\times X$, thus $(X\times X) \backslash\Delta$ is open which makes $\Delta$ closed in $X\times X$.
Now I assume that $\Delta$ is closed in $X\times X$. Then $(X\times X)\backslash\Delta$ is open in $X\times X$. Unless I'm mistaken, every open set $A\times B$ in $X\times X$ will be a subset of $(X\times X)\backslash\Delta$. Then $A\cap B = \emptyset$ because otherwise we would have $(x_1,x_1)\in A\times B \subseteq (X\times X)\backslash\Delta$ for some $x_1\in X$, which is a contradiction. Thus $X$ is Hausdorff.
I'm simply wondering if my argument is correct.