text:
Q: How do I insert random images from my drawable folder to randomly appear on the screen when loaded? I have 15 Images in my drawable folder and want 6 of these random images from this folder to be inserted into given locations when I open this page.
Any help will be greatly appreciated. Below is my xml

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="30dp"
    android:layout_marginLeft="65dp"
    android:src="@drawable/circle" />

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/imageView1"
    android:layout_marginRight="65dp"
    android:src="@drawable/eclipse" />

<ImageView
    android:id="@+id/imageView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageView1"
    android:layout_below="@+id/imageView1"
    android:layout_marginTop="52dp"
    android:src="@drawable/invertedtriangle" />

    <ImageView
    android:id="@+id/imageView4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/imageView2"
    android:layout_below="@+id/imageView1"
    android:layout_marginTop="52dp"
    android:src="@drawable/square" />

    <ImageView
    android:id="@+id/imageView5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageView1"
    android:layout_below="@+id/imageView3"
    android:layout_marginTop="52dp"
    android:src="@drawable/star" />

    <ImageView
    android:id="@+id/imageView6"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageView2"
    android:layout_below="@+id/imageView3"
    android:layout_marginTop="52dp"
    android:src="@drawable/polygon" />

 </RelativeLayout>

Thanks.

A: Here you are:
First of, you need to import the namespace that contains the random object:
import java.util.Random;

Then you have to take an object out of it
final Random rnd = new Random();

Now, all the action happens in your onCreate method, after you set your contentView:
// Reference the images
ImageView img1 = (ImageView) findViewById(R.id.imageView1);
ImageView img2 = (ImageView) findViewById(R.id.imageView2);
ImageView img3 = (ImageView) findViewById(R.id.imageView3);
ImageView img4 = (ImageView) findViewById(R.id.imageView4);
ImageView img5 = (ImageView) findViewById(R.id.imageView5);
ImageView img6 = (ImageView) findViewById(R.id.imageView6);

// Your images are named img_0.png to img_14.png

// For image 1
final String str = "img_" + rnd.nextInt(14);
img1.setImageDrawable
(
    getResources().getDrawable(getResourceID(str, "drawable",
        getApplicationContext()))
);

// For image 2
str = "img_" + rnd.nextInt(14);
img2.setImageDrawable
(
    getResources().getDrawable(getResourceID(str, "drawable",
        getApplicationContext()))
);

// ...

Now, where is the trick?
In this method:
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
    final int ResourceID =
        ctx.getResources().getIdentifier(resName, resType,
            ctx.getApplicationInfo().packageName);
    if (ResourceID == 0)
    {
        throw new IllegalArgumentException
        (
            "No resource string found with name " + resName
            );
    }
    else
    {
        return ResourceID;
    }
}

I left out the lines of code for image 3 to 6, but they are the very same as for image 2.


text:
Q: How to cast a variable to a particular type to convince typescript that everwhere? For IE reasons I need to build a custom Error, however, as best as I can do it, the error has to be checked with the constructor.
customError instanceof CustomError; // false
customError.constructor === CustomError; // true

Now how can I convince typescript that in an if statement?
if (customError.constructor === CustomError) {
  customError.customMethod1() // typescript complaints
  customError.customMethod2() // typescript complaints
  customError.customMethod3() // typescript complaints
  customError.customMethod4() // typescript complaints
}

EDITED:
Background is when you are compiling down to ES5, some inheritances cannot be compatible.
Is there a way I can cast it once and not have to use as everytime I use the variable?
So far the only way to work with it is:
const myCustomError = (customError as CustomError)

Open to other bright ideas.

A: Write an User-Defined Type Guard:
function isCustomError(x: any): x is CustomError {
    return x.constructor === CustomError;
}

And use it:
if (isCustomError(err)) {
    err.customMethod1();
}

See this playground.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL , INSERT with SELECT I'm trying to INSERT new row with this values (hotelNo,guestNo,dataform,dataTo,roomNo)
I know the hotel name , so I have to SELECT the hotelNo from another table , it didn't work with me , is there something wrong?
INSERT INTO Booking
VALUES (hotelNo,123,'3-sept-1014','3-sept-1014',121)
(SELECT hotelNo
 FROM Hotel
 WHERE hotelName='Ritz Carlton' AND city='Dubai');

