text:
Q: Redesign the storage of large amounts of sensor data I have been tasked to implement/redesign a solution that will store weather data from a sensor array. The array will consist of ~40 towers, each with about ~10 sensors each that'll sample atmospheric conditions at 10 second intervals for an undetermined amount of time (years).
Some of the applications and requirements for this task are as follows:

*

*Manage and retrieve tower/sensor configurations to make sense of data analysis.

*Data visualization by sensor or time intervals for meteorological observations.

*Provide customers with reliable and persistent data resources/data sets to compare model and sensor performance (may require some post-processing to deliver in the format required?).

Note: The current solution (implemented as a proof of concept, with 5 towers) stores data as flat files (one file per hour).
I was originally unsure if this would constitute a big data problem in the future, so I researched on a couple of solutions both for relational and NoSQL databases, but I feel I need a little more guidance, as I am no expert in data management.
One of the solutions I thought was to store data in a relational database indexed by tower, sensor, and timestamps and partitioning the table by date.
Another, based on future scaling, was to store it in a document-type NoSQL database, like MongoDB, and mimic the structure of the current solution.
Are any of these good approaches? If not, what would be a better/recommended solution? Also, would it even be necessary to redesign the current solution? I was told that the rationale for using flat files is that they believed a relational database would take too much overhead. Is there a way to avoid this if it was the case?

A: Since (a) the information you are working with appears to be, in a of itself, a very valuable organizational resource, and (b) the volume of data will be considerable, I would decidedly (c) build a relational database on one of the major SQL platforms.
That of course —from a very general perspective— requires three essential  factors:

*

*A clearly defined conceptual schema, in which one has to identify and mark out with precision the prototypes of things, i.e., the entity types (including their properties and interrelationships) of relevance in the business environment you are working with (e.g., the Towers and Sensors you mention).
As you know, this point entails establishing continuous and productive communication with business experts.

*A logical layout that reflects the conceptual level with accuracy, by means of tables (i.e., mathematical relations) holding well-delimited columns with appropriate column names and types (i.e., relation attributes) and all the corresponding constraints to ensure that the data complies with all the rules determined at the previous tier.
Therefore, it is here where the vast power of the relational model comes into play (though its advantages have positive repercussions at other levels of abstraction).

*A physical arrangement that, e.g., boosts the execution speed of the —dynamic— logical data manipulation operations and guarantees the logical constraints.
Since the relational model offers physical data independence, a database management system (DBMS for brevity) can provide any kind of structure at this level, not exclusively indexes, to support the logical definitions. In the case of the leading SQL platforms, yes, this commonly implies, precisely, setting up an indexing strategy based on the database-specific query tendencies, and you brought up very interesting considerations with respect to some possible configurations but, without knowing the particular informational necessities with exactitude, offering specific advices in this regard would not be suitable.
Other elements that deserve evaluation are, e.g., upgrading network infrastructure to increase bandwidth, enabling proper server configurations (hardware- and software-wise), etc. And, if, and only if, a practitioner is qualified enough, he or she could even modify the source code of the DBMS of choice (more feasible in open source environments, naturally).
In this way, the following aspects that you highlight

*

*Manage and retrieve tower/sensor configurations to make sense of data analysis.

*Data visualization by sensor or time intervals for meteorological observations.

*Provide customers with reliable and persistent data resources/data sets to compare model and sensor performance (may require some post-processing to deliver in the format required?).

would be well-addressed, because you would easily be able to declare queries to, e.g., obtain information in very meaningful forms. For instance, you can get data associated with

*

*the Sensor identified by SensorNumber 1750, installed at the Tower identified by TowerNumber 31, between the Date 1 June 2017 and the Date 27 June 2017.

Furthermore, since (1) the data in a relational database is logically managed in terms of sets with the aid of operations based on the relational algebra, and (2) the different SQL engines are physically optimized (some more than the others) for set processing, you can, e.g.,

*

*compare set a with set b;

*join set c with set d;

*obtain subset f through a restriction on set e;

*produce n subsets from n set intersections;

*project n attributes from set f

*retrieve information from set z that is the result of a union of set x with set y;

*and so on.

The data manipulation possibilities are in fact huge —demonstrating the unmatched versatility of the relational paradigm— since you can work not only with base tables (the ones declared with CREATE TABLE … ( … ); statements) but also with derived ones (the ones expressed via SELECT …; operations, sometimes fixed as VIEWs). In other words, you can (i) express new data structures based on (ii) prior ones operating on (iii) the single underlying relational construct, i.e., the mathematical relation.
Evidently, the arrangement of the base tables and columns of a relational database can evolve, and (a) new base tables or columns may be incorporated into it when (b) keeping track of new entity types or entity type properties is deemed worthwhile in the pertinent business context. In other words, neither the initial structure nor the opening constraints of a relational database are expected to be static or immutable. Besides, a database that is appropriately organized from the very beginning tends to be much easier to modify when new informational requirements arise.
In agreement with the considerations above, the logical format of the applicable sets must be produced declaratively, at the database logical level. The graphical or presentational formatting of the sets (e.g., the colouring or font faces utilized) must in turn be processed by way of the code of one or more application programs (yes, mostly in a procedural manner, perhaps with the assistance of an object-oriented framework, HTML, etc.), in order to make the access and presentation of such sets user-friendly. Certainly, you could as well use reporting software that connects with your database.
The modeling of a database of relevance
Given that you will be working with Sensor data (which, among other features, typically involves information in the shape of time series), you may find of help multiple database design and overall administration principles contained in the two exceptional answers, by @PerformanceDBA, to the questions entitled:

*

*"Opinions on sensor / reading / alert database design", and

*"Historical / auditable database".

The Relational, Flat File and NoSQL approaches
The relational model by Dr. Edgar Frank Codd, although published in 1970, remains genuinely the most modern and elegant method (based on logic and set theory) to cope with the problem of data management. The distinct SQL DBMSs are, in turn, the most popular approximations (that, although not fully compliant, are nevertheless really powerful) to the systems proposed in the relational theory, and some of them have been heavily optimized (e.g., regarding their physical-level mechanisms) for even decades now. In addition, the main SQL platforms of course can (and will be able to) work with the most up-to-date storage (e.g., hard drives) and processing (e.g., CPUs) technologies quite efficiently.
When built on a powerful DBMS, a relational database that is properly designed at the conceptual, logical and physical levels would decidedly become a self-contained, self-descriptive and self-protective asset that (1) is trustworthy and (2) offers a fast response, two aspects that, as you know, are of great significance.
Flat files
Therefore, the claim that follows

I was told that the rationale for using flat files is that they believed a relational database would take too much overhead.

is easily discarded, because the flat file approach would be:

*

*pre-scientific;

*far from optimal for large volumes of data;

*too cumbersome;

*application program-dependent (and you would have to implement by hand most of the features that proper DBMSs offer natively);

*its performance will easily be undermined;

*etc.

Whereas the —much more convenient— relational fashion, to say the least:

*

*would offer large scalability (it is physical-level-independent, so you could enhance the underlying physical mechanisms as needed);

*would bring a simple style to manipulate the data (via abstract operations) and

*could work with multiple application programs simultaneously (e.g., one or more mobile apps, and/or one or more web apps, and/or one or more desktop apps, etc.).

If, however, you opt for utilizing flat files, you should evaluate the employment of a robust utility like Awk that, although not a DBMS (and was not designed as such), supplies handy resources to deal with files, records, fields, etc. See The GNU Awk User's Guide for more information on this subject.
NoSQL
"Unstructured data" and associated terms
As per their propaganda, the initial justification for the usage of NoSQL DBMSs is that they are meant to be used in business domains that involve handling "unstructured data", so that calls for the question:

*

*What is the expression "unstructured data" supposed to mean?

In that respect, it must be said that data, by its very nature, is structured; if it had no structure then it would be something meaningless, consequently such a thing (i) could not be considered data and (ii) would not be worth administering. Hence, "unstructured data" is a contradictory and unfortunate expression.
Other phrase of those contexts is "semi-structured data". That phrase suggests that there exists data that is structured "in part" or "in half" so, in accordance with the previous paragraph, only the "part" or "half" that is structured can be actual data, the remaining "part" or "half" is merely a shapeless thing because it lacks structure, and cannot be referred to as data.
Yet another, alas, typical term that is found in NoSQL marketing is "polymorphic data". If said term signifies something like "data that has many different forms", then it is in fact ordinary data, it comes about in many distinct forms as always. And since it has many different forms, then it presents many distinct structures, so there is nothing special about this "kind" of data.
Needless to say, data and data structures have always been susceptible to changes, then there is nothing unusual in this regard either.
Data volume growth
Evidently, the volumes of information managed by means of computerized systems have definitely grown over the years —and will keep growing exponentially as time passes, because new systems are being built every day—, but that is a fact that does not have to do with the structure of the information per se.
Lack of a rounded theoretical foundation
A critical limitation of NoSQL systems (there are of different classes, e.g., document- and graph- based) is that none of the current products —although heavily marketed and labeled as "modern"— possesses a sound theoretical basis (if at all) that supports each and everyone of the three most important elements of a proper DBMS, i.e., tools for data (a) definition, (b) manipulation, and (c) constriction. Thus, the NoSQL approach actually suggests a regression to an ancient era in which the handling of the data was performed in an ad hoc and unsound course of action, with all the needless complexity it entails.
Nowadays, graph systems are included within the "NoSQL" spectrum. These software products invite to manage data by virtue of operations on two distinct structures: nodes and relationships —which, once again, is in conflict with the term "unstructured data"—, and they stand out in the "NoSQL" group because they do have a mathematical foundation. However, graph products are rather similar to network platforms, which are deemed obsolete since tens of years ago (an obvious drawback is that, as suggested above, they need two structures for data representation, while a relational DBMS —as per the information principle— needs only one).
Even if the creation of the different NoSQL systems is chronologically newer in comparison with the origins of the majority of the SQL DBMSs, most of the concepts onto which the NoSQL products are based are, in effect, primitive.
A NoSQL program should be employed, mostly, in scenarios where, e.g.,

*

*the IT personnel lacks the technical skills required to determine (or to determine opportunely) the structure of the data of interest —e.g., due to its complexity—; and/or

*the organization cannot afford suitable education and training for the present staff, or cannot hire new staff that possesses the required education and training; and/or

*when the integrity and consistency of the data is not particularly important; and/or

*when blending the concerning data with that of mission critical systems that demand high precision is not expected.

But, even if the structure of the data at issue is not defined before the creation of the concerning systems, one ore more people will necessarily have to

*

*discover the aforesaid structure,

*discard all the surrounding "interference" and

*collect and link the proper data

after the database and app(s) have entered the production stage in order to be able to get the most out of all the resources invested in a project, then data structure delineation is a task that cannot be bypassed, it has to be done sooner or later.
So, while going the NoSQL way is a possibility, all the factors previously mentioned should definitely be taken into account.
The most robust method
In contrast, approaching the informational requirements of a business environment in a relational manner —i.e., with a general paradigm behind— offers the possibilities of (1) managing the data in its natural structure from the beginning —which eases integration with other data sources— and also of (2) producing new trustworthy structures by dint of the manipulation of a single instrument —as explained in previous sections— that has a robust scientific basis.
According to your description of the scenario in question, you have already identified a particular structure in terms of the relevant organizational needs, so I suggest requesting that the business domain experts validate it. Successively, I recommend taking advantage of (i) the constructs —the relation, the constraints and the operations— provided by the relational model to handle said structure and the respective data, and of (ii) your SQL DBMS of choice which will very likely offer very efficient physical tools that can hold up the present demands and will supply future scalability.


text:
Q: Time Machine to two external USB drives vs Time Machine to 1 external Raid-1 Recently I purchased an iMac Pro with an internal 2TB SSD and restored my system from an external 1TB HDD Time Machine backup as originally created by my old MBP. For the time being I have continued to use the external HDD for my iMac Time Machine backup, however as this drive is only 1TB it's no longer suitable as a backup target (or at least, the time will soon come where it is not suitable due to lack of space).
My new machine setup is thus:

*

*iMac for day-to-day work, covering everything I do for my business.
This is the mission critical device.

*MBP for very rare out of office
work. I might need to do this once or twice per year.

I've been considering a new backup strategy primarily for my new iMac, and my current thinking is thus:

*

*Replace the external 1TB HDD Time Machine drive with an external
RAID-1 device, namely this device G-Technology 12TB G-RAID with
Thunderbolt 3 Hard Drive Storage System - Apple (AU), and target
Time Machine backups there.

*Nightly backups of my internet 2TB drive to Backblaze.

I believe this is effectively the 3-2-1 strategy: 1 internal drive, 1 external drive, 1 off-site backup.
In considering the above I've been researching opinions about RAID-1, and in doing this have seen a lot of opinions stating "RAID isn't backup", "never use RAID for backup" and "deleting files from your drive or being infected with a virus will replicate to the RAID with no roll-back", yet when I consider my strategy above - and bearing in mind for a moment that the RAID drive will only be used for Time Machine backup/restore - I feel like these comments don't apply to my planned configuration. I say this because with RAID-1 I get desirable redundancy protection from drive failures (up to a point, naturally), and as I use Time Machine I inherently benefit from the ability to pick and choose from historical backups. I therefore look at my planned approach and think "I benefit from redundancy, and because I use Time Machine I have multiple versions of each backup, so why can't or shouldn't I use RAID-1 for backup?".
With that said, I have also seen some discussion around using 2 or more external HDDs whereby Time Machine is configured to alternate backups between the drives with each cycle, backing up only what has changed since the last cycle for the specific drive in use. In this setup I could probably buy two 2/3/4TB external HDDs, plug them both in to my iMac, and let Time Machine alternate backups between them.
I am interested in hearing from the experts on this forum their opinions regarding my planned backup strategy, whether RAID-1 as described above makes sense or not (and if not, why not?), and just as interesting to me, what benefits or drawbacks I'm likely to encounter going this route as opposed to simply using two external HDD drives with alternative incremental Time Machine backups. There are two obvious benefits I can already see to using two external HDDs: 1) the cost saving over the external RAID-1 drive (but that is less important to me than reliability and redundancy of backups, not to suggest external drives are inherently unreliable) and 2) if I buy portable external HDDs I can likely use them with the MBP when I'm on the road (this is a very low priority).
Many thanks in advance.

A: I ultimately went with the G-Tech device linked in my original post. My opinion is that it will work perfectly fine with Time Machine, with the added benefit of redundancy should one of the two disks explode. I am also employing off site backups with Backblaze, so I now feel like my risk is covered.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Limited permissions in tmux session I am using a tmux session to run a script that runs some Python code (which uses a virtual environment stored at /opts/...; Python binaries have been copied not linked) that creates virtual machines using libvirt. When I run virsh list --all inside of this tmux session when the script has finished, the machines do not show up. When I run sudo virsh list --all they show up. When I leave the session virsh list --all shows me the VMs as expected. I get them listed as expected as well in a subsequently created new tmux session. What is happening and how can I fix this?
If I run the script outside tmux, then listing the virtual machines works with virsh list --all.


text:
Q: How to fix a Damaged APFS disk? I have an issue with a 1TB 850 Evo, serving as an external disk in a SATA enclosure. I would Really like to recover the data I have on it so any help would be greatly appreciated.
The disk has been running fine as an APFS for a long time. Suddenly it became unnreadable, possibly after using it it in a different USB enclosure. When plugged inn, the disk does not mount. I have tried the below fixes/analysis after browsing this forum. Is there anything else I can do to analyse and/or attempt a repair?
Readout from GPT and Diskutil:

Last login: Wed Aug 14 18:10:42 on ttys000
Framelands-MacBook-Pro:~ frameland$ sudo gdisk /dev/disk4
Password:
GPT fdisk (gdisk) version 1.0.4

Partition table scan:
MBR: not present
BSD: not present
APM: not present
GPT: not present

Creating new GPT entries in memory.

Command (? for help): x

Expert command (? for help): p
Disk /dev/disk4: 244139185 sectors, 931.3 GiB
Sector size (logical): 4096 bytes
Disk identifier (GUID): 59E13892-D1CC-4871-AE60-652455350D51
Partition table holds up to 128 entries
Main partition table begins at sector 2 and ends at sector 5
First usable sector is 6, last usable sector is 244139179
Partitions will be aligned on 256-sector boundaries
Total free space is 244139174 sectors (931.3 GiB)

Number Start (sector) End (sector) Size Code Name

Expert command (? for help): o

Disk size is 244139185 sectors (931.3 GiB)
MBR disk identifier: 0x00000000
MBR partitions:

Number  Boot  Start Sector  End Sector  Status   Code
1             1             244139184   primary  0xEE

Expert command (? for help): q
Framelands-MacBook-Pro:~ frameland$ sudo gdisk /dev/disk3
GPT fdisk (gdisk) version 1.0.4

Partition table scan:
MBR: protective
BSD: not present
APM: not present
GPT: present

Found valid GPT with protective MBR; using GPT.

Command (? for help): x

Expert command (? for help): p
Disk /dev/disk3: 1953525168 sectors, 931.5 GiB
Sector size (logical): 512 bytes
Disk identifier (GUID): 2BA6A682-802B-40E9-8DCB-D924582CFC8C
Partition table holds up to 128 entries
Main partition table begins at sector 2 and ends at sector 33
First usable sector is 34, last usable sector is 1953525134
Partitions will be aligned on 8-sector boundaries
Total free space is 2021 sectors (1010.5 KiB)

Number  Start (sector)  End (sector)  Size       Code  Name
1       40              409639        200.0 MiB  EF00  EFI System Partition
2       411648          1953525127    931.3 GiB  AF0A

Expert command (? for help): o

Disk size is 1953525168 sectors (931.5 GiB)
MBR disk identifier: 0x00000000
MBR partitions:

Number  Boot  Start Sector  End Sector  Status   Code
1             1             1953525167  primary  0xEE

Expert command (? for help): q
Framelands-MacBook-Pro:~ frameland$

Framelands-MacBook-Pro:~ frameland$ diskutil apfs list
APFS Containers (2 found)
|
+-- Container disk1 6801A9B4-1736-46EE-BABA-0DEB9ED0D53C
|   ====================================================
|   APFS Container Reference:     disk1
|   Size (Capacity Ceiling):      499963170816 B (500.0 GB)
|   Capacity In Use By Volumes:   460495699968 B (460.5 GB) (92.1% used)
|   Capacity Not Allocated:       39467470848 B (39.5 GB) (7.9% free)
|   |
|   +-< Physical Store disk0s2 3689942A-E50C-4A74-A827-B763D501115A
|   |   -----------------------------------------------------------
|   |   APFS Physical Store Disk:   disk0s2
|   |   Size:                       499963170816 B (500.0 GB)
|   |
|   +-> Volume disk1s1 6EEB904E-B771-3E0B-8048-C3E4BB58F07A
|   |   ---------------------------------------------------
|   |   APFS Volume Disk (Role):   disk1s1 (No specific role)
|   |   Name:                      Macintosh HD (Case-insensitive)
|   |   Mount Point:               /
|   |   Capacity Consumed:         450106273792 B (450.1 GB)
|   |   FileVault:                 No
|   |
|   +-> Volume disk1s2 B8CA2171-4A7A-41DB-9E34-F6AEC2EDFC9D
|   |   ---------------------------------------------------
|   |   APFS Volume Disk (Role):   disk1s2 (Preboot)
|   |   Name:                      Preboot (Case-insensitive)
|   |   Mount Point:               Not Mounted
|   |   Capacity Consumed:         46379008 B (46.4 MB)
|   |   FileVault:                 No
|   |
|   +-> Volume disk1s3 2B5101E3-2892-466D-ADEA-8DB3D4B91B7B
|   |   ---------------------------------------------------
|   |   APFS Volume Disk (Role):   disk1s3 (Recovery)
|   |   Name:                      Recovery (Case-insensitive)
|   |   Mount Point:               Not Mounted
|   |   Capacity Consumed:         510283776 B (510.3 MB)
|   |   FileVault:                 No
|   |
|   +-> Volume disk1s4 0776BB08-4E72-478C-AD79-8B905F797AD8
|       ---------------------------------------------------
|       APFS Volume Disk (Role):   disk1s4 (VM)
|       Name:                      VM (Case-insensitive)
|       Mount Point:               /private/var/vm
|       Capacity Consumed:         9671274496 B (9.7 GB)
|       FileVault:                 No
|
+-- Container ERROR -69808
    ======================
    APFS Container Reference:     disk3
    Size (Capacity Ceiling):      ERROR -69620
    Capacity In Use By Volumes:   ERROR -69620
    Capacity Not Allocated:       ERROR -69620
    |
    +-< Physical Store disk2s2 CE445FE6-2BFE-416E-AF22-007E56AC0D3D
    | -----------------------------------------------------------
    | APFS Physical Store Disk:   disk2s2
    | Size:                       999994101760 B (1000.0 GB)
    |
    +-> No Volumes

A: There are 3rd party software packages for recovering lost, damaged, or deleted files. These work to varying levels that depends on if the disk space has been written over. Disk Drill, TestDisk for Mac, and others are included in a reference given at this link of the best free data recovery packages in 2020. Most packages like this are not cheap so a free one is maybe the best bet.
Not included in the list are EasyUs, Stellar Data Recovery and Recoverit. These are commercial packages and are not free although they may have free trial versions.
You have to decide for yourself which one sounds best. The only one I've used is the free trial version of Stellar Data Recovery. It worked ok finding some of my deleted files.