A: Remove VALUES (hotelNo,... from your query and you are good to go.
INSERT INTO Booking
(SELECT hotelNo,123,'3-sept-1014','3-sept-1014',121
 FROM Hotel
 WHERE hotelName='Ritz Carlton' AND city='Dubai')

A: You should do it without VALUES
INSERT INTO Booking
(SELECT hotelNo, 123, '3-sept-1014','3-sept-1014',121
 FROM Hotel
 WHERE hotelName='Ritz Carlton' AND city='Dubai');

A: Try this:
INSERT INTO Booking VALUES (
(SELECT hotelNo
FROM Hotel
WHERE hotelName='Ritz Carlton' AND city='Dubai'),
123,'3-sept-1014','3-sept-1014',121);


text:
Q: Why do I get "Expected catch() or return"-error when trying to connect to firestore via cloud-function? I use google cloud firestore with a certain amount of collections.
I am trying to write a google cloud function that returns the number of collections in this firestore upon http-request.
So I wrote the following index.js-file drawing from this question:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.queryForData = functions.https.onRequest((request, response) => {
    var db = admin.firestore();
    db.get().then(snap => {
        response.status(200).send({length: snap.size});
        })
    });

After deploying, I get this error:

The strange thing is: When I delete the line var db = admin.firestore(); I get the very same error. So I suspect, that I am not correctly connecting to firestore at all.
What am I doing wrong?

A: As explained on the official video on HTTP Cloud Function, you should add a catch() block to your Cloud Function, as follows:
exports.queryForData = functions.https.onRequest((request, response) => {
    var db = admin.firestore();
    db.get()
    .then(snap => {
       response.status(200).send({length: snap.size});
       //Or response.send({length: snap.size});
    })
    .catch(error => {
       console.log(error);
       response.status(500).send(error);
    })
});

But, in addition, if I am not mistaken, there is (another) error in your Cloud Function: you do db.get() but there is not get() method for the Firestore service interface. You should call the get() method on a CollectionReference, since you are using the size() method on the returned QuerySnapshot (i.e. snap):
exports.queryForData = functions.https.onRequest((request, response) => {
    var db = admin.firestore();
    db.collection('collectionId').get()
    .then(snap => {
       response.status(200).send({length: snap.size});
       //Or response.send({length: snap.size});
    })
    .catch(error => {
       console.log(error);
       response.status(500).send(error);
    })
});

Note that you could also call get() on a DocumentReference.

A: You need to return a value after thePromise finishes, in your case you can do the following:
exports.queryForData = functions.https.onRequest((request, response) => {
var db = admin.firestore();
return db.get().then(snap => {
     response.status(200).send({length: snap.size});
    })
});

A: The call to Firestore is asynchronous and you must make sure that you are managing the lifecycle of your cloud function for that.
The documentation states the following

*

*Resolve functions that perform asynchronous processing (also known as
  "background functions") by returning a JavaScript promise.

*Terminate HTTP functions with res.redirect(), res.send(), or res.end().

*Terminate a synchronous function with a return; statement.

You can fix this by simply adding a return statement to your db.get(). And also, to get rid of your lint error, you should return a value from inside your handler. You can either return null or just return the response.send()
By omitting a return statement, it will implicitly resolve to undefined ... which probably why you get the warning.
exports.queryForData = functions.https.onRequest((request, response) => {
    var db = admin.firestore();
    return db.get().then(snap => {
        response.status(200).send({length: snap.size});
        return null;
        })
    });

The returned promise from db.get() will ensure that the function stays alive until your HTTP response has been sent and also terminates the function after the promise is resolved.
By not finalizing your functions properly, they might run until they timeout. See this video: https://youtu.be/xu5A1seU6PU?t=233


text:
Q: Angular2 - What is the best practice to notify a directive when a component is updated? I have a tooltip directive thar uses a component as its template. While creating the component dynamicly, the tooltip DOM element is not ready yet with its innerHtml. The component will get its real width for example only after ngAfterViewInit event.
But the directive don't know when the component template has completed rendering. Can I watch the private argument of a component (from directive) and know when its being changed/updated?
tootlipComponentTemplate
@Component({
  selector: 'tooltip-container',
  template: `<div #tooltipContent  [innerHTML]="htmlStr"></div>`
})
export class TooltipContainer implements AfterViewInit {

  @ViewChild('tooltipContent') elementRef: ElementRef;

  width: number;
  htmlStr: string;

  constructor() {}

  ngAfterViewInit() { // this is the place when I really getting the tooltip width
    console.log("ngAfterViewInit: " + this.elementRef.nativeElement.offsetWidth);
    this.width = this.elementRef.nativeElement.offsetWidth;
  }

}

tooltipDirective
@Directive({
  selector: '[myTooltip]'
})
export class myTooltipDirective {

  private tooltip: ComponentRef<TooltipContainer>;
  private innerHtml: string;

  @HostListener("mouseenter", ['$event'])
  show(event:MouseEvent): void {

    // .. creating the tooltip with factory ..

    console.log(this.tooltip.instance.width); // its undefined at this point !!! //

  }

  constructor() {}

}

HTML

text with tooltip on mouseOver

A: You can add an @Output() to your directive to notify the host component
export class TooltipContainer implements AfterViewInit {

  @Output()
  domReady:EventEmitter = new EventEmitter();
  @ViewChild('tooltipContent') elementRef: ElementRef;

  ngAfterViewInit() { // this is the place when I really getting the tooltip width
    console.log("ngAfterViewInit: " + this.elementRef.nativeElement.offsetWidth);
    this.width = this.elementRef.nativeElement.offsetWidth;
    this.domReady.next(null);
  }

text with tooltip on mouseOver


text:
Q: Using the exchange lemma for proofs I recently learned about the exchange lemma (which is an extremely difficult concept to understand, in my opinion), and I'm trying to do a couple of proofs:
Proof 1: Suppose $V$ is a n-dimensional vector space over $F$ and $S \subset V$ is a finite subset.
Use the Exchange Lemma to prove that if $|S| < n$, then $S$ is not a spanning set.
Proof 2: Suppose $V$ is a n-dimensional vector space over $F$ and $S \subset V$ is a finite subset. Use
the Exchange Lemma to prove that if $|S| > n$, then $S$ is linearly dependent.
My attempts:
Proof 1: Suppose $V$ has a basis $G = \{v_1, ... , v_n\}$ and S contains vectors $u_1, ... , u_m$ s.t. $m < n$. It follows that since $|S|$ = $m < n$,
$$|S| < dim(V)$$
Hence, $S$ is not a spanning set.
Proof 2: Again, suppose $V$ has a basis $G = \{v_1, ... , v_n\}$ and S contains vectors $u_1, ... , u_m$. This time, however, $n < m$. By linear independence of bases:
$$a_1v_1 + ... + a_nv_n = 0 \implies a_1 = ... = a_n = 0$$
Since $|S| = m > n$,
$$b_1u_1 + ... + b_mu_m = 0 \implies b_1u_1 + ... + b_nu_n + ... + b_mu_m = 0$$
$\implies$ $u_i$ for $i = n+1 ... m$ are redundant.
Thus, $S$ is linearly dependent.
I'm pretty sure these proofs are way off and don't even use the exchange lemma (can't figure out how to utilize the lemma) but any assistance or corrections are much appreciated.


text:
Q: Add single unit of time to timestamp for use in Blackberry application How can I add a single unit of time to timestamp, just like "add method" of Java "Calendar" class but by using Blackberry API set
Can anyone please help me with source code?

A: You still can use Calendar in BlackBerry:
class Scr extends MainScreen {
    public Scr() {
        Date date = new Date(System.currentTimeMillis());
        add(new LabelField("now:"));
        add(new LabelField(date.toString()));
        add(new LabelField("past month:"));
        add(new LabelField(addDateTime(date, Calendar.MONTH, 1).toString()));
    }

    public Date addDateTime(Date date, int field, int addValue) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int value = c.get(field);
        c.set(field, value + addValue);
        return c.getTime();
    }
}


text:
Q: React build fetch requests failing Mine react apps fetch requests work fine when I test in dev environment (npm start) but after creating a build package (npm run build) and then running that, all my fetch requests receive a failed status when making requests to my locally hosted API. Could this be because my API is not https? Any other ideas?
Thanks

A: Double check if you have the REACT_APP_API_URL on your .env files:

*

*.env (it should be localhost)

*.env.production (this is used on build, it should be production URL)

A: Try adding a proxy field in the package.json of your react app. Once that is in place, run build and test. This usually solves the api issue that react can have with api.
package.json: proxy: "http://localhost:8000"
requests in React app: fetch('/api/urls/....')


text:
Q: Eliminar con un botón dos tablas relacionadas en LARAVEL Tengo tabla Producto y tabla Imagen. Necesito eliminar con un solo botón los dos registros. Producto es la tabla padre, imagen la tabla hija que tiene la fk de tabla producto.
La función en el controlador estoy enviando así (se que no está bien). ¿Cómo puedo hacerlo?
public function destroy($id)
    {
        $result = Producto::find($id);
        $result->delete();

        $resultImagen = Imagen::find($id);
        $resultImagen->idProducto = $result->id_producto;
        $resultImagen->delete();

        return redirect('/productos')->with('success', 'Stock has been deleted Successfully');
    }

A: Como dice Fly tienes que borrar el hijo y después el padre.
public function destroy($id)
{
    // buscas el padre
    $result = Producto::find($id);

    // buscas el hijo y lo borras
    $resultImagen = Imagen::find($result->id_producto);
    $resultImagen->delete();

    // borrar el padre
    $result->delete();

    return redirect('/productos')->with('success', 'Stock has been deleted Successfully');
}


text:
Q: How to confirm the Widget Order in Qt Creator? I've just defined the order in which I want my widgets on a Qt GUI but I can't confirm my action after hours of researches. How can I do it please ?
Here is the order I defined :

I would like the widgets to be in this order : 1 - 2 - 3
But here, there are in that order : 3 - 2 - 1
I tried to build the project to see if something different happens but it just builds exactly what I see on Qt Creator :

I read the tutorial below but there's no information about my problem : https://doc.qt.io/archives/4.3/designer-tab-order.html#:~:text=Setting%20the%20Tab%20Order,position%20in%20the%20tab%20order.
Btw, I don't understand why it's that complicated to do such a simple thing. It's crazy that just pressing the Enter key doesn't do the trick.

A: I found what I needed. To re-order widgets, we just have to move them manually with the mouse.


text:
Q: Copyleft Licenses - Need to attribute? I'm currently evaluating which license to use for my next OS project, and things are getting more and more interesting after I decided that I really want to understand what the licenses mean.
Up until now, I just licensed everything under MIT because I like the MIT and their license is nice and short. And probably because it didn't really matter as only a hand full of people actually used my products.
But now, I'm at the brink of releasing something that will surely be used by many people and also be subject to major modifications, so I want to choose the right license to go with.
From what I understand, there are two groups of licenses; Copyright and Copyleft. Now, I read (and think to understand) MIT and BSD-2/3-Clause, but I'm really having trouble to get the gist of (L)GPL and alike.
My main problem is; I want to always be named in derivative works of my project. I don't really care if it's used proprietary or free, I just want to make sure that anyone who reads the code sees "ah, that's the original author" (referring to me).
Is there a clause in the copyleft licenses that assures this attribution? Or can this only be done using permissive copyright ones?

A: You need to remember the different between copyright and the license. If you write the code, you can always be named in the source files as the copyright holder, regardless of the license. If that is your only requirement, any license will do, it's choice has no bearing on that requirement.
The only slight clarification is that some licenses, like the BSD, forbid removal of the copyright sections. You might use that since it does state your requirement explicitly.
The thing with the GPL, is only use it because you understand the ethics of free software. Using the GPL is an ethical statement, rather than a means to make your software more popular.
Edit: The GPL is not an "open source" license, there's an important difference between open and free, it's not mere semantics. Preventing inclusion in a larger proprietary piece of software isn't primarily intended as a tool for competitive advantage, it's intended as a means to stop the proprietary software using the GPL software and not affording the freedoms that the GPL provides.


text:
Q: Why is curl giving 403 error from inside AWS EC2? I have an AWS EC2 instance running Ubuntu.  Inside this instance, it is running vcpkg, which is attempting to download from Sourceforge at some point during its compilation process.  I am consistently getting 403 errors when these instances attempt to use curl to download from Sourceforge.
The EC2 instances are private, but they have Internet access and are able to perform other actions such as cloning from Github.
The errors I am seeing look like this:
[DEBUG] 80289: popen(curl --fail -L https://sourceforge.net/projects/libuuid//files/libuuid-1.0.3.tar.gz/download --create-dirs --output /builds/vcpkg/downloads/libuuid-1.0.3.tar.gz.80289.part 2>&1)
[DEBUG] 80289: cmd_execute_and_stream_data() returned 22 after   155521 us
[DEBUG] 80289: popen(curl --fail -L https://sourceforge.net/projects/libuuid//files/libuuid-1.0.3.tar.gz/download?use_mirror=cfhcable --create-dirs --output /builds/vcpkg/downloads/libuuid-1.0.3.tar.gz.80289.part 2>&1)
[DEBUG] 80289: cmd_execute_and_stream_data() returned 22 after   157359 us
[DEBUG] 80289: popen(curl --fail -L https://sourceforge.net/projects/libuuid//files/libuuid-1.0.3.tar.gz/download?use_mirror=pilotfiber --create-dirs --output /builds/vcpkg/downloads/libuuid-1.0.3.tar.gz.80289.part 2>&1)
[DEBUG] 80289: cmd_execute_and_stream_data() returned 22 after   156247 us

[many more lines here...]

https://sourceforge.net/projects/libuuid//files/libuuid-1.0.3.tar.gz/download:   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (22) The requested URL returned error: 403

https://sourceforge.net/projects/libuuid//files/libuuid-1.0.3.tar.gz/download?use_mirror=cfhcable:   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (22) The requested URL returned error: 403

https://sourceforge.net/projects/libuuid//files/libuuid-1.0.3.tar.gz/download?use_mirror=pilotfiber:   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (22) The requested URL returned error: 403

However, when this same script attempts to download CMake, there are no issues.  (Though it appears this is being done through another mechanism vs. command-line curl.)
A suitable version of cmake was not found (required v3.22.2). Downloading portable cmake v3.22.2...
Downloading cmake...
  https://github.com/Kitware/CMake/releases/download/v3.22.2/cmake-3.22.2-linux-x86_64.tar.gz -> /builds/vcpkg/downloads/cmake-3.22.2linux-x86_64.tar.gz
Extracting cmake...

Since I am only seeing this in my EC2 instances and not on local machines running the same commands, I am wondering if there is something I can configure on the AWS side to resolve this?  Inbound or Outbound Security Group rules that need to be applied?  Or am I going in the wrong direction here with my debugging?
(I don't think this is important, but these specific errors were generated by attempting to build activemq-cpp with vcpkg using the x64-linux triplet.  I get these same types of errors with some other libraries as well inside EC2.)


text:
Q: Why does Math.Pow(x,y) using double instead of long? We need to use long and Long.toUnsignedString() as type for the rice but Math.Power is changing it to double:
package com.company;

public class Main {

    public static void main(String[] args) {
        int rk = 0;

        for (byte feld = 1; feld < 65; feld++) {
            System.out.println("Feld: " + feld + ", Reiskörner: " + Math.pow(2, rk));
            rk = rk+1;
        }
    }
}

I tested many things but nothing worked.
The Output is:
Feld: 1, Reiskörner: 1.0
Feld: 2, Reiskörner: 2.0
Feld: 3, Reiskörner: 4.0
...
Feld: 63, Reiskörner: 4.6116860184273879E18
Feld: 64, Reiskörner: 9.223372036854776E18

insted of:
Feld: 1, Reiskörner: 1
Feld: 2, Reiskörner: 2
...

A: You can easily cast back to long:
System.out.println("Feld: " + feld + ", Reiskörner: " + (long) Math.pow(2, rk));

But you should note that Math.pow(2,63) is too large to fit in a long variable.
The max long value is 263-1.
You can also avoid Math.pow() if you use the shift operator:
System.out.println("Feld: " + feld + ", Reiskörner: " + Long.toUnsignedString ((1L << rk)));

Note that I used Long.toUnsignedString in order to correctly print 263.

A: It is inefficient to call Math.pow() so many times in a loop when all you need to do is multiply by two each time:
public static void main(String[] args) {
    long rk = 1;

    for (byte feld = 1; feld < 65; feld++) {
        System.out.println("Feld: " + feld + ", Reiskörner: " + Long.toUnsignedString(rk));
        rk *= 2;
    }
}

This also works with long negative numbers (printed as unsigned), such as you get when the result is too large to fit in a signed long, because the multiplication works as expected, unlike casting from a double.


text:
Q: I need to be able to 'rotate' a list thats in a 'square' looking formation into a diamond shape python I am creating a word search solver and need a way to rotate the word search, which is in a list, so the left corner is the 'top' and the bottom right is at the 'bottom'
I have this:
 Puzzle = ["FUNCTIONRRIRAI",
              "RAIOONFRCCPWON",
              "PTCSNOBEUITOLO",
              "BNCACIANTOSLIH",
              "RBYOLILYNREFBT",
              "HYYNOGESTIBRIY",
              "AATTSIONCMCENP",
              "UORTENRRCBFVAU",
              "CEBEECVWIERORI",
              "PROCESSORTOPYF",
              "OHCOMPUTERHSOS",
              "YCYPRESREOSMRW",
              "OATHBRMVTHHCTR",
              "PGORWOOUIPSCHP"]

I need it in the formation of:
Puzzle = ["F","RU","PAN","BTIC",...]

so it appears that the word search has been rotated 45 degrees
any suggestions/help would be appreciated
Code for find_horizontal and words to find:
def load_words_to_find(file_name):
    word_list = []
    file = open(file_name, "r")
    for line in file.readlines():
        word_list.append(line)
    word_list = list(map(lambda s: s.strip(), word_list))
    return word_list

def find_horizontal(Puzzle, Words, ReplaceWith, Found):
    # Parameters :- List:Puzzle, List:Words, Character:ReplaceWith, List:Found
    # Return :- List:Outpuz, List:Found
    # Find all words which are horizontally in place (left to right and right to left), return the puzzle and list of found words
    rev = ''
    Outpuz = Puzzle

    for line in Puzzle:
        rev = line[::-1]

        for word in Words:

            if word in line:
                Found.append(word)
                Puzzle[Puzzle.index(line)] = line.replace(word, ReplaceWith * len(word))
            if word in rev:
                Found.append(word)
                Puzzle[Puzzle.index(line)] = line.replace(word[::-1], ReplaceWith * len(word))
            else:
                pass

    print("Found: ", Found)
    print(Outpuz)

    return Outpuz, Found

find_horizontal(Puzzle, load_words_to_find("words.txt"), ".", [])

A: Kind of silly, but you could insert string iterators to the front of a list, and then join and yield the next character from each iterator.
rows = [
    "FUNCTIONRRIRAI",
    "RAIOONFRCCPWON",
    "PTCSNOBEUITOLO",
    "BNCACIANTOSLIH",
    "RBYOLILYNREFBT",
    "HYYNOGESTIBRIY",
    "AATTSIONCMCENP",
    "UORTENRRCBFVAU",
    "CEBEECVWIERORI",
    "PROCESSORTOPYF",
    "OHCOMPUTERHSOS",
    "YCYPRESREOSMRW",
    "OATHBRMVTHHCTR",
    "PGORWOOUIPSCHP"
]

def get_next_diagonal(rows):

    iters = []
    for row in rows:
        iters.insert(0, iter(row))
        yield "".join(next(it, "") for it in iters)
    while iters[0].__length_hint__():
        yield "".join(next(it, "") for it in iters)

for diagonal in get_next_diagonal(rows):
    print(diagonal)

Output:
F
RU
PAN
BTIC
RNCOT
HBCSOI
AYYANNO
UAYOCOFN
COTNLIBRR
PERTOIAECR
ORBTSGLNUCI
YHOEEIEYTIPR
OCCCENOSNOTWA
PAYOECRNTRSOOI
GTPMSVRCIELLN
OHRPSWCMBFIO
RBEUOIBCRBH
WRSTREFEIT
OMRETRVNY
OVEROOAP
UTOHPRU
IHSSYI
PHMOF
SCRS
CTW
HR
P

A: Apologies for the lack of efficiency, but here is my quick solution.
We view the grid as a set of coordinates. This solution is based off the fact that every item in the output you want will have X and Y coordinates than add up to a certain number. For example, the first item "F" has a location of (0,0), which sum to 0. The second two items "RU" are located ad (1,0) and (0,1), which both add up to 1. The third line "PAN" has letters located at (0,2), (1,1) and (2,0), and so on. Tracking this number with "i" in my solution, it needs to be big enough to scan down and across the lists, so this is twice the size of the length of the array. So we scan the list for items that are located at x and y coordinates where x+y==i.
Code:
Puzzle = ["FUNCTIONRRIRAI",
      "RAIOONFRCCPWON",
      "PTCSNOBEUITOLO",
      "BNCACIANTOSLIH",
      "RBYOLILYNREFBT",
      "HYYNOGESTIBRIY",
      "AATTSIONCMCENP",
      "UORTENRRCBFVAU",
      "CEBEECVWIERORI",
      "PROCESSORTOPYF",
      "OHCOMPUTERHSOS",
      "YCYPRESREOSMRW",
      "OATHBRMVTHHCTR",
      "PGORWOOUIPSCHP"]

output = []
i = 0
while i < len(Puzzle)*2:
    single_string = ""
    for y in range(0,len(Puzzle)):
        for x in range(0,len(Puzzle[0])):
            if (x + y) == i:
                single_string += Puzzle[x][y]
    if single_string != "":
        output.append(single_string)
    i += 1

print(output)

Outputs
['F',
 'RU',
 'PAN',
 'BTIC',
 'RNCOT',
 'HBCSOI',
 'AYYANNO',
 'UAYOCOFN',
 'COTNLIBRR',
 'PERTOIAECR',
 'ORBTSGLNUCI',
 'YHOEEIEYTIPR',
 'OCCCENOSNOTWA',
 'PAYOECRNTRSOOI',
 'GTPMSVRCIELLN',
 'OHRPSWCMBFIO',
 'RBEUOIBCRBH',
 'WRSTREFEIT',
 'OMRETRVNY',
 'OVEROOAP',
 'UTOHPRU',
 'IHSSYI',
 'PHMOF',
 'SCRS',
 'CTW',
 'HR',
 'P']

Hope this helps. Happy to clarify anything if needed

A: Variation on a theme - generate diagonal indices.
If you trace your finger down the left edge, those are the starting point for the top-half diagonals and tracing your finger across the bottom edge are starting points for the bottom-half diagonals.
Top Half:
From each diagonal's starting point the first dimension's indices range from the starting point to zero (negative steps) and the second dimension's indices range from zero to a maximum of the length of the second dimension (positive steps).
Bottom Half:
From each diagonal's starting point the first dimension's indices range from the length of the first dimension minus one to a minimum of zero (negative steps) and the second dimension's indices range from the starting point to a the length of the second dimension (positive steps).
For both sets of diagonals you can take advantage of the fact that zip will stop when the shortest iterable is exhausted.
def cw(dims,ragged=False):
    '''Generate indices for diagonals based on dims.

       dims --> tuple: (nrows,ncolumns)

       Currently only implemented for all rows have same number of columns
       Diagonals as if the rectangle was rotated CW 45 degrees
       bottom-left to upper-right
    '''
    if ragged: raise NotImplementedError
    nrows,ncolumns = dims
    # top half
    index1 = range(0,ncolumns)
    for i in range(nrows):
        yield zip(range(i,-1,-1),index1)
    # bottom half
    index0 = range(nrows-1,-1,-1)
    for i in range(1,nrows):
        yield zip(index0,range(i,ncolumns))

new = []
for diagonal in cw((len(Puzzle),len(Puzzle[0]))):
    new.append(''.join(Puzzle[j][k] for (j,k) in diagonal))

And a CCW rotation solution
def ccw(dims,ragged=False):
    '''Generate indices for diagonals based on dims.

       dims --> tuple: (nrows,ncolumns)

       Currently only implemented for all rows have same number of columns
       Diagonals as if the rectangle was rotated CCW 45 degrees
            top-left to bottom-right
    '''
    if ragged: raise NotImplementedError
    nrows,ncolumns = dims
    # top half
    index0 = range(0,nrows)
    for i in range(ncolumns,-1,-1):
        yield zip(index0,range(i,ncolumns))
    # bottom half
    index1 = range(0,ncolumns)
    for i in range(1,nrows):
        yield zip(range(i,nrows),index1,)

A: I find it easier and clearer to just generate the indexes in two loops, down the rows starting at the first column and then along the columns starting at the last row:
puzzle = ['FUNCTIONRRIRAI',
 'RAIOONFRCCPWON',
 'PTCSNOBEUITOLO',
 'BNCACIANTOSLIH',
 'RBYOLILYNREFBT',
 'HYYNOGESTIBRIY',
 'AATTSIONCMCENP',
 'UORTENRRCBFVAU',
 'CEBEECVWIERORI',
 'PROCESSORTOPYF',
 'OHCOMPUTERHSOS',
 'YCYPRESREOSMRW',
 'OATHBRMVTHHCTR',
 'PGORWOOUIPSCHP']

nrows = len(puzzle)
ncols = len(puzzle[0])
output = []
for ir in range(nrows):
    row = []
    ic = 0
    jr = ir
    while jr >= 0:
        row.append(puzzle[jr][ic])
        ic += 1
        jr -= 1
    output.append(''.join(row))
for ic in range(1, ncols):
    row = []
    ir = nrows - 1
    jc = ic
    while jc < ncols:
        row.append(puzzle[ir][jc])
        ir -= 1
        jc += 1
    output.append(''.join(row))

for row in output:
    print(row)

Output:
F
RU
PAN
BTIC
RNCOT
HBCSOI
AYYANNO
UAYOCOFN
COTNLIBRR
PERTOIAECR
ORBTSGLNUCI
YHOEEIEYTIPR
OCCCENOSNOTWA
PAYOECRNTRSOOI
GTPMSVRCIELLN
OHRPSWCMBFIO
RBEUOIBCRBH
WRSTREFEIT
OMRETRVNY
OVEROOAP
UTOHPRU
IHSSYI
PHMOF
SCRS
CTW
HR
P


text:
Q: How did the rule of addition come to be and why does it give the correct answer when compared empirically? I'm still a high school student and very interested in maths but none of my school books describe these kind of things, and only say how to do it not the whys. My question is very simple, for example:
        19
       +25
      = 44

because the one from adding 9 and 5 goes on to add with 1 and two. How did this rule of addition come to be?
Here's a bit of explanation that can be useful(sorry if it is frustrating):
Suppose we are a 3 year old child and no one teaches us how to add and we recognize 1 is our index and 5 all palm fingers held up. Someone gives us the problem add: 1+5 so we hold 'em up, right? and again someone gives us to add 8564+2345 so we can't lift 'em up. So we try to device a rule but we don't recognize 6+4= 10 in which 0 stays and one jumps neither can we say that only the digits from rightmost positions are to be added. This is what i meant.

A: Here's a sketch of the general theory.
Theorem: Let $b$ be an integer greater than $1$. For every positive integer $N$, there exist

*

*A non-negative integer $n$,

*Integers $a_{n}$, $a_{n-1}$, ..., $a_{2}$, $a_{1}$, $a_{0}$ satisfying $0 \leq a_{k} < b$, and $0 < a_{n}$,
such that
$$
N = a_{n} b^{n} + a_{n-1} b^{n-1} + \dots + a_{1} b + a_{0}
  = \sum_{k=0}^{n} a_{k} b^{k}.
\tag{1}
$$
Moreover, the representation (1) is unique (can be done in precisely one way).
Definition: The integers $(a_{k})_{k=0}^{n}$ are called the (base $b$) digits of $N$. The string of symbols
$$
a_{n}\, a_{n-1} \cdots a_{2}\, a_{1}\, a_{0}
$$
is called the base-$b$ representation of $N$.
The process of carrying arises naturally when you ask how to find the base-$b$ representation of a sum $N + N'$ from the base-$b$ representations of the summands $N$ and $N'$. If
\begin{alignat*}{5}
N &= a_{n} b^{n} &&+ a_{n-1} b^{n-1} &&+ \dots &&+ a_{1} b &&+ a_{0}
  &&= \sum_{k=0}^{n} a_{k} b^{k}, \\
N' &= a_{n}' b^{n} &&+ a_{n-1}' b^{n-1} &&+ \dots &&+ a_{1}' b &&+ a_{0}'
  &&= \sum_{k=0}^{n} a_{k}' b^{k},
\end{alignat*}
then
$$
N + N' = (a_{n} + a_{n}') b^{n} + (a_{n-1} + a_{n-1}') b^{n-1} + \dots + (a_{1} + a_{1}') b + (a_{0} + a_{0}')
  = \sum_{k=0}^{n} (a_{k} + a_{k}') b^{k}.
\tag{2}
$$
If every "coefficient" $a_{k} + a_{k}'$ is smaller than $b$, then (2) immediately gives the base-$b$ representation of $N + N'$ by stringing the coefficients. The snag is, one or more coefficients $a_{k} + a_{k}'$ might be greater than or equal to $b$. In the sum $19 + 25$, for example, the "ones place" $9 + 5$ cannot be represented by a single digit. Instead, we write $9 + 5 = 14 = 10 + 4$; the $4$ stays in the ones place, but the extra $10$ carries to the tens place. Since $10$ units of one is a single unit of ten, we add one to the tens place to accommodate the carry. (The equation $9 + 5 = 14$ itself is a special case.)
Generally, if $b \leq a_{k} + a_{k}'$, write
$$
(a_{k} + a_{k}') b^{k}
  = \bigl[b + (a_{k} + a_{k}' - b)\bigr] b^{k}
  = b^{k+1} + (a_{k} + a_{k}' - b) b^{k}.
\tag{3}
$$
Each of $a_{k}$ and $a_{k}'$ is less than $b$, so $0 \leq a_{k} + a_{k}' - b < b$. In words, $a_{k} + a_{k}' - b$ is a base-$b$ digit. Equation (3) therefore determines the carrying rule: Add the $b^{k}$ coefficients, $a_{k} + a_{k}'$. If the sum of the coefficients is greater than or equal to $b$, subtract $b$ from their sum (obtaining a proper base-$b$ digit) and add $1$ (i.e., $b$ units of $b^{k}$) to the $b^{k+1}$ coefficient, the next column to the left.
To get a clean algorithm for addition, start at the rightmost digit and work leftward, carrying as necessary. (Carrying only affects digits farther to the left. For example, a carry in the hundreds place has no effect on the tens and ones.)

A: Well essentially what you're doing is this:
$$19+25 = (10 + 9) + (20 + 5) = \underbrace{(9 + 5)}_{\text{ones}} + \underbrace{(10 + 20)}_{\text{tens}}$$
Then you'll get:
$$14 + (10 + 20)$$
So for the ones digit you get $4$ so let's subtract that from $14$ to get $10$. For the tens digit, since you still have $10$ left over from adding the ones digits you have to "carry over" $10$ into $(10+20)$:
$$10\,\text{(carried over digit)}+(10+20) = 20+20 = 40$$
Adding the result from the ones digit gives:
$$40 + 4 = 44$$
The "rule" of carrying over from one place value into another is just that, except that you do it vertically.

A: What's the meaning of $19$ ? Obviously not $1+9$, but $10+9$, because the first digit "weights" $10$. Similarly, $25$ is $20+5$. The $2$ is worth $20=2\times10$. Another digit on the left would weight $100$, like $625=6\times100+2\times10+5$.
Now how do we add two decimal numbers ?
$$19+25=(1\times10+9)+(2\times10+5)$$
We can regroup $(1+2)\times 10+(9+5)=3\times10+14$. Fine for the first digit, but no so for the units: $14$ isn't a single digit. To workaround, we decompose $14=1\times10+4$.
Now, $$19+25=(1+2+1)\times10+(4)=44.$$
You can easily generalize and imagine the graphical layout that makes this process well-organized.

A: The reason that this rule of addition came to be is that people count to 10 with their fingers.  Other number systems have developed in other cultures, such as counting by 5's on one hand, or counting to 60 by 5 subgroups of the sub-digits on the other hand.  Computers only use '0' and '1' for positive voltage and negative voltage.  Some people are also trying to get people to start using base 12 since it has many factors for how small of a number it is.  Base 10 is just a standard.
Standard numbers are represented in the form:
number = place_valebase^1st_digit_value + place_valebase^2nd_digit_value + place_vale*base^3nd_digit_value+...
Where:
0 <= place_value < base
And "place_value", "base", and "nth_digit_value"'s are integer values.  These last two statements are important since it means that for any digit space there is some symbol representing the maximum integer value of that digit space, and there is a minimum of 0 (or any appropriate symbol) for that digit space.
There needs to be a system that expresses numbers greater than 9 and less than 0 in the number system, as well as decimal values.  The problem is that if we just changed the base, we would need a symbol for every number organized in such a way that each number could be identified upon sight without being seen before.
That won't work.  Which is why we have digit spaces.
Each digit space is an improvement upon each previous digit space so that it can pick up the pace where the last digit space left off, so 9+1=10 in base 10, as well as 1+1=10 in base 2, F+1=10 in base 16, etc.  The digit system in place allows the next digit to represent numbers that aren't in the same set as the first digit so that we don't waste symbols representing multiple numbers more than once.
Except for leading zeroes, which is why there are number systems like this:
https://en.wikipedia.org/wiki/Gray_code.  Gray still has overlapping numbers with different numbers of digits, but this is an example to show that writing out numbers can be done in many ways.
Speaking of which...
Even though the standard for decimal mathematics is to use big endian notation (where the digit representing the greatest value comes first), it can be useful to write out numbers in little endian notation (where the digit representing the smallest value comes first).  Example:
Big endian notation:
 52
+29
=81

Little endian notation:
 25
+92
=18

Little endian notation can be especially useful for serial transmissions between computers since addition of the first part of the number can cause the carry and the sum can be computed progressively while the message is received, instead of all at once if the message is received in big endian notation.
There are also mathematical notations such as postfix notation, which I am a fan of since it abolishes the counter-intuitive and perfectly-useless order of operations as well as frees up the parentheses symbols for other uses.
Or you can just start writing numbers vertically and see how that goes ;)
As for WHY addition is necessary: it's not.  Binary and computers don't actually do addition; it's just a series of logic operations on input values, which could also be mapped into the decimal system as well with some extra effort.  Addition is just a function resulting in a value.
Consider the equality:
a+b=c+d
There is no such thing as natural equivalence; it has been defined by humans as a way to recognize when two functional outputs give the same result.  This is just a way to say 'map the addition of a and b to the addition of c and d, and vice-versa', AKA
+(a,b)<->+(c,d)
I think I'm done now that I've obliterated mathematical notation and the idea of equivalence altogether.  If you have any remaining questions or feel that this explanation is incomplete, don't hesitate to notify me :)

A: It's not that carrying is a rule, but more that it's a natural result of addition within a number system.
Adding two numbers is a natural process. If I have a big group of things, and I add another big group of things, then I have added the two groups together. When it's with things (rather than tracking the number of them in your head), there's no need to perform any carrying over because the things are simply there. If I want to know the number of them, I can count them.
However, we represent numbers within a base (let's assume we're using base 10 for the moment). A single digit decimal number can only represent 0-9, so even when we're counting (adding 1 at a time) we have to carry to count to 10. That is, when a digit is at the highest value within the base but you still have more to add, you need to use the next digit higher digit. In base 10, to add 1 to 9 I reach 10, effectively having carried the 1.
The necessity of carrying is slightly more apparent with lower bases. For example, in binary (base 2), each digit can be 0 or 1. Instead of decimal where you have a digit for ones, tens, hundreds, etc., in binary you have a digit for ones, twos, fours, eights, etc.
The decimal number 7 is represented in binary as
111

(that's 1*1+1*2+1*4)
If we want to add 1 (binary 1) to 7 (binary 111), we get 8 (binary 1000). It looks like this:
   111
+  001
= 1000

You'll see that, because we're adding to a digit which is already at its maximum value, it carries to the next higher digit. In this case, because each higher digit is also maxed out, it continues carrying up until it reaches an empty digit.

The reason carrying is so explicit in addition is because, with the technique you showed, it's easy to add any numbers. By writing the numbers this way, adding arbitrarily large numbers becomes as easy as adding two 1-digit numbers several times over. 88010343 + 69139740 becomes:
  8|8|0|1|0|3|4|3
+ 6|9|1|3|9|7|4|0

It's only slightly more complicated because these aren't independent operations; we carry up to the next digit as we go along because it's easy to do in-place, rather than having to make a note and do it later (e.g. the millions digit had a result of 17, so once I'm done I'll add 10 million).

A: Suppose you have no money in your pocket, but you remember that
last week you lent Alice $19$ pounds and you lent Bob $25$ pounds.
So you find Alice and Bob and collect the money that they owe you.
But Alice and Bob have only some ten-pound notes and one-pound coins
in their pockets, so they pay you as follows:

*

*Alice: $1$ ten-pound note, $9$ one-pound coins.

*Bob: $2$ ten-pound notes, $5$ one-pound coins.

Now you have $3$ ten-pound notes and $14$ one-pound coins.
How much money do you have?
You don't like carrying around so many coins (they're heavy),
so you go to your bank, give the teller $10$ of your one-pound coins,
and receive back a single ten-pound note. This is a fair exchange, isn't it?
You neither lost nor gained money by this exchange.
You now have $4$ ten-pound notes. You also have $4$ one-pound coins
left after giving $10$ of the original $14$ to the bank.
Is it clear that you have $44$ pounds after adding the $25$ pounds from Bob
to the $19$ pounds from Alice?
When you are adding up numbers in the usual notation
(base-ten place-value numbers),
the "carry" operation is just like going to the bank to exchange
a number of one-pound coins for a smaller number of ten-pound notes.
The main difference is,
when doing arithmetic with base-ten place-value numbers,
you have to do this, because your "pocket" only has enough "room"
for at most nine coins of notes of any particular denomination;
that is, the only way you can write a number in the standard format
is to write down the number of "ones",
then the number of "tens" to the left of that,
then the number of "hundreds" to the left of that, etc.,
and you have only the digits $0$ through $9$ to say how many ones,
how many tens, and so forth.

A:
How did this rule of addition come to be?

From abacus.

A: It's simple.
Say you're working in a certain column.
(It doesn't matter which column .. the first one, fourth column .. whatever.)
Say you get to "ten" in that column.  Well, that's the same as a "1" in the next column!
It's just that simple.  Each "ten" in "that" column is like a "1" in the "next" column.
In fact, you COULD just write a "ten" in that column, if you wanted (!)
So, eight thousand .. 8-0-0-0 ... you could write as 7-ten-0-0 if you wanted .. see ?!!
7-ten-0-0 would mean "seven thousands", "ten hundreds" (which is of course just a thousand) and zero tens and ones.
Of course, the ten in that column is just worth a 1 in the next column!  7 plus 1 is 8, so we just write 7-0-0-0.
Enjoy.

A: This is something that comes from the way we represent numbers with symbols. I'll simplify your example a bit for explanation purposes
     9
   + 3
  = 12

Let's say you have 9 apples in a box. You need to write down how many apples are in the box for when you go to sell them. Now imagine that there is no such thing as letters or numbers than how do you do it?
The easiest way would be to make a line on the box for every apply in it. But then you would have to count the 9 lines instead of apples which gets you nowhere.
What if instead of making 9 separate lines, you grouped the lines together in groups of 5. There is still a little counting involved when reading the lines but it is much quicker.
So then to represent the addition problem it would look like
          ||||/  ||||
       +          |||
 =   ||||/  ||||/  ||

When we do the addition we would start with our 9 lines
||||/  ||||

And in order to add 3 lines we first have to complete our group of 5
||||/  ||||/

Then we "carry" over the last two lines to make 12
||||/  ||||/  ||

When working with numbers the same thing is happening only instead of making groups of 5 we make groups of 10 because we use the 10 symbols of 0-9 to represent our numbers as opposed to using a pattern of 5 lines.

A: We start by separating the ones and the tens:
$$19 + 25 = (10 + 9) + (20 + 5)$$
We will first add the ones, then the tens:
$$(9 + 5) + (10 + 20) = 14 + (10 + 20)$$
Now we extract the ones from 14, and pass along the ten:
$$14 + (10 + 20) = 4 + 10 + (10 + 20) = 4 + (10 + 10 + 20)$$
We can now add the tens:
$$4 + (10 + 10 + 20) = 4 + 40 = 44$$
Now try that for other sums, such as $29 + 43$ and $147 + 84$. In the last one, just separate the ones, the tens and the hundreds.

A: This method works even in mixed radix systems: Say you have $2$ yards, $2$ feet, and $9$ inches of rope, while your friend as $3$ yards, $1$ foot, and $7$ inches. How much do you have together? Well, $9$ inches plus $7$ inches is $16$ inches; but $12$ inches are a foot, so that's $1$ foot and $4$ inches. If we put aside the $4$ inches, we next have $2+1+1=4$ feet; but $3$ feet are a yard, so that's $1$ yard and $1$ foot. If we put aside the $1$ foot, we next have $2+3+1=6$ yards. So in total we have $6$ yards, $1$ foot, $4$ inches.
Of course, with our good old decimal number systems the addition rule becomes less complex as we always have the same ten smaller units in one bigger unit, but the idea behind it is the same. (You may think of counting/adding pebbles, where ten pebbles are bundles into bags, ten bags are bundles into boxes, ten boxes are stuffed into a trunk, and so on.

A: A visual representation:
  19
+ 25
= 44

Let's remove the answer and split the numbers into tens and units:
    10 + 9 {= 19}
+   20 + 5 {= 25}

This give us:
    30 + 14

We can make a new addition out of these numbers:
    14
+   30

Let's split these numbers into tens and units too:
    10 + 4 {= 14}
+   30 + 0 {= 30}

The 10 represents the 1 that was carried from the units column to the tens column. The second number, 30, must end in a zero because we only used digits from the tens column to calculate it. This means that at this stage we will never get a carry from the units column to the tens column, allowing us to progress past this stage, although for larger numbers we could get a carry from the tens column to the hundreds column (not shown). We can now complete the sum:
    10 + 4
+   30 + 0
=   40 + 4 {= 44}

This is why this method works. It is because breaking a number into parts (not digits, $10\ne1$) and adding all the parts up again will always give you the original number. $14=10+4=4+10=7+7=11+3=1+2+3+8$, etc. This is called associativity. When you carry the 1 from 14, you are actually carrying 10, but in the tens column you write 10 as 1.

A: Other people have done all the math-y specifications, and have done so spectactularly. From reading the comments, it seems as if the "why we have to carry exceeds over" hasn't been received by everyone yet. Let me try to explain that with an "analogy" (it's not really an analogy, but.. let's just go with it):
I assume you are familiar with the binary representation (or base-2).
In all numbersystems, there is a highest number any single-digit representation can contain. In base-2, that number is 1. In base-10, that number is 9.
This means that in base-2, it's not possible to represent the number 2 like 2 or 02 -- it has to be 10, because the value 2 is too high to be represented in the first single-digit position. Ergo, you must carry the exceed over to the next position.
Another way of looking at this is, again using base-2, each single-digit representation -- each position -- is a counting of how many of its corresponding values the number should specify, and each position can only correspond to one value. Let's take the base-2 number 10 and start reading from the right:
1st position: 0 -- how many ONEs do we have
2nd position: 1 -- how many TWOs do we have
Which of course corresponds to the number 2 in base-10.
Another number, 1011101 and its corresponding base-10 values:
1st position: 1 -- number of ONEs
2nd position: 0 -- number of TWOs
3rd position: 1 -- number of FOURs
4th position: 1 -- number of EIGHTs
5th position: 1 -- number of SIXTEENs
6th position: 0 -- number of THIRTYTWOs
7th position: 1 -- number of SIXTYFOURs
Counting it all up -- I don't speak latex, so I'm sorry for the formatting -- it becomes 64*1 + 32*0 + 16*1 + 8*1 + 4*1 + 2*0 + 1*1 = 93.
Carrying this logic over to base-10, where each position can hold {0, 9} and naturally cannot be double-digit:
1st position: number of ONEs
2nd position: number of TENs
3rd position: number of HUNDREDs
...
nth position: number of 10^(n-1)s
If we have the addition 8 + 4 = 12, and we weren't able to carry exceeds, the first position on the right-hand side would contain the double-digit number 12 (and the second position would contain 0), which is illegal. The first position can only contain the number of ones, and it is impossible in this representation to have more than nine ones. The moment you get 10 ONEs, you don't actually have 10 ONEs -- you have one TEN.
Thusly, we either carry the 1 (meaning one TEN in this example) over to the next position where it belongs (with the rest of the TENs), leaving 2 in the position for ONEs, giving us the number 1*10 + 2*1 = 12 -- or the numbersystem breaks down.
In the everyday, this representation is still used explicitly to some extent:
"One-thousand two-hundred" = 1200:
1st position: 0 -- number of ONEs
2nd position: 0 -- number of TENs
3rd position: 2 -- number of HUNDREDs
4th position: 1 -- number of THOUSANDs
Finally, imagine if you weren't able to carry exceeds: you have literally no way of knowing what any number you're presented with means. The number 1200 could mean "one-thousand two-hundred" or it could mean "one-thousand and twenty", or the number 10200 could mean "one-thousand two-hundred" or "ten-thousand twenty" or "one-thousand twenty", depending on how you align the addition.
Re: myself earlier, the numbersystem is 100% useless if you do not carry.

A: Every natural number $N$ in the decimal system is represented by $n + 1$ digits
$a_n \dots a_1a_0$
for which each stands for the number of powers of $10$ that add up to the given number.
$N = a_n\cdot 10^n + \dots + a_1 \cdot 10^1 + a_0 \cdot 10^0 $
Each digit $a_n$ has 10 possible "states" form $0$ to $9$ indicating how many of the powers contribute to $N$.
If you now add two numbers $A + B$
$A = a_n \cdot 10^n + \dots +a_1 \cdot 10 + a_0$
$B = b_n \cdot 10^n + \dots +b_1 \cdot 10 + b_0$
$A+B = (a_n + b_n) \cdot 10^n + \dots + (a_1 + b_1) \cdot 10 + (a_0+b_0)$
it can happen that these $(a_n + b_n)$ exceed the possible 10 "states" that are representable by 10 digits. Thus, we have to remove the exceed $c$ from $a_n + b_n$: $c = a_n + b_n - 10$ and add this exceed to the next higher power (and repeat if we get again another exceed).
Note that in other number systems (like hexadecimal) the procedure works the same except we have more (or less) states to represent with each digit.

A: All addition is based on a basic assumption about numbers that fit our observations of reality:  numbers are consistent.  5 is always going to be five.  If it's five on monday, then it's going to be five on tuesday.  And if we pick it up, get on an airplane and take it to France and turn it upside down it will still be 5.
So...
FACT 1: Numbers exist
FACT 2: a = a.  If b = a then a and b are the same number and if a and be are different numbers a $\ne$ b.
Now if we combine two numbers we will get a third and as numbers are consistent if we add the same two numbers we will always get the same third number.
So ...
FACT 3: Addition is a binary operation.  For any two numbers, a and b, we can add them together to get a + b = c,, a third number.
Now, again, numbers are consistent.  So it doesn't matter how we group the numbers when we add them or what order we add them in.  They will add to the same amount.
So...
FACT 4:  Addition is associative:  a + (b + c) = (a + b) +c
FACT 5: Addition is commutative: a + b = b + a.
Numbers are consistent so we can group them into bunches.  We can count these groups of numbers as though they were discrete objects.
FACT 6: A  multiplication exists for integers where  na = a + a + ... + a (a added n times).
And numbers are consistent, he says yet again for a final time, so no matter how you bunch them up the still add to the same number.
So
FACT 7:  Multiplication is distributive over addition: n(a + b) = na + nb.
And as long as those facts are observed .... addition works.  And we can do addition by observing those facts.
So now the real question is how do we represent numbers and he do the representations allow as to add?
We could do what the romans did and use seven symbols to represent values from 1 to 1000.
Then: XIX is two tens and a one but the one before the ten means it is one less: two tens less a one.  XXV is two tens and a five.
So XIX + XXV = (X + X -I) + (X + X +V) but we can ungroup these and move them around because addition is associative and commutative: X + X + X + X + V - I = (X + X + X + X) + (IV).  We have IV of those Xes  so we can group those: IV(X) + (IV) = V*X - I*X + (IV) = L - X + IV = XLIV.
Or we can do what no culture has ever done in the history of the world and write numbers by their prime factorization.
So $19 + 5^2$ is... well that's really hard.  We have to replace numbers with other numbers.  $19 = 2^2*5 - 1$ So $19 + 5^2 = (2^2*5 -1) + 5^2 = (2^2*5 + 5^2) - 1 = 5(2^2 + 5) - 1 = 5*(3^2) - 1 = (2^2 + 1)3^2 - 1 = (2^2*3^2) + (3^2 - 1) = 2^2*3^2 + 2^3 = 2^2(3^2 + 2) = 2^2*11$.  That was all substituting and grouping and substituting and regrouping.
$19 + 5^2 = 2^2*11$
Or we can use arabic decimal numbers where the number $abc = a*10^2 + b*10 + c$.
So $19 + 25$ can be spread out to $(1*10 + 9) + (2*10 + 5)$ which we can ungroup and shift around to get $1*10 + 2*10 + 9 + 5 = (1*10 + 2*10) + (9 + 5)$ which we can undistribute $(1 + 2)*10 + (14) = 3*10 + 14$ and spread out $3*10 + 10 + 4$ and regroup and rebunch $(3 + 1)*10 + 4 = 4*10 + 4$ and ... compress: $44$.
That's why addition works.

A: Though my answer is not quite what I want as well, this is what I could conclude seeing all the views here and it's not an algebric verification. If it will be possible I'll come back here and post an answer delving deeper into the history:


text:
Q: UWP - How to check NumLock and CapsLock status? How can check for CapsLock or NumLock status and see if they are enabled or disabled (on or off)? As far as I searched, I know only it's possible to check if they are pressed.

A: You can check it on your Page using:
var keystate = Window.Current.CoreWindow.GetKeyState(VirtualKey.NumberKeyLock);
var isNumLocked = (keystate & CoreVirtualKeyStates.Locked) != 0;


text:
Q: Trying to upload image but getting error <img th:src="@{resources\static\images\Desert.jpg}"  text**height="15%"width="15%"/>

I am trying to view an image on website but I'm getting an error. This is Thymeleaf.
Error on Google console:

GET http://localhost:8080/appstore/resources/static/images/Desert.jpg 404 (Not Found)

A: I'm assuming that the path is coming from database, If so then you can try this
code
 <img th:src="${eachObject.image}" width="50px" height="30px"/>

So eachObject is a list of object which you get while iterating.This should work fine.


text:
Q: PHP: Insert multiarray key into sub array key I have a miltidimentional array like this:
Array ( [11] => Array ( [0] => 5 )
        [12] => Array ( [0] => 7 )
        [14] => Array ( [0] => 9 [1] => 10 [2] => 11 [3] => 25 )
      )

And would like to convert it like that:
Array ( [0] => Array ( [11] => 5 )
        [1] => Array ( [12] => 7 )
        [2] => Array ( [14] => 9 )
        [3] => Array ( [14] => 10)
        [4] => Array ( [14] => 11)
        [5] => Array ( [14] => 25)
      )

Do you have any idea how it could be done?

A: Bare minimum:
foreach($myArray as $a => $b)
  foreach($b as $c)
    $tmpArray[] = array($a => $c);
$myArray = $tmpArray; unset($tmpArray);

Working Example

A:     <pre>
<?php

$arr = array();
$arr[11] = array(0, 1, 2);
$arr[12] = 3;
$arr[13] = array(4, 5);

print_r($arr);

$arr2 = array();

$x = 0;
$a = 0;

while ($x < 14) {// count() will fail with '3' but our numbers are at 11
    if (is_array($arr[$x])) {
        $p = 0;
        while ($p < count($arr[$x])) {// works here because index starts at 0
            if (!is_null($arr[$x]))  {
                $arr2[$a++] = $arr[$x][$p];
            }
            $p ++;
        }
    }
    else {
        if (!is_null($arr[$x])) {
            $arr2[$a++] = $arr[$x];
        }
    }

    $x ++;
}

print_r($arr2);
?>
</pre>

Result:
Array
(
    [11] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 2
        )

    [12] => 3
    [13] => Array
        (
            [0] => 4
            [1] => 5
        )

)
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)

im too tired so this is the max i can do now..
The problems:
while ($x < 14) {// count() will be '3' but our numbers are at 11

Maybe this code could be improved..


text:
Q: How can I get a footer with 2 contents 100% lenght of every monitor I wanted to create an footer to my project, but now i have the problem how to get the footer to the full size of the monitor. There I have my footer code and then my css.

.container {
    text-decoration: none;
    background-color: #333;
    float: left;
    display: block;
}

.container h1 {
    font-size: 18px;
    font-family:'Roboto Condensed', 'sans-serif';
    padding-left: 20px;
    padding-top: 20px;
    padding-bottom: 6px;
}

.container a {
    text-decoration: none;
    font-size: 16px;
    color: rgba(106,106,106,1.00);
    padding-left: 20px;
    padding-right: 20px;
}

.container a:hover {
    color: maroon;
}

Finanzdienstleistung

            Versicherungen

            Schadensabwickelung

Vermietung

            Freie Wohnungen

            Alle Wohnungen

A: You could turn them to display: table-cell instead of floats, to keep them in one row and filling the full width:

footer {
  display: table;
  width: 100%;
}

.container {
    text-decoration: none;
    background-color: #333;
    display: table-cell;
}

.container h1 {
    font-size: 18px;
    font-family:'Roboto Condensed', 'sans-serif';
    padding-left: 20px;
    padding-top: 20px;
    padding-bottom: 6px;
}

.container a {
    text-decoration: none;
    font-size: 16px;
    color: rgba(106,106,106,1.00);
    padding-left: 20px;
    padding-right: 20px;
}

.container a:hover {
    color: maroon;
}

Finanzdienstleistung

            Versicherungen

            Schadensabwickelung

Vermietung

            Freie Wohnungen

            Alle Wohnungen

A: Checkout the following. Just adding: width: 50% to container fixes it

.container {
    text-decoration: none;
    background-color: #333;
    float: left;
    display: block;
    width: 50%;
}

.container h1 {
    font-size: 18px;
    font-family:'Roboto Condensed', 'sans-serif';
    padding-left: 20px;
    padding-top: 20px;
    padding-bottom: 6px;
}

.container a {
    text-decoration: none;
    font-size: 16px;
    color: rgba(106,106,106,1.00);
    padding-left: 20px;
    padding-right: 20px;
}

.container a:hover {
    color: maroon;
}

Finanzdienstleistung

            Versicherungen

            Schadensabwickelung

Vermietung

            Freie Wohnungen

            Alle Wohnungen


text:
Q: how to use nginx as reverse proxy for cross domains I need to achieve below test case using nginx:
www.example.com/api/ should redirect to ABC.com/api,
while www.example.com/api/site/login should redirect to XYZ.com/api/site/login
But in the browser, user should only see www.example.com/api.... (and not the redirected URL).
Please let me know how this can be achieved.

A: The usage of ABC.com is forbidden by stackoverflow rules, so in example config I use domain names ABC.example.com and XYZ.example.com:
server {

    ...

    server_name www.example.com;

    ...

    location /api/ {
        proxy_set_header Host ABC.example.com;
        proxy_pass http://ABC.example.com;
    }

    location /api/site/login {
        proxy_set_header Host XYZ.example.com;
        proxy_pass http://XYZ.example.com;
    }

    ...

}

(replace http:// with https:// if needed)
The order of location directives is of no importance because, as the documentation states, the location with the longest matching prefix is selected.
With the proxy_set_header parameter, nginx will behave exactly in the way you need, and the user will see www.example.com/api... Otherwise, without this parameter, nginx will generate HTTP 301 redirection to ABC.example.com or XYZ.example.com.
You don't need to specify a URI in the proxy_pass parameter because, as the documentation states, if proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed.
You can specify your servers ABC.example.com and XYZ.example.com as domain names or as IP addresses. If you specify them as domain names, you need to specify the additional parameter resolver in your server config. You can use your local name server if you have one, or use something external like Google public DNS (8.8.8.8) or DNS provided for you by your ISP:
server {

    ...

    server_name www.example.com;
    resolver 8.8.8.8;

    ...

}

A: Try this:
location /api {
    proxy_pass http://proxiedsite.com/api;
}

When NGINX proxies a request, it sends the request to a specified
  proxied server, fetches the response, and sends it back to the client.
  It is possible to proxy requests to an HTTP server (another NGINX
  server or any other server) or a non-HTTP server (which can run an
  application developed with a specific framework, such as PHP or
  Python) using a specified protocol. Supported protocols include
  FastCGI, uwsgi, SCGI, and memcached.
To pass a request to an HTTP proxied server, the proxy_pass directive
  is specified inside a location.

Resource from NGINX Docs


text:
Q: MySQL ROUND and AVG not working as expected hi i am tying to use mysql ROUND and AVG functions ,
public function get_average_rating_by_specialty($shop_id,$where_array=array())
    {

        $this->replica->select('PreferenceToLOBID,PreferenceID , AVG(ROUND(AvarageRating)) as AvarageRating');
        $this->replica->from('*******');
        $this->replica->where(array('ShopID'=>$shop_id,'IsDelete'=>0));

        if($where_array)
        {
            $this->replica->where($where_array);
        }

        $this->replica->group_by('PreferenceID,PreferenceToLOBID');
        $result = $this->replica->get();

        return $result->result_array();
    }

here i m trying to get average values after round the AvarageRating value,
i have only one record that matches my conditions  in that row the AvarageRating value is 4.5
but the query result is
Array
(
    [0] => Array
        (
            [PreferenceToLOBID] => 29
            [PreferenceID] => 654
            [AvarageRating] => 4.0000
        )

)

when i remove ROUND this works correctly , but i want to round the AvarageRating values before get the average
in this case i expect 4.5 to be the result , why it's returning 4
please help , thanks in advance.

A: ROUND(AvarageRating,1)
then You can get desired 4,5

A: You're asking it to round 4.5 to 0 decimal places, and then average it.
See http://dev.mysql.com/doc/refman/5.1/en/mathematical-functions.html#function_round
WRT to whether the answer should be 4 or 5, pay special attention to this part of the docs:
"For approximate-value numbers, the result depends on the C library. On many systems, this means that ROUND() uses the "round to nearest even" rule: A value with any fractional part is rounded to the nearest even integer."


text:
Q: Compare two UIImages with CC_MD5 in iOS ,but the hash code will be changed after reboot the device I 've use
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(inImage)];

CC_MD5(imageData, [imageData length], result);

for generate MD5 code of my picture and add them to NSDictionary for compare the image from photoLibrary.
But when I add some code or reboot my device , I find the hash code is totally changed .
How can resolve this problem ?

A: You should use
NSData *imageData = [NSData dataWithContentsOfFile:file];
CC_MD5(imageData, [imageData length], result);

that must work fine.
Also consider to use sha1 as basing algorithm.

A: PNG file format allows to have timestamps inside the binary data. This will be different every time you call UIImagePNGRepresentation. I am afraid you can't use MD5 to compare the data of two images this way. Try to extract the raw image data from the files and generate MD5 of the raw data.


text:
Q: Error:Unable to resolve dependency for ':app@debug/compileClasspath' Hello I am facing Unable to resolve dependency error in my android studio & i`ve tried it all e.g deleting .gradle folder updating gradle to 4.5 reinstalll android studio and many more solution but I still have this error pls help  Here are gradle files
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "pk.com.sngpl.gasiscash"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    allprojects {
        repositories {
            google()
            maven { url "https://jitpack.io" }
            maven { url "https://maven.google.com" }
            maven { url 'http://repo1.maven.org/maven2' }
            jcenter()
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    androidTestImplementation 'junit:junit:4.12'

    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:design:26.1.0'
    compile 'com.github.blackfizz:eazegraph:1.2.2@aar'
    compile 'com.github.dmytrodanylyk:android-morphing-button:98a4986e56' // commit hash
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.android.support:recyclerview-v7:26.1.0'
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.github.bumptech.glide:glide:4.0.0-RC1'
    compile 'com.github.medyo:fancybuttons:1.8.4'
}

Here is another one
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Here is gradle wrapper properties
 #Tue Dec 19 19:38:03 PKT 2017
    distributionBase=GRADLE_USER_HOME
    distributionPath=wrapper/dists
    zipStoreBase=GRADLE_USER_HOME
    zipStorePath=wrapper/dists
    distributionUrl=https\://services.gradle.org/distributions/gradle-4.5.1-all.zip

& this is gradle.properties
[# Project-wide Gradle settings.

# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.

# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1024m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true][1]

A: App gradle :
 apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "pk.com.sngpl.gasiscash"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    androidTestImplementation 'junit:junit:4.12'

    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:design:26.1.0'
    compile 'com.github.blackfizz:eazegraph:1.2.2@aar'
    compile 'com.github.dmytrodanylyk:android-morphing-button:98a4986e56' // commit hash
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.android.support:recyclerview-v7:26.1.0'
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.github.bumptech.glide:glide:4.0.0-RC1'
    compile 'com.github.medyo:fancybuttons:1.8.4'
}

main gradle :
    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
        repositories {
            google()
            maven { url "https://jitpack.io" }
            maven { url "https://maven.google.com" }
            maven { url 'http://repo1.maven.org/maven2' }
            jcenter()
        }
    }

task clean(type: Delete) {
    delete rootProject.buildDir
}

Try this and let me know..


text:
Q: Dynamic Alocation in c not working I'm getting exit(1)(if there's some error in the allocation) every time i try to run the case 1. And i have no ideia why, can i get some help ?
#include <stdio.h>
#include <stdlib.h>

typedef struct hospede{             //guest
    int numreg;     //register num
    char nome[80];
    int acompanhante;   //n of ppl
    int dias;   //time to stay
    estado tabela;
}hospede;

typedef struct quarto{          //room
    int num;    //num do quarto
    char categoria;     //[S] ou [F]
    char status;        //[L] ou [O]
    estado stats;
    }quarto;

void alocaHospede(hospede **hosp, int tam);
void alocaQuartos(quarto **quar, int tam);
void geraQuartos(quarto *quar);
void checkIn(hospede *hosp, int tam);

int main()
{
    hospede *hpd = NULL;
    quarto *qrt = NULL;
    quarto quart;
    int qtd = 0;
    char op;
    int x;

    qrt = &quart;
    geraQuartos(qrt);
    do{
        printf("\n1-CheckIn\n>");
        scanf("%i", &x);
        fflush(stdin);
        switch(x){
        case 1:
            alocaHospede(&hpd, qtd+1);
            checkIn(hpd, qtd);
        }
        printf("\nDeseja continuar? \n");
        scanf("%c", &op);
        fflush(stdin);
    }while(op!='n' && op!='N');

    return 0;
}
void checkIn(hospede *hosp, int tam){
    printf("\nwork\n");
}//checkIn
void alocaHospede(hospede **hosp, int tam){
    *hosp = (hospede*)realloc(*hosp, tam*sizeof(hospede));
    if(*hosp == NULL)
        exit(1);
}//aloca hospede

void alocaQuartos(quarto **quar, int tam){
if((*quar = (quarto *) realloc(*quar, tam * sizeof(quarto)))== NULL)
    exit(1);
}//alocaQuartos

void geraQuartos(quarto *quar){
    int i;
    for(i=0;i<15;i++,quar++){
        (*quar).num = i+1;
    }
}//geraQuartos

OBS:
I Removed some structures and unions that aren't being used yet to make the code shorter, also i'll do the allocation to the rooms as well, i think it's the same problem.

A: geraQuartos(qrt) causes stack overflow since quart is only 1-entry-lengthed but you writes 1st ~ 15th entries inside the function.
Anything strange could happen on stack overflow.

A: The for loop in geraQuartos is treating its argument as a pointer to an array of 15 quartos structures. But it's a pointer to just one structure, so it's writing outside the bounds of the object. This is causing undefined behavior, and in this case it's overwriting hpd so it's not NULL. This then causes realloc to fail because the first argument isn't NULL or a pointer that was previously returned by malloc.
Change the declaration of quart to:
quarto quart[15];

and then do:
geraQuartos(quart);


text:
Q: Spivak, Ch. 20, Problem 18: Use Taylor's Theorem to prove that $\lim\limits_{x\to a} \frac{f(x)-P_{n,a}(x)}{(x-a)^n}=0$ The following is a problem from Spivak's Calculus

Chapter 20, Problem 18: Deduce Theorem $1$ as a corollary of Taylor's
Theorem, with any form of the remainder. (The catch is that it will be
necessary to assume one more derivative than in the hypotheses for
Theorem 1).

Here is Theorem $1$

Theorem 1 Suppose that $f$ is a function for which
$$f'(a),...,f^{(n)}(a)$$
all exist. Let
$$a_k=\frac{f^{(k)}(a)}{k!}, 0\leq k\leq n$$
and define
$$P_{n,a}(x)=a_0+a_1(x-a)+...+a_n(x-a)^n$$
Then
$$\lim\limits_{x\to a} \frac{f(x)-P_{n,a}(x)}{(x-a)^n}=0$$

and here is Taylor's Theorem

Theorem 4 (Taylor's Theorem) Suppose that $f',...,f^{(n+1)}$ are defined on $[a,x]$, and that $R_{n,a}(x)$ is defined by
$$f(x)=f(a)+f'(a)(x-a)+...+\frac{f^{(n)}(a)}{n!}(x-a)^n+R_{n,a}(x)$$
Then
$$R_{n,a}(x)=\frac{f^{(n+1)}(t)}{(n+1)!}(x-a)^{n+1},\text{ for some }
 t \text{ in } (a,x)$$
(Lagrange form of the remainder).

My primary question is: why can or can't we use the following proof

Assume we know Taylor's theorem is true and assume the first $n+1$
derivatives of $f$ exist on $[a,x]$.
Taylor's theorem tells us that
$$f(x)-P_{n,a}(x)=R_{n,a}(x)=\frac{f^{(n+1)}(t)}{(n+1)!}(x-a)^{n+1},
 \text{ for } t\in (a,x)$$
Then,
$$\lim\limits_{x\to a}
 \frac{f(x)-P_{n,a}(x)}{(x-a)^n}=\lim\limits_{x\to a}
 \frac{f^{(n+1)(t)}}{(n+1)!}(x-a)=0$$

In addition, let me just show the solution manual solution and my own understanding of it in more steps
Solution Manual

Suppose $|f^{(n+1)}|$ is bounded, by some $M$, on some interval around
$a$. Then for $x$ in this interval we have
$$|R_{n,a}(x)|=\frac{|f^{(n+1)}(t)|}{n!}|x-a|^{n+1}\tag{1}$$
so
$$\frac{|R_{n,a}(x)|}{|x-a|^n}\leq M|x-a|\tag{2}$$
so
$$\lim\limits_{x\to a} \frac{R_{n,a}(x)}{(x-a)^n}=0\tag{3}$$
A similar proof works for the integral form of the remainder and for
the Cauchy form.

Here is my understanding of this proof in more steps

Suppose we know Taylor's theorem is true, and assume the assumptions
of that theorem are true on some interval $[a,x]$.
One of those assumptions is that $f',...,f^{(n+1)}$ are defined on
$[a,x]$. Thus, $f^{(n+1)}$ is continuous on $[a,x]$, and
hence bounded on this interval.
Thus, there exists some $M>0$, such that for any $x_1\in[a,x]$ we
have $|f^{(n+1)}(x_1)|\leq M$.
In addition, Taylor's theorem tells us that there is some $t\in
 (a,x)$ such that
$$R_{n,a}(x)=\frac{f^{(n+1)}(t)}{(n+1)!}(x-a)^{n+1}\tag{4}$$
Second question: why does $(1)$ have the denominator as $n!$ and not $(n+1)!$ as in $(4)$?
Now we take the absolute value of both sides of $(4)$
$$|R_{n,a}(x)|=\frac{|f^{(n+1)}(t)|}{(n+1)!}|(x-a)|^{n+1}$$
$$0\leq \frac{|R_{n,a}(x)|}{|x-a|^{n}}=\frac{|f^{(n+1)}(t)|}{(n+1)!}|x-a|$$
$$\leq \frac{M}{(n+1)!}|x-a|\leq M|x-a|$$
Hence
$$\lim\limits_{x\to a}
 \frac{|R_{n,a}(x)|}{|x-a|^{n}}=\lim\limits_{x\to a}
 \frac{|f(x)-P_{n,a}(x)|}{|x-a|^{n}} =0$$
$$\implies \lim\limits_{x\to a} \frac{f(x)-P_{n,a}(x)}{(x-a)^{n}} =0$$
which is the result of Theorem 1.

A: For your second question: yes I think it is a typo, and it should be $(n+1)!$.
For your first question: note that the $t$ depends on $x$, the $f^{(n+1)}(t)$ term will vary as $x \to a$ (you cannot treat it as a constant in $x$), and you cannot immediately conclude $\lim_{x \to a} \frac{f^{(n+1)}(t)}{(n+1)!} (x-a) = 0$. As the solution manual shows, this can be fixed as long as you have a condition that ensures the existence of some $M$ such that $|f^{(n+1)}(t)| \le M$ for all $x$ near $a$.


text:
Q: Confusion in understanding of Steinitz Exchange Lemma by an example I am trying to understand Steinitz Exchange Lemma from Kurosh's Group Theory:

Suppose in a group $G$, two finite systems of elements are given:
$$
u', u'', \ldots, u^{(k)} \hskip5mm (I) \hskip1cm \mbox{ and } \hskip5mm v', v'', \ldots, v^{(l)} \hskip5mm (II)
$$
the first of which is linearly independent system, each of whose elements is linearly dependent on the second system. Then $k\le l$ and from $(II)$, $k$ elements can be omitted such that the remaining elements with the elements of $(I)$ form a system equivalent to $(II)$.

My question is simple, but I am not getting my fault in understanding.
Suppose we have group $G=\mathbb{Z}\oplus \mathbb{Z}$, with following systems of elements.
$$
(2,0), (0,2) \hskip5mm (I) \hskip1cm \mbox{ and } \hskip1cm (1,0), (0,1)\hskip5mm (II).
$$
It is clear that

*

*$(I)$ is linearly independent (their $\mathbb{Z}$-linear combination is zero only when coefficients are zero).

*Members of $(I)$ are linearly dependent on $(II)$ (obvious).

*$k\le l$ (they are equal to two both).
As per assertion, we can omit two elements from $(II)$ and replacing them two elements from $(I)$, we get a system equivalent to $(II)$; it means that $(I)$ and $(II)$ should be equivalent. But this is not the case - members of $(II)$ are not $\mathbb{Z}$-combinations of members of $(I)$.
Can anybody point out my misunderstanding?

A: According to Kurosh, systems (I) and (II) are equivalent.
Note the definition given by Kourosh:
An element $u$ of $G$ linearly dependent on the
system of elements $u_1,u_2,\ldots,u_l$ of $G$ if
$$
\alpha u=\beta_1 u_1+\beta_2 u_2+\ldots+\beta_lu_l,\ \alpha,\beta_i\in\mathbb{Z}.
$$
And perhaps $\alpha\neq1$.


text:
Q: Potential issues (if any) in recursively replacing spaces with underscores across all filenames on hard-drive In my external hard drive, there are about 1TB of data (PDFs, plain text docs, pictures, binary execuatables etc.). The data was created in Windows 10 and the hard-drive is formatted NTFS.
Starting from the root of the hard drive, I would like to recursively descend into each folder and replace the spaces in all files with underscore to make it easier to work with them from the terminal.
I saw the question here: and thinking of using the top answer there
 rename 'y/ /_/' *

from the root of my external hard drive.
However, that thread does not have a high view count and only 2 members have upvoted the answers. Being a novice, I am a little concerned if there might be any inherent issues in this. Is there a better way to handle this issue of cross-platform ease of working at the terminal ? (maybe advice like 'do this only for plain text files, or some other problems that I am not able to foresee')

A: I think it will work for you, but stay alert for the following problems that may arise:

*

*You may overwrite some files (ex: if you have 'some_file.txt' and 'some file.txt', the first one will be overwritten (lost).

*The rename command is not recursive. If you have many directories and sub-directories, you will need to figure out a way to do it (script, or using find, as pointed by @centimane find ./ -exec rename 'y/ /_/' {} \;).

*If you have some applications and lib files, they may stop work if they can't find the renamed files anymore (same for saved .html pages, for example).
It is a good idea to try the command first in a sub directory with a copy of some of the files.
obs: Sorry about the English. It is not my native language...


text:
Q: unable to change date format with "/" as separator , if default system date format having "-" as date separator In my local machine System short Date setting is of format "M/d/yyyy". In my C# code i can convert DateTime to "dd/MM/yyyy" or "dd-MM-yyyy" format using
//1
var date=string.Format("{0:dd/MM/yyyy}", DateTime.Now) //output is:05/09/2017
//2
var date=string.Format("{0:dd-MM-yyyy}", DateTime.Now) //output is:05-09-2017

But if i change my system date settings of short date to "yyyy-MM-dd" or simply any date format having "-" as separator instead of "/" i'm unable to convert date to other formats like
//3
var date=string.Format("{0:dd-MM-yyyy}", DateTime.Now) //output is:05-09-2017
//4
var date=string.Format("{0:dd/MM/yyyy}", DateTime.Now) //output is still :05-09-2017

In the above code even i have changed separator to "/" it's still giving "-" in the output.How can i output 4th one to "05/09/2017".

A: The / character is a special formatting character for DateTime which says "use the specified/current locale's date separator".
If you want to force it to use / you have to escape the character by surrounding it with single quotes:
var date=string.Format("{0:dd'/'MM'/'yyyy}", DateTime.Now)

Alteratively, you can escape it with the \ character:
var date=string.Format("{0:dd\\/MM\\/yyyy}", DateTime.Now)

(But I find the first approach to be slightly more readable.)
Finally, you can also use double-quotes to escape it, but that's even less readable:
var date = string.Format("{0:dd\"/\"MM\"/\"yyyy}", DateTime.Now);

Alternatively (as Jon points out) you can override the culture to use one that uses / as a separator:
var date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now);


text: Q: Avahi - Publish service to an unique device Is there any way to publish a service like a printer or chromecast to an unique device? I am trying to configure avahi in an environment where there are several iot devices (printers, chromecast...) and I need to publish this device only to the equipment that I want.


text:
Q: OIDC integration with google cloud identity platform I could not use our own OpenID provider with google cloud platform to authenticate user to Firebase authentication framework, it complains invalid discovery document.
Although I ran test on https://openid.net/certification/testing/ it passes all test for discovery endpoint. Attaching snippet here.
Also my OIDC discovery endpoint : https://hagext.westeurope.cloudapp.azure.com/https/api/rest/v3.0/oauth/smartiddigitalaccess/.well-known/openid-configuration
Any help would be really appreciated! enter image description here
[enter image description here][2]

A: Based on the error message you have provided, it would be best to review the documentation on OpenID Connect with Google Identity Platform/GCP:
https://developers.google.com/identity/protocols/oauth2/openid-connect
Otherwise, it would be best to reach out to the GSuite support team as Identity Platform is under G Suite, and products such as Google's SAML and OpenID Connect support can be used with G Suite support. You may follow this link to reach out to GSuite support:
https://support.google.com/a/answer/1047213?pli=1


text:
Q: get the Widgets' tree of an application It's a well-known fact that Qt uses a "parent-child relationship" to link widgets together. In order to maintain a (C++)Qt5 application, I'm searching for a tool able to somehow describe these relationships, something like :
  QMainApplication
  |
  \----->QMainWindow
         |
         \----->QSplitter(as CentralWidget)
                |
                \--->QTextEdit
                \--->QTextEdit

It may be a function which could be launched from the code with the QApplication as a parameter; it may be too an external tool able to analyse the code.
Does such a function/tool exist ?

A: There are few solutions:
In Qt Designer there is widget which do something similar.

But you can use this class to see relationship:
ObjectTreeModel.h
#ifndef OBJECTTREEMODEL_H
#define OBJECTTREEMODEL_H

#include <QAbstractItemModel>

class ObjectTreeModel : public QAbstractItemModel
{
    Q_OBJECT
public:
    ObjectTreeModel( QObject *root, QObject *parent = 0 )
    {
        m_root = root;
    }

    QVariant data( const QModelIndex &index, int role ) const;
    QVariant headerData( int section, Qt::Orientation orientation,
    int role = Qt::DisplayRole ) const;
    int rowCount( const QModelIndex &parent = QModelIndex() ) const;
    int columnCount( const QModelIndex &parent = QModelIndex() ) const;
    QModelIndex index( int row, int column,
    const QModelIndex &parent = QModelIndex() ) const;
    QModelIndex parent( const QModelIndex &index ) const;
private:
    QObject *m_root;
};

#endif // OBJECTTREEMODEL_H

*.cpp
#include "objecttreemodel.h"

QVariant ObjectTreeModel::headerData(int section, Qt::Orientation orientation, int role ) const
    {
         if( role != Qt::DisplayRole || orientation != Qt::Horizontal )
            return QVariant();
         switch( section )
        {
            case 0:
                return QString( "Object" );
            case 1:
                return QString( "Class" );
            default:
                return QVariant();
        }
    }

QModelIndex ObjectTreeModel::index(int row, int column,const QModelIndex &parent ) const
{
    QObject *parentObject;
    if( !parent.isValid() )
        parentObject = m_root;
    else
        parentObject = static_cast<QObject*>( parent.internalPointer() );
    if( row >= 0 && row < parentObject->children().count() )
        return createIndex( row, column, parentObject->children().at( row ) );
    else
        return QModelIndex();
}

int ObjectTreeModel::rowCount(const QModelIndex &parent ) const
{
    QObject *parentObject;
    if( !parent.isValid() )
        parentObject = m_root;
    else
        parentObject = static_cast<QObject*>( parent.internalPointer() );
    return parentObject->children().count();
}
int ObjectTreeModel::columnCount(const QModelIndex &parent ) const
{
    return 2;
}

QVariant ObjectTreeModel::data( const QModelIndex &index, int role) const
{
    if( !index.isValid() )
        return QVariant();
    if( role == Qt::DisplayRole )
    {
    switch( index.column() )
    {
        case 0:
            return static_cast<QObject*>( index.internalPointer() )->objectName();
        case 1:
            return static_cast<QObject*>( index.internalPointer() )->metaObject()->className();
        default:
            break;
    }
    }
return QVariant();
}

QModelIndex ObjectTreeModel::parent(const QModelIndex &index) const
{
    if( !index.isValid() )
        return QModelIndex();
    QObject *indexObject = static_cast<QObject*>( index.internalPointer() );
    QObject *parentObject = indexObject->parent();
    if( parentObject == m_root )
        return QModelIndex();
    QObject *grandParentObject = parentObject->parent();
    return createIndex( grandParentObject->children().indexOf( parentObject ),0, parentObject );
}

Usage(in main.cpp):
#include "objecttreemodel.h"
//...
MainWindow w;
w.show();
ObjectTreeModel *model = new ObjectTreeModel(&w);
QTreeView tree;
tree.setModel(model);
tree.show();

Result:


text:
Q: ServiceStack.DataAnnotations missing attributes definitions? I'm trying to use ServiceStack's attribute decorators from ServiceStack.DataAnnotations but when I view the ServiceStack.DataAnnotations namespace in the MSVS Object Browser, there are only the following types:
ComputeAttribute
DecimalLengthAttribute
IgnoreAttribute
PrimaryKeyAttribute
I have the latest bins and all of my references check out.  Specifically, I'm looking to use the [AutoIncrement] and [Index] attribs.
Thanks

A: The [AutoIncrement] and [Index] attributes are in the ServiceStack.Interfaces.DataAnnotations namespace in the dependency-free ServiceStack.Interfaces.dll which if you're using NuGet you can find inside the ServiceStack.Common NuGet package.


text:
Q: Phoenix different title per page with root module This question is similar to (but not an exact duplicate of) Phoenix Framework - page titles per route.
Ideally, i want to create titles like in the described question, but I am using a root layout since my project uses Phoenix LiveView. The HTML skeleton including the head and title HTML tag are part of the root template (root.html.eex). The app template extends on that from my understanding. I implemented the code from the above question
<title>
  <%= if Kernel.function_exported?(@view_module, :title, 2) do %>
    <%= @view_module.title(Phoenix.Controller.action_name(@conn), assigns) %> - StHub
  <% else %>
    StHub
  <% end %>
</title>

and created a title function inside of my specific page view
defmodule StHubWeb.WowsView do
  use StHubWeb, :view

  def title(_action, _assigns) do
    "Dashboard"
  end
end

but the else branch of the code is triggered. Upon further inspection, I think that the issue is with using a root template, because the @view_module while rendering the root template is StHubWeb.LayoutView, and only inside of the LayoutView/app.html.eex template, the @view_module is my actual view (StHubWeb.WowsView).
I am not sure how to solve this other than removing the root template, but then my LiveView will have to contain the entire HTML skeleton all the time.
Maybe there is a way for me to define a title function in my LayoutView that will grab the title from StHubWeb.WowsView, but I am not sure how to do that.
Thanks for the help!


text:
Q: Cannot create a cdo instance in python My python version is 3.10.6. I want to create an instance of a Cdo object in python (https://pypi.org/project/cdo/).
from cdo import *
cdo = Cdo()

Howerver, I am getting the following error:
/usr/bin/python3.10 /home/iliamous/PycharmProjects/winbank-esg-risk-gis-platform/scratch_work.py
Traceback (most recent call last):
  File "/home/iliamous/PycharmProjects/winbank-esg-risk-gis-platform/scratch_work.py", line 209, in <module>
    cdo = Cdo()
  File "/home/iliamous/.local/lib/python3.10/site-packages/cdo.py", line 190, in __init__
    self.operators         = self.__getOperators()
  File "/home/iliamous/.local/lib/python3.10/site-packages/cdo.py", line 283, in __getOperators
    version = parse_version(getCdoVersion(self.CDO))
  File "/home/iliamous/.local/lib/python3.10/site-packages/cdo.py", line 78, in getCdoVersion
    proc = subprocess.Popen([path2cdo, '-V'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
  File "/usr/lib/python3.10/subprocess.py", line 969, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.10/subprocess.py", line 1720, in _execute_child
    and os.path.dirname(executable)
  File "/usr/lib/python3.10/posixpath.py", line 152, in dirname
    p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not NoneType

A: Seems there was an issue with the installation of the package. First, I removed the package by writing in the terminal
pip uninstall cdo

Then, I installed cdo again, this time using the command line
sudo apt-get -y install cdo

For more info check https://installati.one/ubuntu/20.04/cdo/.


text:
Q: Loaded MobileNet model giving wrong predictions I am trying to load mobilenet_v2_1.4_224 (link: https://github.com/tensorflow/models/tree/master/research/slim/nets/mobilenet) which was trained in TensorFlow, and serve it in GoLang.
Thing is when I try to make a prediction of image with a panda, I get the wrong prediction. My guess is I downloaded wrong imagenet label file. On which imagenet dataset was network i mentioned above trained on?

A: AFAIK MobileNet from the Tensorflow Model Zoo is trained on ILSVRC-2012-CLS, which has 1,000 classes including Giant Panda and Red Panda.
However as MobileNet is not 100% accurate, you might experience varying results depending on the input image you provide. Make sure to make it is tightly cropped around the Panda, and try various images, as some might return incorrect labels as even the best MobileNets V2 models have an accuracy around 70% on the ImageNet dataset.
If you want to be able to classify pandas more precisely, I'd suggest retrain your MobileNet model with a Panda dataset. There are plenty of available examples on how to do this, I have linked a couple below using the MobileNets architecture and Tensorflow as Framework.
https://www.tensorflow.org/hub/tutorials/image_retraining
https://hackernoon.com/creating-insanely-fast-image-classifiers-with-mobilenet-in-tensorflow-f030ce0a2991
https://medium.com/@sumit.arora/training-a-neural-network-using-mobilenets-in-tensorflow-for-image-classification-on-android-14f2792f64c1


text:
Q: Partition setup in oracle We are having few tables with partitions and we don't know how to get the partition keys for a specific table.
How can I get or view the partition key set up in oracle database for a specific table?

A: You'll find that information here:
select * from USER_PART_TABLES;
select * from USER_PART_KEY_COLUMNS;

Source.

A: Check out all the below data dictionary views,
ALL_PART_KEY_COLUMNS
DBA_PART_KEY_COLUMNS
USER_PART_KEY_COLUMNS

There is also a view called ALL_SUBPART_KEY_COLUMNS.