A: Assuming that the affected disk hasn't been wiped, so that we can still work with it, let's get some more info about the disk's structures, since the output provided by fsck_apfs that you saw in Disk Utility isn't particularly helpful. We need to know more about the role of the malformed object with OID 0x148d6d that is mentioned in the output.
Please download and compile apfs-inspect, then run it on your affected disk so that we can get a better idea of what's going on under the hood. Assuming that the output from diskutil is the same as that in your question, this is done with sudo apfs-inspect /dev/disk2s2 or sudo apfs-inspect /dev/disk3. Share the output here using Pastebin or similar, since it will be very long.

A: Looks like the media is formatted to Dos32.  You need to reformat the drive to exFat.

Explanation:
https://en.wikipedia.org/wiki/Large-file_support


text:
Q: C# windows form async task gettting cross thread operation exception I am getting a cross thread invalid exception on a small project with camera capture in windows forms.  I am using an async task but can't find the correct way to update a PictureBox element from the task routine without disabling the cross thread exception.  What is the correct way to avoid this?  I tried the Invoke required logic but then I get the same exception with the MainForm element
 private void InitCameraBtn_Click(object sender, EventArgs e)
        {
            if (InitCameraBtn.Text.Equals("Init Camera"))
            {
                StartCamera();
                InitCameraBtn.Text = "Stop Camera";
                isCameraRunning = true;
            }
            else
            {
                capture.Release();
                InitCameraBtn.Text = "Init Camera";
                isCameraRunning = false;
            }
        }

private async void StartCamera()
        {
            //cameraThread = new Thread(new ThreadStart(CameraThreadCallback));
            //cameraThread.Start();
            var r = await CameraThreadCallback();

        }

 public async Task<int>  CameraThreadCallback()
        {
            return await Task<int>.Run(() =>
            {

                frame = new Mat();
                capture = new VideoCapture(0);
                capture.Open(0);

                if (capture.IsOpened())
                {
                    while (isCameraRunning)
                    {

                        capture.Read(frame);
                        image = BitmapConverter.ToBitmap(frame);
                        if (CameraBox.Image != null)
                        {
                            CameraBox.Image.Dispose();
                        }
                        //CameraBox.Image = image;

                        setImage(image);
                    }
                }
                return 0;
            });
        }

private void setImage (Bitmap i)
        {
            //MainForm.CheckForIllegalCrossThreadCalls = false;
            CameraBox.Image = i;
            Thread.Sleep(500);

        }

A: You should update Camera box by using the below method:
private void SetCameraBoxImage(Image image)
    {
        if (CameraBox.InvokeRequired)
        {
            var d = new SafeCallDelegate(SetCameraBoxImage);
            CameraBox.Invoke(d, new object[] { image});
        }
        else
        {
            CameraBox.Image = image;
        }
    }

So Instead of using CameraBox.Image = value use SetCameraBoxImage(value)

A: I think that you are trying to access windows form control from another thread. In that case, you need to make a thread-safe call
public async Task<int> CameraThreadCallback()
{
    return await Task<int>.Run(() =>
    {
        frame = new Mat();
        capture = new VideoCapture(0);
        capture.Open(0);

        if (capture.IsOpened())
        {
            while (isCameraRunning)
            {
                capture.Read(frame);
                image = BitmapConverter.ToBitmap(frame);
                CameraBox.Invoke(new Action(() =>
                {
                    if (CameraBox.Image != null)
                    {
                        CameraBox.Image.Dispose();
                    }
                    CameraBox.Image = image;
                })):
            }
        }
        return 0;
    });
}


text:
Q: React Native Error: Invalid hook call. Hooks can only be called inside of the body of a function component I'm programming with some friends a Chess App and now we get an Error implementing the Chess itself.
we get the error in the first const of the function as well as at the Export of App.jsx
Our GitHub Repo: Chedu
App.jsx
import React, { useEffect, useState } from "react";
import "./App.css";
import { gameSubject, initGame, resetGame } from "./Game";
import Board from "./Board";

function App() {
  const [board, setBoard] = useState([]); //get Error here
  const [isGameOver, setIsGameOver] = useState();
  const [result, setResult] = useState();
  const [turn, setTurn] = useState();

  useEffect(() => {
    initGame();
    const subscribe = gameSubject.subscribe((game) => {
      setBoard(game.board);
      setIsGameOver(game.isGameOver);
      setResult(game.result);
      setTurn(game.turn);
    });
    return () => subscribe.unsubscribe();
  }, []);

  return (

      {isGameOver && (

          GAME OVER
          <button onClick={resetGame}>
             NEW GAME
          </button>

      )}

        <Board board={board} turn={turn} />

      {result &&
{result}
}

  );
}
export default App(); //Error Anonymous Function

in Index.js we are Rendering the function and export it.
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
export default ReactDOM.render(
  <React.StrictMode>
    <DndProvider backend={HTML5Backend}>
      <App />
    </DndProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

serviceWorker.unregister();

And at last we want to render the index.js in our ChessBoardPage
import React, { useState } from "react";
import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  Dimensions,
  Switch,
} from "react-native"; //components

import ReactDOM from "react-dom";

import cheduLogo from "../Pictures/Logo.png";
import loginPictureBlack from "../Pictures/login.png";
import loginPictureWhite from "../Pictures/login_white.png";
import registerPictureBlack from "../Pictures/register.png";
import registerPictureWhite from "../Pictures/register_white.png";
import userPictureBlack from "../Pictures/user.png";
import userPictureWhite from "../Pictures/user_white.png";

import ChessGame from "./ChessBoard/index";

const windowWidth = Dimensions.get("window").width;
const windowHeight = Dimensions.get("window").height;

const { width } = Dimensions.get("window");

const x = 100;
const y = 200;

export default class TempPage extends React.Component {
  state = {
    switchValue: false,
    backgroundColor: "white",
    SwitchLogin: loginPictureBlack,
    SwitchRegister: registerPictureBlack,
    SwitchUser: userPictureBlack,
    SunMoon: "☀",
    ShadowBackgroundColor: "white",
  };

  handleSwitchBackground = () => {
    [...]
    }
  };

  render() {
    let { backgroundColor } = this.state;
    return (
      <View
        style={{
          windowWidth,
          windowHeight,
          backgroundColor: this.state.backgroundColor,
        }}
      >

        [...]

        {/*Content*/}
        <View stlye={{ flex: 1 }}>
          <ChessGame />
        </View>
      </View>
    );
  }
}
[...]

A: sometime we have issues in react when using anonymous functions. Since anonymous functions aren't assigned an identifier (via const/let/var), they aren't persistent whenever this functional component inevitably gets rendered again. This causes JavaScript to allocate new memory each time this component is re-rendered instead of allocating a single piece of memory only once when using "named functions"
consider refactoring your code as follows
import React, { useEffect, useState } from "react";
import "./App.css";
import { gameSubject, initGame, resetGame } from "./Game";
import Board from "./Board";

const App = () => {
  const [board, setBoard] = useState([]); //get Error here
  const [isGameOver, setIsGameOver] = useState();
  const [result, setResult] = useState();
  const [turn, setTurn] = useState();

  useEffect(() => {
    initGame();
    const subscribe = gameSubject.subscribe((game) => {
      setBoard(game.board);
      setIsGameOver(game.isGameOver);
      setResult(game.result);
      setTurn(game.turn);
    });
    return () => subscribe.unsubscribe();
  }, []);

  return (

      {isGameOver && (

          GAME OVER
          <button onClick={resetGame}>
             NEW GAME
          </button>

      )}

        <Board board={board} turn={turn} />

      {result &&
{result}
}

  );
};
export default App;

I am not sure why  you are using HTML tags in react native, which think are not yet supported in  App.jsx. You should return a <View/> tag instead of div.


text:
Q: How to skip n rows for order by clause in SQL Server I have a dataset. The first 2 rows should be ignored and ordering (by name column) should start from the 3rd row. And it should be done through a query only.
aaa g   900
zzz g   900  -- the first 2 rows should be fixed
bb  g   900  -- ordering should start from here
yy  g   900
rrr g   900
fff g   900

Desired output:
    aaa g   900
    zzz g   900
    bb  g   900
    ff  g   900
    rrr g   900
    yy  g   900

A: You can use case logic in the order by:
order by (case when col1 = 'aaa' then 1
               when col1 = 'zzz' then 2
               else 3
          end),
         col1

A: select *
from table_name
except
select top 2 *
from table_name
order by column_name


text:
Q: Integral of $y^3 \sin^2 (x^2 + y^2 + z^2) $ I have the following problem, integrate $\int_B y^3 \sin^2(x^2+y^2+z^2)$ where $B$ is the set between $y^2 = 1-z$, $x=0$, $x=4$, $z=0$.
I have tried to solve the problem using spherical and cylindrical coordinates but the resulting integral is quite complicated. Is there any transformation resulting in a more reasonable integral? The problem advises to take into account the "simmetry" of the problem.
Thanks in advance.

A: The integral is $0$ because the integrand function is odd in $y$ and the integration set is even in $y$.

A: The volume integral is
$$\int_0^4\int_{-1}^{1} y^3 [\sin^2(x^2+y^2+(1-y^2)^2)
-\sin^2(x^2+y^2)]
dydx $$
Note that the integrand is odd in $y$ over its integration limit $y\in [-1,1]$, which makes the integral vanishing.


text:
Q: How to use nextPageToken in Google Apps Reseller API? I am writing a simple Java application that fetches all customer subscriptions from Google Apps Reseller using the Reseller API. However I am stuck at paging through the results as the max size is 100 per page and I cannot figure out the next page token. Here is the code so far. How do I use the setNextPageToken() and print all of the results?
public static void main(String[] args) throws IOException {
        GoogleCredential credentials = GoogleApiUtil.getCredentials();

        Reseller service = new Reseller.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials)
                .setApplicationName("ResellerDemo").build();

        boolean allResultsRead = false;
        String nextPageToken = null;
        while (!allResultsRead) {
            Subscriptions result = service.subscriptions().list()
                    .execute();
            List<Subscription> subscriptions = result.getSubscriptions();
            nextPageToken = result.getNextPageToken();
            if (subscriptions == null || subscriptions.size() == 0) {
                System.out.println("No subscriptions found.");
            } else {
                System.out.println("Subscriptions:");
                for (Subscription sub : subscriptions) {
                    System.out.printf("%s (%s, %s)\n",
                            sub.getCustomerId(),
                            sub.getSkuId(),
                            sub.getPlan().getCommitmentInterval());
                }
            }
            if (result.getNextPageToken() == null) {
                allResultsRead = true;

            } else {
                result.setNextPageToken(result.getNextPageToken());

            }

        }

A: This should work. When you implement the real thing, make sure you have retry with exponential back off.
public void retrieveAll() throws IOException, InterruptedException {

    GoogleCredential credentials = GoogleApiUtil.getCredentials();

    Reseller service = new Reseller.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials)
            .setApplicationName("ResellerDemo").build();

    String nextPageToken = null;

    do {
        Subscriptions subsList = service.subscriptions().list().setMaxResults(Long.valueOf(100)).setPageToken(nextPageToken)
                .execute();
        printSubscirptions(subsList);

        nextPageToken = subsList.getNextPageToken();

    } while(nextPageToken != null && !"".equals(nextPageToken));

}

private void printSubscirptions(Subscriptions subscriptions){
    System.out.println("Subscriptions:");
    for (Subscription sub : subscriptions.getSubscriptions()) {
        System.out.printf("%s (%s, %s)\n",
                sub.getCustomerId(),
                sub.getSkuId(),
                sub.getPlan().getCommitmentInterval());
    }

}


text:
Q: Creating a multi level comments system in asp.net mvc I'm currently working on a blog written in asp.net mvc. I have a table that stores comments with the following model
public partial class Comment
    {
        public int CommentId { get; set; }
        public string Comment { get; set; }
        public System.DateTime CommentDate { get; set; }
        public int AuthorId { get; set; }
        public int PostId { get; set; }
        public int CategoryId { get; set; }

        public virtual Category Category { get; set; }
        public virtual Post Post { get; set; }
        public virtual UserProfile UserProfile { get; set; }
    }

Currently the comment is still  a one-level comment i.e a user cannot reply to a comment. How can i implement a multilevel comment system in such a way that a comment can have a reply and that reply can have another reply and so on.

A: Add parentCommentId column which refers to the Comments table.
After that in each reply :

*

*If it is a direct reply to the post, leave parentCommentId column empty

*If it is a reply to a previously posted comment, put that comment id in this column.  In this case you can leave postid column empty or not. It depends on your favor!

A: first i need to excuse you for my bad English if you want a tree of comments as i understood like you comment and reply and you need to reply on my reply thats make u should add 1 more field you can call it subcomment id which it will be as an forign key to comment table " self relation " and this subcommenid will hold the parent comment ID

A: But essentially..
I don't know how your POST Class is defined.. Is it a collection? Or a simple class? If it's not a collection you want to make it as so..
Inside your Comment Class Change..
public virtual Post Post { get; set; }

to:
Public virtual ICollection<Post> Posts { get; set; }

or define it in another class private field..
This will defines the relationship and will be your navigation property as well..
So in your controller you can return both tables like such...
public ActionResult GetComments(int id)
{
  db.context.comments.Include("Posts").Where(c => c.CommentID == id).ToList();
}

A: You need create custom Htmlhelper / TreeView and pass data in to this helper. Data model will be according to Mahmoud Moravej.


text:
Q: Fontspec and Adforn I keep getting a strange error when I load adforn with my documents. It boils down to fontspec changing the encoding from U to TU, and then it throws me an error and automatically updated the encoding with defaults.
I have solved this by making a new file in my texmf called TUOrnementsADF.fd containing the same content as the Uornements one. I was wondering if there's a better way to solve this. (Or if this would have the maintainer fix the problem).
This only really bothers me because I use vim-latexsuite, and that automatically registers this as an error and takes me to the file the error comes from. Just an aside.
An MWE:
\documentclass{article}
\usepackage{adforn}
\usepackage{fontspec}

\begin{document}

Hi\adfast{1}
\end{document}

A: The problem is a small bug in adforn.sty, which does, at the beginning,
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{adforn}[2010/07/25 v1.0 adforn CFR]
\RequirePackage{pifont}
\Pifont{OrnementsADF}

but the last call should be braced. The effect is that OrnementsADF becomes the current font and fontspec tries to load it with the TU encoding, failing at the task. Calls of \adforn or \adfast in the document are not affected.
Workaround: load adforn after fontspec (or other packages that depend on it, such as polyglossia), but the quirk should be fixed like
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{adforn}[2010/07/25 v1.0 adforn CFR]
\RequirePackage{pifont}
{\Pifont{OrnementsADF}}

so the change in the current font, which is only necessary to load the .fd file, is not carried along at group end.
The same strategy is adopted at the end of pifont.sty:
[...]
\newcommand{\ding}{\Pisymbol{pzd}}
\def\dingfill#1{\Pifill{pzd}{#1}}
\def\dingline#1{\Piline{pzd}{#1}}
\newenvironment{dinglist}[1]{\begin{Pilist}{pzd}{#1}}%
  {\end{Pilist}}
\newenvironment{dingautolist}[1]{\begin{Piautolist}{pzd}{#1}}%
  {\end{Piautolist}}
{\Pifont{pzd}}
{\Pifont{psy}}
\endinput
%%
%% End of file `pifont.sty'.


text:
Q: My custom REST endpoint is returning double encoded JSON. How can I make it stop? Here is my current controller:
@RestResource(urlMapping='/monitor')
global with sharing class TheController {

    @HttpGet
    global static String doGet() {

        Map<String, Object> status = new Map<String, Object>();
        status.put('key', 'value');
        return JSON.serialize(status);
    }
}

But this controller double encodes my json.
I found that sObjects are automatically serialized in rest endpoints:

When returning sObjects they are automatically serialized to JSON:

With that in mind I tried a controller like this one:
@RestResource(urlMapping='/monitor')
global with sharing class TheController {

    @HttpGet
    global static Map<String, Object> doGet() {

        Map<String, Object> status = new Map<String, Object>();
        status.put('key', 'value');
        return status;
    }
}

but then received the following error:

Save error: Invalid type for Http* method:
   Map.Object

What is the correct way to format a response for my REST endpoint?

A: The serialization seems to require type information up front. So Map<String, String> would compile but is probably not what you want.
You can create simple inner classes with just properties and return graphs of those. I have implemented some REST APIs that way.
You can also do the serialization yourself by following this pattern:
@HttpGet
global static void get() {
    RestResponse res = RestContext.response;
    if (res == null) {
        res = new RestResponse();
        RestContext.response = res;
    }
    res.statusCode = 200;
    res.responseBody = Blob.valueOf(JSON.serialize(myObjectGraph()));
}

A: as an alternative to Keith C; I do the following (letting SFDC do the serializing for me)
 //  -------------------------------------------------------
 //  INNER CLASS ResponseWrapper : SFDC Apex Rest feature automatically serializes an instance of this class into JSON response to client
 //  -------------------------------------------------------
 global class ResponseWrapper {
    // my object graph goes in here
 }

  @HttpGet
  global static ResponseWrapper doGet () {      // corresponds to R in CRUD
  ResponseWrapper    respW    = new ResponseWrapper();
  RestRequest        restRqst    = System.RestContext.request;
  RestResponse      restResp    = System.RestContext.response;

  // do my GET operations, building up member variables within ResponseWrapper
  restResp.statusCode = 200; // if you have errors, set this to something else like 400
  return respW;  // sfdc rest will serialize this for you
}


text:
Q: Difference between Creating a new Result Source and configuring Search Result webpart Query I have a subsite where I would need to return results. The results will be similar to the out of the box Local SharePoint Sites except that results will be coming from a specific subsite.
I know that the Path: is both used in the resulting query regardless whether I define it in Result Source or the Search Result webpart. What are the differences between defining a new result source compared to simple defining it the query of the search result webpart? It seems like it will achieve the same.
The contents of either approach have already been crawled by the Local SharePoint Site. I read some articles saying that creating a new result source will create an index for the subsite that I want, but isn't the same thing happening if I simply define the path as the parameter in my search result webpart?

A: A simple explanation would be around reusability.
You can use the same filters in a Result Source and a query rule in a SRWP.  The benefit of a Result Source is that it can A) be set as the 'default' for that site and lower and B) can be reused in multiple SRWPs without having to write the query rule again and again (and have to change it multiple times when needed).
You can chain them so that the Result Source does most of the filtering and then the SRWP just adds a little more specific filtering at this specific location.


text:
Q: Is there a way to have a specific content based CSS for e.g. numbers Is there a way to put a check in SASS files or CSS files to check for the content inside a div:
For e.g.: If a div has numbers in it I want the content inside it to be aligned to the right and whereas if the div has text in it I want the content to be aligned to the left.
Is it possible. I see it happening on a lot of websites, and I pretty sure that they must not have hard-coded it that way.
Thanks in advance.

A: no. thats not possible. you need to check it somewhere else.
you could for example check the content in php code and then depending on the type of content add a css-class to the parent html-element.


text:
Q: Rotate screen depending on video width and height I'm currently detecting the width and height of a selected video by doing the following:
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
    mediaMetadataRetriever.setDataSource(this, mVideoUri);
    String height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
    String width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);

The activity in manifest:
<activity android:name=".TrimVideoActivity"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen"
        />

If I toast the the width and height it always returns w : 1920 h : 1080 no matter what the dimensions of the video are. I think it is returning the width and height of the device instead.
Is there something that I'm missing or doing wrong?

EDIT
By following the link that @VladMatvienko suggested I was able to get the correct width and height of the video file, this is how I implemented it:
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    Bitmap bmp = null;
    retriever.setDataSource(this, mVideoUri);
    bmp = retriever.getFrameAtTime();

    String videoWidth = String.valueOf(bmp.getWidth());
    String videoHeight = String.valueOf(bmp.getHeight());

Now I want to rotate the screen depending on the result (width/height), I tried it by doing the following:
int w = Integer.parseInt(videoWidth);
    int h = Integer.parseInt(videoHeight);

    if (w > h) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    } if(w < h) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    }

But, the screen always gets rotated to landscape, instead of being set to portrait when the width is smaller than the height?

A: I decided to add a answer explaining how I fixed this issue.
The issue with my initial approach:
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(this, mVideoUri);
String height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
String width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);

The problem with this is that the video might not have the metadata that I'm looking for, which will result a nullpointerexception.
To avoid this issue I can get one frame from the video (as a bitmap) and get the width and height from that bitmap by doing the following:
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
Bitmap bmp;
retriever.setDataSource(this, mVideoUri);
bmp = retriever.getFrameAtTime();

But, this brings up another issue, that you might not have. In my case I would like to get the first/nearest frame to the start, because if the screen was rotated during the capturing of the video, then the width/height of the frame will change, so I just added 1 to getFrameAtTime(1).

Now I can rotate the screen depending of the width and height of my video file by doing:
try {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    Bitmap bmp;
    retriever.setDataSource(this, mVideoUri);
    bmp = retriever.getFrameAtTime(1);

    int videoWidth = bmp.getWidth();
    int videoHeight = bmp.getHeight();

    if (videoWidth > videoHeight) {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
    if (videoWidth < videoHeight) {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

}catch (RuntimeException ex){
    Log.e("MediaMetadataRetriever", "- Failed to rotate the video");
}

Of course the above will be called from within onCreate.
Hope this helps someone out there.


text:
Q: Iterative map reduce jobs. How to take reducer output and feed it to the next stage? Specifically, I am trying to fnd a way to compute the shortest path in a graph using map reduce. The one that I have come up with seems to require multiple rounds of map reduce. However, all the documentation I have read so far on Hadoop does not seem to clearly describe running map reduce jobs that have multiple stages.i.e. take the output from the reducer from the first stage and feed it as input to the mapper of the next stage. I am hoping something like his wold be allowed in Hadoop.

A: I have blogged about it here:
http://codingwiththomas.blogspot.com/2011/04/controlling-hadoop-job-recursion.html
This is even graph-algorithm related, you will end up with quite the same code.
The basic idea is that you have a counter which is going to be a measure of how many vertices have been update in a single mapreduce step. Then you schedule jobs again and again until you have no updated vertices anymore.
But seriously, MapReduce sucks for graph algorithms, use a better framework like Apache Hama for it.
Apache Giraph can be helpful for you as well.

A: Steve's answer is essentially correct.  For each step, you'll set the inputformat's input directory to the previous step's output directory.  Repeat this for as many iterations as you require.  However, Map-Reduce is a poor abstraction for iterative graph problems.  Take a look at Apache Giraph, which is a designed particularly for these types of situations.  You'll find your problem easier to express and the iterative nature of the problem is taken care of for you.

A: I think you can refer this example : http://famousphil.com/blog/2011/06/a-hadoop-mapreduce-solution-to-dijkstra%E2%80%99s-algorithm/


text:
Q: Dynamic category select So I have a dropdown where user selects a category. But I want to make it more user firendly so that it automaticaly selects the category id and post it in that category.
My cshtml:

    @Html.LabelFor(model => model.category.Id, "category", htmlAttributes: new { @class = "control-label col-md-2" })

    @Html.DropDownList("CategoryId", null, htmlAttributes: new { @class = "form-control", required = "" })
    @Html.ValidationMessageFor(model => Model.category, "", new { @class = "text-danger" })

My controler:
public ActionResult Create()
{
    ViewBag.CategoryId = new SelectList(db.Categorys, "Id", "Title", db.Categorys);
    return View();
}

[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Title,CategoryId,Content")] Thread thread)
{
    if (ModelState.IsValid)
    {
        thread.ApplicationUserId = User.Identity.GetUserId();
        db.Threads.Add(thread);
        db.SaveChanges();
        return RedirectToAction("Post", new { @id = thread.Id });
    }
    ViewBag.CategoryId = new SelectList(db.Categorys, "Id", "Title", thread.Id);
    return View(thread);
}

What should I do to make it dynamic, so that the user don't have to select a category id, but the select element does it by itself.

A: Use DropDownListFor and specify appropriate model property to store your valun in and it will do it for you.
@Html.DropDownListFor(m => m.CatId, Model.List, null) where CatId is a property in your model, List is a list of items to show as values in select element. Instead of null in the third parameter you can specify additional html attributes for this element (e.g. id, class)


text:
Q: react-router v4 NavLink is not changing URL when I started the project I did not work with create-react-app
I built the basic react-flux app like always which is with browserify and babelify and all
and the react-router v4 was working and no problem happened
then I immigrated to create-react-app env
to use the testing and building tools that is offered
and I installed all packages that I used previously properly
but react-router v4 had a problem
when I click NavLink, it does not change the URL
but when I change the URL manually it works fine
I use BrowserRouter like this:
    <BrowserRouter history={HashRouter}<App /></BrowserRouter>,document.getElementById("root"));

And NavLink like this:
    <NavLink className="nav-link" activeClassName="active" to={"/drugs"}>
                            <i className="fa fa-medkit" aria-hidden="false"/>
                             Drugs
                        </NavLink>

And Router like this:
   <Switch>
                <Route exact={true} path="/" component={Patients}/>
                <Route exact path="/drugs" component={Drugs}/>
                <Route exact path="/settings" component={Settings}/>
                <Route path="*" component={Error}/>
            </Switch>

and thanks in advance.

A: Most likely your component does not update properly. This can happen if you inherit from React.PureComponent instead of React.Component or mess up with the method shouldComponentUpdate().
If you can't figure it out (you should), you can still pass the location object manually with the HOC withRouter from react-router-dom like so :
import { withRouter } from 'react-router-dom';

const Menu = ({ location }) => (
  <menu>
    <NavLink
      className="nav-link"
      activeClassName="active"
      location={location}
      to="/drugs"
    >
      <i className="fa fa-medkit" aria-hidden="false" />
       Drugs
    </NavLink>
  </menu>
);

export default withRouter(Menu);

Note: Most imports have been stripped out for clarity

A: The problem is <Navlink to={"/drugs"}. When you use {} You're indicating that you'll be using JS, and since "/drugs" is not valid js it fails.
Instead remove the {}.
<NavLink className="nav-link" activeClassName="active" to="/drugs">


text:
Q: How to backup history in Firefox? Firefox currently has a history page limit. In about:config:
places.history.expiration.transient_current_max_pages: 10322

I want to retain it completely. There are lot of useful information in that data. Is there a setting or extension that allows me to save old history automatically to my hard drive?

A: Simply open your History panel.
Then at the top left of the panel, click the menu "Import and Save". And there, the first line you find in that menu is... "Save". It saves all your history.
Simple. Direct. Without any need of a technical knowledge and without any need of an extension.
:-)
In the past there was the wonderful extension FEBE, from Chuck Baker which was the best to make backups of everything at once or feature by feature, and automatically (scheduled) as well as manually. But since Firefox 57 Quantum it doesn't work any more, like many other wonderful extensions which were awesome (Add Bookmark Here², CLEO, DownThemAll, FEBE, FireFTP, FlashGot, Location Bar Enhancer, OPIE, Roomy Bookmark Toolbar, Saved Password Editor, Show Parent Folder, TabMix Plus, etc, etc, etc). Conclusion : as many very old Firefox users which were faithful to Firefox from the very first days I have ended up by being definitely fed up and I have eventually dropped Firefox recently. All along these last 6 years the management team of Mozilla has taken the habit to turn the back to the users. That's why Firefox which was a wonderful browser with more than 80% of the netizens throughout the world at the end of the last decade has now fallen to a pitiful 10% of use among the different available browsers.
If instead of Firefox you use Cyberfox or Waterfox or Palemoon you can keep on using >>ALL<< these old awesome extensions that I cited above. But not in the native Firefox. So the best is to use Cyberfox or Waterfox or Palemoon instead of Firefox. You won't be disturbed nor worried... as they all are forks of Firefox in its former way to work BEFORE Quantum.

A: What does the places.history.expiration.transient_current_max_pages preference do in Firefox? According to this Mozilla: Places Expiration article:

places.history.expiration.max_pages: The maximum number of pages that may be retained in the database before starting to expire.

*

*Steps: As the question is with Linux, the following procedure is focused on Linux environment. But the procedure is same for Windows or MacOS but the Firefox installation path is different. Use any file manager or text editor to create and edit files. These steps are with command line.

*

*Find the Firefox executable. Type this command to find firefox executable: which firefox. The usual installation path will be /usr/bin/firefox.

*Change directory to /usr/lib/firefox.

*Create autoconfig.js file: touch ./defaults/pref/autoconfig.js. The file name is constant, don't use any other name. Add these lines in that file:

  //comments
  pref("general.config.filename", "mozilla.cfg");
  pref("general.config.obscure_value", 0);
  //END//

The mozilla.cfg file name can be any other name but it should be match with the very next step.
  * Create mozilla.cfg file: touch /usr/lib/firefox/mozilla.cfg. Add these lines in that file and change that value as you want:
  // IMPORTANT: Start your code on the 2nd line
  lockPref("places.history.expiration.transient_current_max_pages", 999999);

*

*Notes: The folder structure will be like this (other files are omitted):

/usr/lib/firefox
|
+-- mozilla.cfg
|
+-- defaults/pref
    |
    +-- autoconfig.js

Always remember to change those file permission with chmod 644 aka. -rw-r--r--. Kill all Firefox processes to make effect the changes. The mozilla.cfg file should have a comment at first line. lockPerf can be changed as following:

*

*pref(prefName, value) – If the user has changed the value, it will get reset every time the browser is started.

*defaultPref(prefName, value) – It can be permanently changed by the user.

*lockPref(prefName, value) – Locking a preference prevents a user from changing it.

See more options and details in this article: Customizing Firefox Using AutoConfig


text:
Q: node.js request module getaddrinfo error I am trying to hit http://api.openweathermap.org using my assigned apikey ,it is working fine with browser but when i am trying using request module it is giving me error:
code is
apiKey = 'cb1d43c417fce6fa41e4b2251d76fbf2';
city = 'mysore';
url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`;
var request = require('request');
request(url, function(err, response, body) {
  if (err) {
    console.log('error:', err);
  } else {
    console.log('body:', body);
  }
});

and the error is;
C:\Users\manu.varghese\node-weather>node index.js
error: { Error: getaddrinfo EAI_AGAIN api.openweathermap.org:80
at Object._errnoException (util.js:992:11)
at errnoException (dns.js:55:15)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)
code: 'EAI_AGAIN',
errno: 'EAI_AGAIN',
syscall: 'getaddrinfo',
hostname: 'api.openweathermap.org',
host: 'api.openweathermap.org',
port: 80 }

A: Can you try using different DNS servers? You can do it in Windows/Mac OS/ Linux or explicitly in Node:
let dns = require('dns');
dns.setServers(['8.8.8.8']);
8.8.8.8 is one of Google's DNS servers. You can try with whatever suits you.


text:
Q: dday ical and google calendar until problems Hi I have this ical (1.0 beta)
I have this code
IICalendarCollection iCal = iCalendar.LoadFromStream(fileStream);
foreach (var ic in iCal)
{
    foreach (var evt in ic.Events)
    {
        DateTime now = DateTime.UtcNow.Date;
        if (evt.Start.UTC.Date.CompareTo(now) >= 0 && evt.End.UTC.Date.CompareTo(now) >= 0)
        {
            foreach (var rule in evt.RecurrenceRules)
            {
                if (rule.Frequency == FrequencyType.Daily)
                {
                    // always false until is never set.
                    bool doesRepeatingEnd = DoesRepeatingEnd(rule);
                    if (doesRepeatingEnd)
                    {
                        TimeSpan until = now.Subtract(rule.Until);
                        int days = until.Days;
                    }
                    else { }
                } else if (rule.Frequency == FrequencyType.Weekly)
                {
                }
                else if (rule.Frequency == FrequencyType.Monthly)
                {
                }
                else if (rule.Frequency == FrequencyType.Yearly)
                {
                }

            }
    }   }
}

        private static bool DoesRepeatingEnd(IRecurrencePattern rule)
        {
            DateTime until = rule.Until;
            return until != DateTime.MinValue;
        }

I import a google calendar in(ical format)
BEGIN:VCALENDAR
PRODID:-//Google Inc//Google Calendar 70.9054//EN
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:PUBLISH
X-WR-CALNAME:
 Name X-WR-TIMEZONE:America/Washington
 BEGIN:VTIMEZONE
 TZID:America/Washington
 X-LIC-LOCATION:America/Washington
 BEGIN:DAYLIGHT
 TZOFFSETFROM:-0800
 TZOFFSETTO:-0700
 TZNAME:PDT
 DTSTART:19700308T020000
 RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU
 END:DAYLIGHT
 BEGIN:STANDARD
 TZOFFSETFROM:-0700
 TZOFFSETTO:-0800
 TZNAME:PST
 DTSTART:19701101T020000
 RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU
 END:STANDARD
 END:VTIMEZONE
 BEGIN:VEVENT
 DTSTART;VALUE=DATE:20110530
 DTEND;VALUE=DATE:20110531
 RRULE:FREQ=DAILY;UNTIL=20110604
 DTSTAMP:20110424T202756Z
 UID:fl16scis3l3qmhrrbb6uhkmo98@google.com
 CREATED:20110424T202406Z
 DESCRIPTION:
 LAST-MODIFIED:20110424T202406Z
 LOCATION:
 SEQUENCE:0
 STATUS:CONFIRMED
 SUMMARY:dd
 TRANSP:TRANSPARENT
 END:VEVENT
 END:VCALENDAR

as you can see I have  RRULE:FREQ=DAILY;UNTIL=20110604 but my code never picks it up rule.Until is always like the default datetime.
Anyone have any ideas?
Thanks

A: This is a bug in the current version of dday ical and will be fixed in future versions
 Google Repeating Task Until Time Bug


text:
Q: Surjective map on real projective space If $f$ is map of $\mathbf{RP}^2$, inducing an isomorphism in homology, then $f$ is surjective. How can one prove this, maybe using some kind of CW complex structure on it or how?

A: Suppose $f$ misses a point $p \in \Bbb R \mathrm{P}^2$. Then $f$ factors through $Y = \Bbb R \mathrm{P}^2 - \{p\}$:
$$
\Bbb R \mathrm{P}^2 \xrightarrow{g} Y \xrightarrow{i} \Bbb R \mathrm{P}^2
$$
$Y$ is homotopy equivalent to $S^1$. Consider the fundamental polygon of $\Bbb R \mathrm{P}^2$ to see this. This forces $g_* : H_1(\Bbb R \mathrm{P}^2) \to H_1(Y)$ to be trivial since $H_1(\Bbb R \mathrm{P}^2) \cong \Bbb Z_2$ and $H_1(Y) \cong \Bbb Z$.
It follows that $f_* = i_* \circ g_*$ cannot be an isomorphism.


text:
Q: List GitHub Branches Dynamically In Jenkins Jobs I'm working with jenkins 2.249.3 and active choices plugin - version 2.5.1
I'm trying to create an interactive job that allows users to select a git branch from which they will deploy the product.
I found some nice solutions on how to do that but from some reason I get empty list
the script goes like that:
def gitBranches = ("git ls-remote --heads git@github.com:org/repository.git").execute()

and then return gitBranches.text.readLines().collect {  it.split()[1].replaceAll('refs/heads/', '').replaceAll("\\^\\{\\}", '') }
I think that the git command does not success at all. I verified that when I run the same command from the jenkins server itself it works so I guess I don't understand something regarding the context in which the groovy script is running.

A: Ok... I got it and indeed it's ssh issue. I'll explain
In my jenkins server there was already ssh private key that was configured for ubuntu user while I needed to configure another key for jenkins user.
I generated a new ssh key and saved it under another name. (id_rsa_2)
Jenkins is running the script in kind of a sandbox/shell that does not load automatically all the keys under .ssh folder (Correct me If I'm saying something stupid). My workaround for that was writing a bash script that runs "ssh-add" command and than launches git ls-remote command.


text:
Q: TCPDF weird issue in CakePHP I am having a formatting issue with PDF generation with TCPDF in CakePHP.
It doesn't show the exact table & div structure as there in HTML.
Does anyone know the solution for it?
Thanks in advance.

A: I found my solution by changing my code to clean html into the tcpdf format means by using cell and multicell function of tcpdf.
Refrence : http://www.onemoretake.com/2009/03/09/tcpdf-variable-height-table-rows-with-multicell/

A: Code that i m sending u is for creating xls file and u just need to change some header prameter in it.

Just put this code in the head of your html file and it will force u to download automatically.But change the header according to pdf file


text:
Q: Tranquility server would not send data to druid I'm using imply-2.2.3. Here is my tranquility server configuration:
{
  "dataSources" : [
    {
      "spec" : {
        "dataSchema" : {
          "dataSource" : "tutorial-tranquility-server",
          "parser" : {
            "type" : "string",
            "parseSpec" : {
              "timestampSpec" : {
                "column" : "timestamp",
                "format" : "auto"
              },
              "dimensionsSpec" : {
                "dimensions" : [],
                "dimensionExclusions" : [
                  "timestamp",
                  "value"
                ]
              },
              "format" : "json"
            }
          },
          "granularitySpec" : {
            "type" : "uniform",
            "segmentGranularity" : "hour",
            "queryGranularity" : "none"
          },
          "metricsSpec" : [
            {
              "type" : "count",
              "name" : "count"
            },
            {
              "name" : "value_sum",
              "type" : "doubleSum",
              "fieldName" : "value"
            },
            {
              "fieldName" : "value",
              "name" : "value_min",
              "type" : "doubleMin"
            },
            {
              "type" : "doubleMax",
              "name" : "value_max",
              "fieldName" : "value"
            }
          ]
        },
        "ioConfig" : {
          "type" : "realtime"
        },
        "tuningConfig" : {
          "type" : "realtime",
          "maxRowsInMemory" : "50000",
          "windowPeriod" : "PT10M"
        }
      },
      "properties" : {
        "task.partitions" : "1",
        "task.replicants" : "1"
      }
    },
    {
      "spec": {
        "dataSchema" : {
          "dataSource" : "test",
          "parser" : {
            "type" : "string",
            "parseSpec" : {
              "timestampSpec" : {
                "column" : "timestamp",
                "format" : "auto"
              },
              "dimensionsSpec" : {
                "dimensions" : [
                  "a"
                ],
              },
              "format" : "json"
            }
          },
          "granularitySpec" : {
            "type" : "uniform",
            "segmentGranularity" : "hour",
            "queryGranularity" : "none"
          },
          "metricsSpec" : [
            {
              "type" : "count",
              "name" : "count"
            },
            {
              "type": "doubleSum",
              "name": "b",
              "fieldName": "b"
            }
          ]
        },
        "ioConfig" : {
          "type" : "realtime"
        },
        "tuningConfig" : {
          "type" : "realtime",
          "maxRowsInMemory" : "50000",
          "windowPeriod" : "P1Y"
        }
      },
      "properties": {
        "task.partitions" : "1",
        "task.replicants" : "1"
      }
    }
  ],
  "properties" : {
    "zookeeper.connect" : "localhost",
    "druid.discovery.curator.path" : "/druid/discovery",
    "druid.selectors.indexing.serviceName" : "druid/overlord",
    "http.port" : "8200",
    "http.threads" : "40",
    "serialization.format" : "smile",
    "druidBeam.taskLocator": "overlord"
  }
}

I have trouble sending data to the second datasoruce, test, specifically. I tried to send the below data to druid with python requests:

{'b': 7, 'timestamp': '2017-01-20T03:32:54.586415', 'a': 't'}

The response I receive:
b'{"result":{"received":1,"sent":0}}'

If you read my config file you will notice that I set window period to one year. I would like to send data in with a large time span to druid using tranquility server. Is there something wrong with my config or data?


text:
Q: Script to redirect if connection is established I have made this script that, if I have internet (checking with image) then it redirects, but it keeps images in cache, and if I have no internet then it still loads.

Loading...

The problem is the cache, it caches the image and then when I reload without internet it still tries to load. Does anyone know another way to fix it?

A: Append a random number to the img url so that the browser doesn't cache the image. See
Disable cache for some images

A: You could try something like this :

The point is to add a random/unique value at the end of the url so the request is never the same


text:
Q: Error: free(): invalid next size (fast): What is this strange error I'm getting? I'm compiling C++ using g++ on Ubuntu 10.10. It pops up randomly when I run the executable (maybe 2 times in 8 hours, with 10 compiles an hour). However, if I make clean and recompile it goes away most of the time.
*** glibc detected *** ./emailQueue.app: free(): invalid next size (fast): 0x0000000001c40270 ***
======= Backtrace: =========
/lib/libc.so.6(+0x774b6)[0x7f490d95e4b6]
/lib/libc.so.6(cfree+0x73)[0x7f490d964c83]
./emailQueue.app[0x401f47]
/lib/libc.so.6(__libc_start_main+0xfe)[0x7f490d905d8e]
./emailQueue.app[0x401cc9]
======= Memory map: ========
00400000-0040d000 r-xp 00000000 08:01 1311132                            /home/server/Projects/email/emailQueue.app
0060d000-0060e000 r--p 0000d000 08:01 1311132                            /home/server/Projects/email/emailQueue.app
0060e000-0060f000 rw-p 0000e000 08:01 1311132                            /home/server/Projects/email/emailQueue.app
01c40000-01c82000 rw-p 00000000 00:00 0                                  [heap]
7f4908000000-7f4908021000 rw-p 00000000 00:00 0
7f4908021000-7f490c000000 ---p 00000000 00:00 0
7f490ce52000-7f490ce5e000 r-xp 00000000 08:01 1051251                    /lib/libnss_files-2.12.1.so
7f490ce5e000-7f490d05d000 ---p 0000c000 08:01 1051251                    /lib/libnss_files-2.12.1.so
7f490d05d000-7f490d05e000 r--p 0000b000 08:01 1051251                    /lib/libnss_files-2.12.1.so
7f490d05e000-7f490d05f000 rw-p 0000c000 08:01 1051251                    /lib/libnss_files-2.12.1.so
7f490d05f000-7f490d075000 r-xp 00000000 08:01 1048770                    /lib/libz.so.1.2.3.4
7f490d075000-7f490d275000 ---p 00016000 08:01 1048770                    /lib/libz.so.1.2.3.4
7f490d275000-7f490d276000 r--p 00016000 08:01 1048770                    /lib/libz.so.1.2.3.4
7f490d276000-7f490d277000 rw-p 00017000 08:01 1048770                    /lib/libz.so.1.2.3.4
7f490d277000-7f490d28e000 r-xp 00000000 08:01 1051248                    /lib/libnsl-2.12.1.so
7f490d28e000-7f490d48d000 ---p 00017000 08:01 1051248                    /lib/libnsl-2.12.1.so
7f490d48d000-7f490d48e000 r--p 00016000 08:01 1051248                    /lib/libnsl-2.12.1.so
7f490d48e000-7f490d48f000 rw-p 00017000 08:01 1051248                    /lib/libnsl-2.12.1.so
7f490d48f000-7f490d491000 rw-p 00000000 00:00 0
7f490d491000-7f490d49a000 r-xp 00000000 08:01 1051244                    /lib/libcrypt-2.12.1.so
7f490d49a000-7f490d69a000 ---p 00009000 08:01 1051244                    /lib/libcrypt-2.12.1.so
7f490d69a000-7f490d69b000 r--p 00009000 08:01 1051244                    /lib/libcrypt-2.12.1.so
7f490d69b000-7f490d69c000 rw-p 0000a000 08:01 1051244                    /lib/libcrypt-2.12.1.so
7f490d69c000-7f490d6ca000 rw-p 00000000 00:00 0
7f490d6ca000-7f490d6e2000 r-xp 00000000 08:01 1051256                    /lib/libpthread-2.12.1.so
7f490d6e2000-7f490d8e1000 ---p 00018000 08:01 1051256                    /lib/libpthread-2.12.1.so
7f490d8e1000-7f490d8e2000 r--p 00017000 08:01 1051256                    /lib/libpthread-2.12.1.so
7f490d8e2000-7f490d8e3000 rw-p 00018000 08:01 1051256                    /lib/libpthread-2.12.1.so
7f490d8e3000-7f490d8e7000 rw-p 00000000 00:00 0
7f490d8e7000-7f490da61000 r-xp 00000000 08:01 1048743                    /lib/libc-2.12.1.so
7f490da61000-7f490dc60000 ---p 0017a000 08:01 1048743                    /lib/libc-2.12.1.so
7f490dc60000-7f490dc64000 r--p 00179000 08:01 1048743                    /lib/libc-2.12.1.so
7f490dc64000-7f490dc65000 rw-p 0017d000 08:01 1048743                    /lib/libc-2.12.1.so
7f490dc65000-7f490dc6a000 rw-p 00000000 00:00 0
7f490dc6a000-7f490dc7f000 r-xp 00000000 08:01 1048655                    /lib/libgcc_s.so.1
7f490dc7f000-7f490de7e000 ---p 00015000 08:01 1048655                    /lib/libgcc_s.so.1
7f490de7e000-7f490de7f000 r--p 00014000 08:01 1048655                    /lib/libgcc_s.so.1
7f490de7f000-7f490de80000 rw-p 00015000 08:01 1048655                    /lib/libgcc_s.so.1
7f490de80000-7f490df02000 r-xp 00000000 08:01 1051246                    /lib/libm-2.12.1.so
7f490df02000-7f490e101000 ---p 00082000 08:01 1051246                    /lib/libm-2.12.1.so
7f490e101000-7f490e102000 r--p 00081000 08:01 1051246                    /lib/libm-2.12.1.so
7f490e102000-7f490e103000 rw-p 00082000 08:01 1051246                    /lib/libm-2.12.1.so
7f490e103000-7f490e1eb000 r-xp 00000000 08:01 4853329                    /usr/lib/libstdc++.so.6.0.14
7f490e1eb000-7f490e3ea000 ---p 000e8000 08:01 4853329                    /usr/lib/libstdc++.so.6.0.14
7f490e3ea000-7f490e3f2000 r--p 000e7000 08:01 4853329                    /usr/lib/libstdc++.so.6.0.14
7f490e3f2000-7f490e3f4000 rw-p 000ef000 08:01 4853329                    /usr/lib/libstdc++.so.6.0.14
7f490e3f4000-7f490e409000 rw-p 00000000 00:00 0
7f490e409000-7f490e5c7000 r-xp 00000000 08:01 4851315                    /usr/lib/libmysqlclient.so.16.0.0
7f490e5c7000-7f490e7c7000 ---p 001be000 08:01 4851315                    /usr/lib/libmysqlclient.so.16.0.0
7f490e7c7000-7f490e7cc000 r--p 001be000 08:01 4851315                    /usr/lib/libmysqlclient.so.16.0.0
7f490e7cc000-7f490e816000 rw-p 001c3000 08:01 4851315                    /usr/lib/libmysqlclient.so.16.0.0
7f490e816000-7f490e817000 rw-p 00000000 00:00 0
7f490e817000-7f490e837000 r-xp 00000000 08:01 1048597                    /lib/ld-2.12.1.so
7f490ea15000-7f490ea1c000 rw-p 00000000 00:00 0
7f490ea33000-7f490ea37000 rw-p 00000000 00:00 0
7f490ea37000-7f490ea38000 r--p 00020000 08:01 1048597                    /lib/ld-2.12.1.so
7f490ea38000-7f490ea39000 rw-p 00021000 08:01 1048597                    /lib/ld-2.12.1.so
7f490ea39000-7f490ea3a000 rw-p 00000000 00:00 0
7fffb85b9000-7fffb85da000 rw-p 00000000 00:00 0                          [stack]
7fffb85ff000-7fffb8600000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted

A: We need the code, but that usually pops up when you try to free() memory from a pointer that is not allocated. This often happens when you're double-freeing.

A: If you are trying to allocate space for an array of pointers, such as
char** my_array_of_strings;  // or some array of pointers such as int** or even void**

then you will need to consider word size (8 bytes in a 64-bit system, 4 bytes in a 32-bit system) when allocating space for n pointers.  The size of a pointer is the same of your word size.
So while you may wish to allocate space for n pointers, you are actually going to need n times 8 or 4 (for 64-bit or 32-bit systems, respectively)
To avoid overflowing your allocated memory for n elements of 8 bytes:
my_array_of_strings = (char**) malloc( n * 8 );  // for 64-bit systems
my_array_of_strings = (char**) malloc( n * 4 );  // for 32-bit systems

This will return a block of n pointers, each consisting of 8 bytes (or 4 bytes if you're using a 32-bit system)
I have noticed that Linux will allow you to use all n pointers when you haven't compensated for word size, but when you try to free that memory it realizes its mistake and it gives out that rather nasty error.  And it is a bad one, when you overflow allocated memory, many security issues lie in wait.

A: I encountered the same problem, even though I did not make any dynamic memory allocation in my program, but I was accessing a vector's index without allocating memory for it.
So, if the same case, better allocate some memory using resize() and then access vector elements.

A: It means that you have a memory error.  You may be trying to free a pointer that wasn't allocated by malloc (or delete an object that wasn't created by new) or you may be trying to free/delete such an object more than once.  You may be overflowing a buffer or otherwise writing to memory to which you shouldn't be writing, causing heap corruption.
Any number of programming errors can cause this problem.  You need to use a debugger, get a backtrace, and see what your program is doing when the error occurs.  If that fails and you determine you have corrupted the heap at some previous point in time, you may be in for some painful debugging (it may not be too painful if the project is small enough that you can tackle it piece by piece).

A: I encountered such a situation where code was circumventing STL's api and writing to the array unsafely when someone resizes it. Adding the assert here caught it:
void Logo::add(const QVector3D &v, const QVector3D &n)
{
 GLfloat *p = m_data.data() + m_count;
 *p++ = v.x();
 *p++ = v.y();
 *p++ = v.z();
 *p++ = n.x();
 *p++ = n.y();
 *p++ = n.z();
 m_count += 6;
 Q_ASSERT( m_count <= m_data.size() );
}

A: I encountered a similar error. It was a noob mistake done in a hurry. Integer array without declaring size int a[] then trying to access it.
C++ compiler should've caught such an error easily if it were in main. However since this particular int array was declared inside an object, it was being created at the same time as my object (many objects were being created) and the compiler was throwing a free(): invalid next size(normal) error.
I thought of 2 explanations for this (please enlighten me if anyone knows more):
1.) This resulted in some random memory being assigned to it but since this wasn't accessible it was freeing up all the other heap memory just trying to find this int.
2.) The memory required by it was practically infinite for a program and to assign this it was freeing up all other memory.
A simple:
    int* a;
    class foo{
    foo(){
       for(i=0;i<n;i++)
           a=new int[i];
     }

Solved the problem. But it did take a lot of time trying to debug this because the compiler could not "really" find the error.


text:
Q: Java MongoDB : updating multiple documents at a time I have a following schema
Id:
date_created:
vars: {
      NAME:
      VALUE:
      EDITABLE:
      .....

}

*

*By definition Id is unique and could be like A, B, C, AA, AB, ....

*I have over a million documents like these, all unique documents

*Lets say I want to update VALUE in vars of subset of documents which qualify the Id provided to me as a list.
Using the api, I am not sure which api I can use to do multiple document updates qualifying the criteria where {Id: {$in: [A, B, X, Y, ...]}}
Please help

A: Use this version of the update method and set the multi parameter to true.  Otherwise the update will only be applied to the first matched document.


text:
Q: How to make only some url [other than mydomain] in my webview app open in browser? I would like to make any url other than my domains url to be opened in browser, for example if the user clicks a link like "https://www.google.com/(variable)" in my webview app , it should be opened in their browser not inside my webapp.
Please help me to do so In Kotlin


text:
Q: Is it possible to do server push in a desktop-scope event queue in ZK? I'm quite new to ZK and the concept of event queues. What I'm trying to do is run a long operation in the server and update the UI of the progress in real-time, instead of blocking the UI while the long operation runs. So for example, if there are 3 tasks (this number is not fixed) to do in the long operation, it should update the UI by updating a "log trace" textbox and a progress bar that same number of times.
My code structure looks like:
if (EventQueues.exists("longop")) {
     print("It is busy. Please wait");
     return; //busy
   }

   EventQueue eq = EventQueues.lookup("longop"); //create a queue
   String result;

   //subscribe async listener to handle long operation
   eq.subscribe(new EventListener() {
     public void onEvent(Event evt) {
       if ("doLongOp".equals(evt.getName())) {
         //simulate a long operation
          doTask1();
          eq.publish(new Event("printStatus", null, "Task1 completed."));
          doTask2();
          eq.publish(new Event("printStatus", null, "Task2 completed."));
          doTask3();
          eq.publish(new Event("printStatus", null, "Task3 completed."));
          result = "success";
          eq.publish(new Event("endLongOp")); //notify it is done
       }
     }
   }, true); //asynchronous

   //subscribe a normal listener to show the resul to the browser
   eq.subscribe(new EventListener() {
     public void onEvent(Event evt) {
       if("printStatus".equals(evt.getName())) {
          printToTextbox((String)evt.getData()); //appends value to the log textbox
       }
       if ("endLongOp".equals(evt.getName())) {
         print(result); //show the result to the browser
         EventQueues.remove("longop");
       }
     }
   }); //synchronous

   eq.publish(new Event("doLongOp")); //kick off the long operation

This didn't work. All the printStatus events happen AFTER the long operation is finished. The only thing this fixed is that the UI is not getting blocked whenever the long operation runs. I was assuming that since the long operation thread is asynch, it will still send the events to the queue and the synch UI thread will be able to handle them as soon as they happen. So after several hours of trial and error, and after noticing that the server push is NOT used in a desktop scope queue, I changed the scope to application and explicitly enabled server push:
EventQueue<Event> eq = EventQueues.lookup("longop", EventQueues.APPLICATION, true);
desktop.enableServerPush(true);

it just worked. I know that ZK CE only has the client polling, which is fine for my use case. But why is it that in desktop scope, server push is not used? How can we accomplish such task if we don't want the queue to be shared application-wide? I want each desktop to have their own event queue.
It might also be worth mentioning that I have enabled the event thread. And that I tried disabling it but the result was the same. So it looks to me that it doesn't affect my problem.
Any help is greatly appreciated.
PS: I am using ZK CE 7.0.3

A: There are many possible solutions for your situation.
Please take a look at this section of ZK documents.
You can use the piggyback, but when the user doesn't do anything, you also have no updates on the screen.
So I suggest go for the echoEvents.
So you have to do task 1, update screen and echo onTask2.
In OnTask2 do your stuff, update screen and echo onTask3.
And for onTask3 do task 3 and update the screen.
Edit :
The scope doesn't have to be application scope.  The application scope event queue has already server push build in (And I believe Session also). For the desktop you have to do it manually(or other approach). (your desktop.enableServerPush isn't needed for application scope)
If you want to work simple with the eventqueue look here.
Use the EventQueue.subscribe(EventListener, EventListener) what is the async and sync Eventlistener.
The only thing is, in the Sync listener you need to call your Task 2 with again the sync listener for refreshing GUI and start task 3 in same way.
The other way is passing the desktop to the async listener so you can enable (and disable) server push there.(async listener never has reference to desktop, it's a complete new thread)


text:
Q: Elmish App: Change  style dynamically Version
    nuget Fable.Core ~> 3
    nuget Fable.Elmish ~> 3

How to change body style in elmish app?

A: You can access the Dom through the Fable.Import.Browser module.
Try e.g.,
open Fable.Import

Browser.document.body.style.fontSize <- "20px"

or
Browser.document.body.classList.add("my-class")
Browser.document.body.classList.remove("my-class")


text: Q: Why do the researchers usually study the collection of **nonempty** closed subsets? In the research field of hypertopologies, researchers usually study on nonempty closed subsets of a topological space, although I have seen, but a very few books or articles, where the authors have studied the collection of closed subsets including the empty subset. I am curious, why do the researchers usually study the collection of nonempty closed subsets? Is there any particular purpose behind it? What I think is: while the application of hypertopologies in optimization, nonlinear analysis, well-posed problems, etc. authors don't face the empty set; however, I have not gone thoroughly through the application part of hypertopologies, what I think is my guess.


text:
Q: How to display HTML-like table data on iPhone? I have a set of data in a matrix which I would like to display in my iPhone app with all of the rows and columns intact. Everything I can find on the web dealing with "tables iPhone" gives me information on UITableView, which only lets you show a list of items to the user - not an actual table in the HTML sense. What's the best way on the iPhone to display an actual table of data to the user, with column & row headings and table cells?

A: The solution that I found was simply to use a UIWebView. Then I can build the HTML table dynamically and load it into the web view.

A: The UITableView class was specifically designed to only show one column at a time due to the small size of the screen. If the data of your application absolutely needs to be laid out in one big grid on one screen the right way to do it, would be to add each cell as a subview to a custom view. Then implement the layoutSubviews method on your custom view to lay out the frames of the subviews in the grid you want.


text:
Q: MySQLi associative array of results in PHP 5.2.6 Is there a way to fetch an associative array of results in MySQLi using PHP 5.2.6?
I know is PHP 5.3+ you can use get_result(). I know there is bind_result() in PHP 5.2.6 although there can be any number of columns in the query (not a set number.)
Been pulling my hair out over this one, ANY help will be appreciated!

A: Procedural :
mysqli_fetch_assoc ( mysqli_result $result )

Object Oriented :
mysqli_result::fetch_assoc ( void )

More info : http://php.net/manual/en/mysqli-result.fetch-assoc.php

A: Your friend is mysqli_fetch_assoc.It Fetches a result row as an associative array.
From the doumentation..
Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in resultset


text:
Q: Proving inequality $(x^2+y^2)(y-1)+yx-y^2<0$ I have an inequality which came out of Lyapunov function for system of ODE's:  $$(x^2+y^2)(y-1)+yx-y^2<0.$$  To prove stability of my solution, I have to prove that the inequalty is true in area $0<x^2 +y^2<1$. I know it must be simple, but I am still in trouble. Any help is appreciated.

A: If $x = y$, then $$(x^2 + y^2)(y - 1) + yx - y^2 = 2x^2(x - 1) < 0$$ since $x < 1$. Now suppose $x \neq y$. If $x$ and $y$ are positive, then $0 < x^2 < x$ and $y^3 < y^2$, thus
\begin{align}(x^2 + y^2)(y - 1) + yx - y^2 &= x^2y + y^3 - x^2 - y^2 + yx - y^2\\
& < x^2y - x^2 - y^2 + yx \\
& < 2xy - (x^2 + y^2)\\
& < 0.\end{align}
If $x < 0 < y$ or $y < 0 < x$, then $yx - y^2 = y(x - y) < 0$; since $(x^2 + y^2)(y - 1) < 0$ (as $y < 1$) we have $(x^2 + y^2)(y - 1) + yx - y^2 < 0$. Finally, if $x$ and $y$ are both negative, then $y^3 < 0 < y^2$ and $x^2 > 0 > x$; like in the case when $x$ and $y$ are both positive, we have
$$(x^2 + y^2)(y - 1) + yx - y^2 < x^2y - x^2 - y^2 + yx < 2xy - (x^2 + y^2) < 0.$$


text:
Q: Make Box Around Page Red I have used …
\usepackage{fancybox}
\fancypage{}{\fbox}

… to put a box around my text on every page including header and footer. It looks how I want it, except for the color. How do I make it red instead of black? I am using LuaLaTeX to compile.

A: I figured it out. I used: \fancypage{}{\fcolorbox{red}{white}}


text:
Q: Конкатенация массивов и их преобразование в SQLAlchemy У меня есть следующий PostgreSQL запрос:
WITH sub_query AS (
    SELECT vi.idvalfield,
           vi.value::text
    FROM valueint_value AS vi
    UNION
    SELECT vt.idvalfield,
           vt.value::text
    FROM valuetext_value AS vt
)

SELECT
       sq.idvalfield,
       sq.value
FROM sub_query AS sq
         JOIN valuefield AS vf ON vf.idvalfield = sq.idvalfield
         JOIN event e on vf.idevent = e.idevent
WHERE NOT (e.idevent || array[]::uuid[]) && (SELECT array_agg(e.idevent) AS id_event
                                              FROM sub_query AS sq
                                                       JOIN valuefield AS vf ON vf.idvalfield = sq.idvalfield
                                                       JOIN event e on vf.idevent = e.idevent
                                              WHERE (idtable = 41 AND sq.value = 222)
                                                 OR (idtable = 43 AND sq.value = 18)
);

Я описал CTE. Количество таблиц в UNION меняется поэтому описал динамически:
from sqlalchemy.dialects import postgresql
from sqlalchemy import or_, and_
from sqlalchemy import cast, Table, Text
from sqlalchemy.dialects.postgresql import array_agg, array, ARRAY, UUID

models_view = [
        session.query(
            model.c.idvalfield.label('id_value'),
            cast(model.c.value, Text).label('value')
        ).filter(model.c.idvalfield.in_(id_fields))
        for model, id_fields in model_values.items()
    ]

cte_union_view = models_view[0].union_all(*models_view[1:]).cte()

Затем описал подзапрос в WHERE:
filtered_event = session.query(array_agg(Event.idevent))\
        .select_from(cte_union_view)\
        .join(Valuefield, cte_union_view.c.id_value == Valuefield.idvalfield)\
        .join(Event, Event.idevent == Valuefield.idevent)\
        .filter(or_(and_(Valuefield.idtable == 41, cte_union_view.c.value == '222'),
                    and_(Valuefield.idtable == 43, cte_union_view.c.value == '18'))).subquery()

Описал основной запрос:
event_all = session.query(cte_union_view)\
        .join(Valuefield, cte_union_view.c.id_value == Valuefield.idvalfield)\
        .join(Event, Event.idevent == Valuefield.idevent).all()

Но у меня не получается описать само условие WHERE:
WHERE NOT (e.idevent || array[]::uuid[]) && (SELECT array_agg(e.idevent)

Пробовал:
filter(cast([Event.idevent + array([])], ARRAY(UUID)).in_(filtered_event))
and
filter(cast([array([Event.idevent]) + array([])], ARRAY(UUID)).in_(filtered_event))

Но это не работает. Кто знает, как можно это описать на ORM?

A: В общем, покопавшись в алхимии нашел способ решения. Может будет кому-то полезен.
Преобразование UUID в массив UUID'ов
(e.idevent || array[]::uuid[])

можно выполнить используя literal_column:
literal_column('ARRAY[]::uuid[]').op('||')(Event.idevent)

И теперь весь блок WHERE можно описать так:
.filter(uuid_event_arr.notin_(filtered_event)).all()

Но, на самом деле оказалось проще переписать подзапрос в WHERE, без функции array_agg(). А это в свою очередь упростить построение запроса средствами алхимии:
filtered_event = session.query(Event.idevent)\
        .select_from(cte_union_view)\
        .join(Valuefield, cte_union_view.c.id_value == Valuefield.idvalfield)\
        .join(Event, Event.idevent == Valuefield.idevent)\
        .filter(and_(Valuefield.idtable == 41, cte_union_view.c.v_text == '222'))

views_value = session.query(cte_union_view)\
        .join(Valuefield, cte_union_view.c.id_value == Valuefield.idvalfield)\
        .join(Event, Event.idevent == Valuefield.idevent)\
        .filter(Event.idevent.notin_(filtered_event)).all()


text:
Q: How to push data into a nested array in firestore? How can i do this?
I have a data stucture for each user in a user collection, I have created my own schema for the user object stored in the collection.
I want to have a favoriteMovies collection initalised into this object so that i can add movie objects inside.
Heres an example of what im trying to do :

      async function signUp(email, password){
        const {user} = await auth.createUserWithEmailAndPassword(email, password)

        // initialise the schema for the data
        const userInitialised = await db.collection('users').doc(user.uid).set(userSchemaObject(user.uid))
        return userInitialised;

      }

Then the schema so far:

    export default function userSchemaObject(uuid){
      return {
        uuid,
        favmovies:[]
      }
    }

A:
I'm asking how to push data to a nested array

From your question and comment, your favmovies field should be of type Array and does not seem to be "nested". Therefore you should simply use arrayUnion() in order to push data to this Array.
The following code demonstrates how to create a doc with an empty Array field, then, later, how to push a value.
const db = firebase.firestore();

const newDocRef = db.collection('test').doc();

newDocRef
    .set({
      uuid: 'uuid_value',
      favmovies: [],
    })
    .then(() => {
      newDocRef.update({
        favmovies: firebase.firestore.FieldValue.arrayUnion('movie1'),
      });
    });

Note that you can pass several elements to the arrayUnion() method.
newDocRef.update({
    favmovies: firebase.firestore.FieldValue.arrayUnion(
      'movie1',
      'movie2'
    ),
});