text:
Q: Gradle '+' dependencies (dynamic version) only finals? I'm wondering if I can just use the final, non-beta subset of dependencies, when using dynamic versions, e.g.
 testCompile group: 'junit', name: 'junit', version: '4.+'

downloads http://repo1.maven.org/maven2/junit/junit/4.12-beta-1/junit-4.12-beta-1.jar, but I would like to use any final JUnit 4 version.
How is that possible?

A: version: 'latest.release' gives the latest release version. There isn't currently a way to get the latest 4. release version.


text:
Q: htaccess redirect from http to https + GET param I'm trying to edit my .httaccess configuration. I want redirect everythink to https, but if I try this, what I found on stackoverflow:
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

It wont redirect.
Now my .htaccess looks like:
RewriteEngine On

# ignore all existing files and directories for rewriting
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule ^([\d+^/]*)$ /index.php?id=$1 [QSA,L]
RewriteRule ^([\w+^/]*)$ /index.php?name=$1 [QSA,L]

Rewrite rules like:
^([\d+^/]*)$ /index.php?id=$1 [QSA,L]

working well if I want

*

*www.mydomain.com/523

it is like

*

*www.mydomain.com/index.php?id=523

So how can I append my code to redirect from
http:// to https:// and my older rewrite rules will still work?

A: Try  :
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI [NE,L,R]
  # ignore all existing files and directories for rewriting
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([\d+^/]*)$ /index.php?id=$1 [QSA,L]
RewriteRule ^([\w+^/]*)$ /index.php?name=$1 [QSA,L]

A: I've solved this for GET params:
RewriteEngine On

# ignore all existing files and directories for rewriting
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule ^([\d+^/]*)$ https://%{HTTP_HOST}/index.php?id=$1 [QSA,L]
RewriteRule ^([\w+^/]*)$ https://%{HTTP_HOST}/index.php?name=$1 [QSA,L]

But I can't solve it for homepage and all other pages. I'm using JS location.replace instead. If someone will know how to set .htaccess to do these things synchronous:

*

*redirect every files into https

*and all digits and words after slash on homepage (example.com/63) redirect to https://%{HTTP_HOST}/index.php?id=$1 (as GET param)

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Signal 11: Segmentation fault" error after switching PostgreSQL Alpine image to Debian with upgrade from 12.3 to 12.6 I have a PostgreSQL database for some sensoric data on my Raspberry Pi. It runs on the postgres:12-alpine tag without automatic updates yet. Before the update, I got the following version string:
('PostgreSQL 12.3 on arm-unknown-linux-musleabihf, compiled by gcc (Alpine 9.3.0) 9.3.0, 32-bit',)

After I noticed that it was a bit out of date, I pulled the latest image with the following version string:
('PostgreSQL 12.6 on arm-unknown-linux-musleabihf, compiled by gcc (Alpine 10.2.1_pre1) 10.2.1 20201203, 32-bit',)

This worked, but I noticed that new inserted sensor data got a timestamp from 2038 when using NOW(). It seems complicated to solve with Alpine, maybe also an Alpine issue. I already had trouble with issues created by their musl usage. Since the normal image is not too much larger (109MB vs 62MB), I switched to the regular postgres:12 image.
Since the container was started with the normal Debian image, the startup failed:
postgres_1  | PostgreSQL Database directory appears to contain a database; Skipping initialization
postgres_1  |
postgres_1  | 2021-03-31 17:00:05.213 UTC [1] LOG:  starting PostgreSQL 12.3 on arm-unknown-linux-musleabihf, compiled by gcc (Alpine 9.3.0) 9.3.0, 32-bit
postgres_1  | 2021-03-31 17:00:05.214 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres_1  | 2021-03-31 17:00:05.214 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres_1  | 2021-03-31 17:00:05.226 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1  | 2021-03-31 17:00:11.083 UTC [1] LOG:  startup process (PID 20) was terminated by signal 11: Segmentation fault
postgres_1  | 2021-03-31 17:00:11.084 UTC [1] LOG:  aborting startup due to startup process failure
postgres_1  | 2021-03-31 17:00:14.480 UTC [1] LOG:  database system is shut down
pms_postgres_1 exited with code 1

Same issue with the Debian image:
postgres_1  | PostgreSQL Database directory appears to contain a database; Skipping initialization
postgres_1  |
postgres_1  | 2021-03-31 17:11:19.733 UTC [1] LOG:  starting PostgreSQL 12.3 (Debian 12.3-1.pgdg100+1) on arm-unknown-linux-gnueabihf, compiled by gcc (Debian 8.3.0-6) 8.3.0, 32-bit
postgres_1  | 2021-03-31 17:11:19.738 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres_1  | 2021-03-31 17:11:19.738 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres_1  | 2021-03-31 17:11:19.752 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1  | 2021-03-31 17:11:28.520 UTC [1] LOG:  startup process (PID 27) was terminated by signal 11: Segmentation fault
postgres_1  | 2021-03-31 17:11:28.520 UTC [1] LOG:  aborting startup due to startup process failure
postgres_1  | 2021-03-31 17:11:35.024 UTC [1] LOG:  database system is shut down
pms_postgres_1 exited with code 1

It's also not working with the latest 12.6 release. I'm assuming that the problem was, I switched from Alpine to Debian AND also updated the PostgreSQL version with the pull. So PSQL 12.3 on Alpine was upgraded to PSQL 12.6 on Debian.
Why does this Segmentation fault error occur and how can I fix it?
My docker-compose.yml:
version: '2.4'
volumes:
  #postgres-data_new:
  postgres-data:

services:
  postgres:
    image: postgres:12.6
    #image: postgres:12.3-alpine
    #image: postgres:12-alpine
    restart: always
    volumes:
      - postgres-data:/var/lib/postgresql/data
      - ./create-tables.sql:/docker-entrypoint-initdb.d/create-tables.sql
    environment:
      POSTGRES_PASSWORD: xx
      POSTGRES_DB: xxx
    ports:
      - 5432:5432

create-tables.sql just creates a very basic measure data table:
create table if not exists sensors(
    id SERIAL PRIMARY KEY,
    soilMoisture NUMERIC NOT NULL,
    temp NUMERIC NOT NULL,
    dateTime timestamp NOT NULL
);

A: It seems that the problem is an outdated libseccomp  version on the host: libseccomp 2.4.2 or newer and Docker to 19.03.9 or newer are required. But my RPI has just 2.3.3 from the repos:
# dpkg -l | grep libseccomp
ii  libseccomp2:armhf                   2.3.3-4                             armhf        high level interface to Linux seccomp filter

There are two ways to fix this, but only for new containers with fresh volumes. I still couldn't get my existing database from the volume working with that.
#1 Install a newer version manually and bypass the package manager
At least until the repos got updated. I guess this will happen after some time, then we can use the version provided by Raspbians repos again.
wget http://ftp.us.debian.org/debian/pool/main/libs/libseccomp/libseccomp2_2.5.1-1_armhf.deb
sudo dpkg -i libseccomp2_2.5.1-1_armhf.deb

#2 Disable it in docker-compose.yml as workaround
security_opt:
  - seccomp:unconfined

But this will reduce the security of the host against malicious code in the container, so updating the library seems to be a more secure solution.


text:
Q: Typescript ignores types when resolving promise I just spent around an hour debugging a type error in my code that boiled down to this:
function foo(): Promise<string> {
  return new Promise((resolve, reject) => {
    resolve();
  });
}

I'm very disappointed that Typescript didn't do its one job and detect this error. Why didn't it?

A: This is, unfortunately, a TypeScript design limitation (see microsoft/TypeScript#22040).    The standard library's typing for the Promise constructor's construct signature is the following:
new <T>(executor: (
  resolve: (value?: T | PromiseLike<T>) => void,
  reject: (reason?: any) => void
) => void): Promise<T>;

You can see that resolve()'s argument is declared to be optional, whether or not undefined is assignable to the type T.  Presumably if you want a Promise<void>, a Promise<undefined>, or a Promise<string | undefined>, or anything where undefined is a valid T, then that's fine, since resolve() is similar to resolve(undefined).  But, as you noticed, if you want a Promise<string>, it's unfortunate that resolve() is accepted.
This can be addressed by tweaking the standard library typings, but unfortunately previous attempts to fix this (see microsoft/TypeScript#22772) resulted in too many breaking changes in existing TypeScript code, so they didn't want to actually push such changes upstream.  Too bad.

Luckily, if you want to fix this in your own code, you can use declaration merging to add a constructor signature overload that will take precedence.  The particular version of the constructor signature you use depends on your use case.  If you want you can always prohibit zero-argument resolve() and require that people write resolve(undefined) if that's what they want:
declare global { // comment out this line if not in a module
  interface PromiseConstructor {
    new <T>(executor: (
      resolve: (value: T | PromiseLike<T>) => void, // value is not optional
      reject: (reason?: any) => void) => void
    ): Promise<T>;
  }
} // comment out this line if not in a module

( Note that PromiseConstructor is in global scope, so if your code is in a module you need to use global augmentation with declare global to get the above to work. If you're already in global scope you should leave out the declare global block. )
Or you can try to get more clever you can write a version of the signature that allows resolve() with no arguments if and only if undefined is assignable to T:
declare global {
  type PossiblyOptional<F extends (a: any) => any> = F extends (...a: infer A) => infer R ?
    undefined extends A[0] ? (...a: Partial<A>) => R : F : never;

  interface PromiseConstructor {
    new <T>(executor: (
      resolve: PossiblyOptional<(value: T | PromiseLike<T>) => void>,
      reject: (reason?: any) => void) => void
    ): Promise<T>;
  }
}

Let's use that latter type and check the behavior of some example code:
function foo(): Promise<string> {
  return new Promise((resolve, reject) => { resolve(); }); // error!
  // Expected 1 arguments, but got 0 -----> ~~~~~~~~~
}

function bar(): Promise<string | undefined> {
  return new Promise((resolve, reject) => { resolve(); }); // okay
}

That's better, right?  Your foo() implementation generates the desired error, while a similar bar() implementation whose return type is Promise<string | undefined> does not.

Okay, hope that helps; good luck!
Playground link to code


text:
Q: Cannot in display Amcharts in a div I am plotting Amcharts in a particular div in my html.The problem is I receive the data through ajax and try to plot it in that div (mainchart) but I am successfully receiving the data but unable to show the graph.I am pretty sure it has something to do with the width and height of the div. But not sure how to identify it .
HTML div is mainchart for the graph

    <row>

Main Chart Area

    </row>

CSS class for right
.right{
  display : flex;
  justify-content : center;
  align-items : center;
  background-image: url("htmlbackground.jpg");
  height : 100%;
  color : #3d231b;
}

JS to plot graph
var chart = AmCharts.makeChart("mainchart", {
                  "type": "stock",
                  "theme": "light",
                     "dataProvider": data,

                  "dataDateFormat": "YYYY-MM-DD",
                  "seriesField": "day",
                  "seriesValueFields": ["a", "c"],
                  "seriesGraphTemplate": {
                    "lineThickness": 2,
                    "type": "smoothedLine",
                    "useDataSetColors": false,
                    "bullet": "round"
                  },

                  "categoryAxesSettings": {
                    "minPeriod": "mm"
                  },

                  "dataSets": [{
                    "dataProvider": data,
                    "categoryField": "time"
                  }],

                  "panels": [{

                      "valueAxes": [ {
                        "title":"Values"
                        }],
                      "listeners": [{
                           "event": "drawn",
                           "method": function(e)

                           }
                         }

                      ],
                        "titles": [{
                              "id": "Title-1",
                              "size": 15,
                              "text": "Analysis"
                            }],

                        "stockLegend": {}
                  }],
                  "panelsSettings": {
                   "marginLeft": 50
                   },

                    "chartCursorSettings": {
                    "valueBalloonsEnabled": true
                  },

                "responsive": {
                "enabled": true
                 },

                });

data  is the data received from ajax.
Any help is appreciated.

A: You need to do 2 things:

*

*First, make sure the element where the chart will be drawn to is not sharing or reuse (for lack of better words) CSS classes that are not specific to the chart.

That means you need to move the #mainchart div to be inside the column:

<row>

Main Chart Area

</row>

*

*Then you need to add the expected dimensions for the chart in CSS:
#mainchart {
width: 100%;
height: 400px;}


text:
Q: Call mysql link on each function or pass the link through them? I do not know the best way, for performance, schema to call mysql link.
Which is better:
Do I call my MySQL link on each function, or call it just one time, and then pass the link through the functions?
For example,
Require through each function:
function one(){
  require('mysql.php');
  $query = 'SELECt * FROM table';
  $sql   = mysqli_query($link,$query);
}

function two(){
  require('mysql.php');
  $query = 'SELECt * FROM table';
  $sql   = mysqli_query($link,$query);
}

function three(){
  require('mysql.php');
  $query = 'SELECt * FROM table';
  $sql   = mysqli_query($link,$query);
}

Or require one time and then pass the link to the functions:
require('mysql.php');

function one($link){
  $query = 'SELECt * FROM table';
  $sql   = mysqli_query($link,$query);
}

function two($link){
  $query = 'SELECt * FROM table';
  $sql   = mysqli_query($link,$query);
}

function three($link){
  $query = 'SELECt * FROM table';
  $sql   = mysqli_query($link,$query);
}

I want know which of these is the best way to gain performance (even if was just a little) and to avoid to overcharging my database because all these functions will be called on in sequence.
I'm not using PDO.
And the question marked as the duplicate has nothing to do with my question.


text:
Q: What are the various link types in Windows? How do I create them? Is it possible to link two files or folders without having a different extension under Windows?
I'm looking for functionality equivalent to the soft and hard links in Unix.

A: If you're on Windows Vista or later, and have admin rights, you might check out the mklink command (it's a command line tool). I'm not sure how symlink-y it actually is since windows gives it the little arrow icon it puts on shortcuts, but a quick notepad++ test on a text file suggests it might work for what you're looking for.
You can run mklink with no arguments for a quick usage guide.

A: Please note that the only unfortunate difference is that you need Administrator rights to create symbolic links. IE, you need an elevated prompt. (A workaround is the SeCreateSymbolicLinkPrivilege can be granted to normal Users via secpol.msc.)
Note in terminology: Windows shortcuts are not called "symlinks"; they are shell links, as they are simply files that the Windows Explorer shell treats specially.

Symlinks:  How do I create them on NTFS file system?
Windows Vista and later versions support Unix-style symlinks on NTFS filesystems.
Remember that they also follow the same path resolution – relative links are created relative to the link's location, not to the current directory. People often forget that. They can also be implemented using an absolute path; EG c:\windows\system32 instead of \system32 (which goes to a system32 directory connected to the link's location).
Symlinks are implemented using reparse points and generally have the same behavior as Unix symlinks.
For files you can execute:

mklink linkname targetpath

For directories you can execute:

mklink /d linkname targetpath

Hardlinks: How do I create them on NTFS file systems?
All versions of Windows NT support Unix-style hard links on NTFS filesystems. Using mklink on Vista and up:

mklink /h linkname targetpath

For Windows 2000 and XP, use fsutil.

fsutil hardlink create linkname targetpath

These also work the same way as Unix hard links – multiple file table entries point to the same inode.

Directory Junctions: How do I create them on NTFS file systems?
Windows 2000 and later support directory junctions on NTFS filesystems. They are different from symlinks in that they are always absolute and only point to directories, never to files.

mklink /j linkname targetpath

On versions which do not have mklink, download junction from Sysinternals:

junction linkname targetpath

Junctions are implemented using reparse points.

How can I mount a volume using a reparse point in Windows?
For completeness, on Windows 2000 and later, reparse points can also point to volumes, resulting in persistent Unix-style disk mounts:

mountvol mountpoint \\?\Volume{volumeguid}

Volume GUIDs are listed by mountvol; they are static but only within the same machine.

Is there a way to do this in Windows Explorer?
Yes, you can use the shell extension Link Shell Extension which makes it very easy to make the links that have been described above. You can find the downloads at the bottom of the page.

The NTFS file system implemented in NT4, Windows 2000, Windows XP, Windows XP64, and Windows7 supports a facility known as hard links (referred to herein as Hardlinks). Hardlinks provide the ability to keep a single copy of a file yet have it appear in multiple folders (directories). They can be created with the POSIX command ln included in the Windows Resource Kit, the fsutil command utility included in Windows XP or my command line ln.exe utility.
The extension allows the user to select one or many files or folders, then using the mouse, complete the creation of the required Links - Hardlinks, Junctions or Symbolic Links or in the case of folders to create Clones consisting of Hard or Symbolic Links. LSE is supported on all Windows versions that support NTFS version 5.0 or later, including Windows XP64 and Windows7. Hardlinks, Junctions and Symbolic Links are NOT supported on FAT file systems, and nor is the Cloning and Smart Copy process supported on FAT file systems.

The source can simple be picked using a right click menu.

And depending on what you picked, you right click on a destination folder and get a menu with options.

This makes it very easy to create links. For an extensive guide, read the LSE documentation.
Downloads can be found at the bottom of their page.
Relevant MSDN URLs:

*

*Reparse Points

*Hardlinks and Junctions

*Symlinks

A: In this answer I will attempt to outline what the different types of links in directory management are as well as why they are useful as well as when they could be used. When trying to achieve a certain organization on your file volumes, knowing the various different types as well as creating them is valuable knowledge.
For information on how a certain link can be made, refer to grawity's answer.
What is a link?
A link is a relationship between two entities; in the context of directory management, a link can be seen as a relationship between the following two entities:

*

*Directory Table
This table keeps track of the files and folders that reside in a specific folder.

A directory table is a special type of file that represents a directory (also known as a folder). Each file or directory stored within it is represented by a 32-byte entry in the table. Each entry records the name, extension, attributes (archive, directory, hidden, read-only, system and volume), the date and time of last modification, the address of the first cluster of the file/directory's data and finally the size of the file/directory.

*Data Cluster
More specifically, the first cluster of the file or directory.

A cluster is the smallest logical amount of disk space that can be allocated to hold a file.

The special thing about this relationship is that it allows one to have only one data cluster but many links to that data cluster, this allows us to show data as being present in multiple locations. However, there are multiple ways to do this and each method of doing so has its own effects.
To see where this roots from, lets go back to the past...
What is a shell link and why is in not always sufficient?
Although it might not sound familiar, we all know this one! File shortcuts are undoubtedly the most frequently used way of linking files. These were found in some of the early versions of Windows 9x and have been there for a long while.
These allow you to quickly create a shortcut to any file or folder, they are more specifically made to store extra information along just the link like for example the working directory the file is executed in, the arguments to provide to the program as well as options like whether to maximize the program.
The downside to this approach of linking is exactly that, the extra information requires this type of link to have a data cluster on its own to contain that file. The problem then is not necessarily that it takes disk space, but its rather that it the link is indirectly accessed as the Data Cluster first has to be requested before we get to the actual link. If the path referred to in the actual link is gone the shell link will still exist.
If you were to operate on the file being referred to, you would actually first have to figure out in which directory the file is. You can't simply open the link in an editor as you would then be editing the .lnk file rather than the file being linked to. This locks out a lot of possible use cases for shell links.
How does a junction point link try to solve these problems?
A NTFS junction point allows one to create a symbolic link to a directory on the local drives, in such a way that it behaves just like a normal directory. So, you have one directory of files stored on your disk but can access it from multiple locations.
When removing the junction point, the original directory remains. When removing the original directory, the junction point remains. It is very costly to enumerate the disk to check for junction points that have to be deleted. This is a downside as a result of its implementation.
The NTFS junction point is implemented using NTFS reparse points, which are NTFS file system objects introduced with Windows 2000.

An NTFS reparse point is a type of NTFS file system object. Reparse points provide a way to extend the NTFS filesystem by adding extra information to the directory entry, so a file system filter can interpret how the operating system will treat the data. This allows the creation of junction points, NTFS symbolic links and volume mount points, and is a key feature to Windows 2000's Hierarchical Storage System.

That's right, the invention of the reparse point allows us to do more sophisticated ways of linking.
The NTFS junction point is a soft link, which means that it just links to the name of the file. This means that whenever the link is deleted the original data stays intact; but, whenever the original data is deleted the original data will be gone.
Can I also soft link files? Are there symbolic links?
Yes, when Windows Vista came around they decided to extend the functionality of the NTFS file system object(s) by providing the NTFS symbolic link, which is a soft link that acts in the same way as the NTFS junction point. But can be applied to file and directories.
They again share the same deletion behavior, in some use cases this can be a pain for files as you don't want to have an useless copy of a file hanging around. This is why also the notion of hard links have been implemented.
What is a hard link and how does it behave as opposed to soft links?
Hard links are not NTFS file system objects, but they are instead a link to a file (in detail, they refer to the MFT entry as that stores extra information about the actual file). The MFT entry has a field that remembers the amounts of time a file is being hard linked to. The data will still be accessible as long as at least one link that points to it still exists.
So, the data does no longer depend on a single MFT entry to exist. As long as there is a hard link around, the data will survive. This prevents accidental deleting for cases where one does not want to remember where the original file was.
You could for example make a folder with "movies I still have to watch" as well as a folder "movies that I take on vacation" as well as a folder "favorite movies". Movies that are none of these will be properly deleted while movies that are any of these will continue to exist even when you have watched a movie.
What is a volume mount point link for?
Some IT or business people might dislike having to remember or type the different drive letters their system has. What does M: really mean anyway? Was it Music? Movies? Models? Maps?
Microsoft has done efforts over the year to try to migrate users away from the work in drive C: to work in your user folder. I could undoubtedly say that the users with UAC and permission problems are those that do not follow these guidelines, but doesn't that make them wonder:
Why should you even be viewing anything but your personal files on a daily basis?
Volume mount points are the professional IT way of not being limited by drive letters as well as having a directory structure that makes sense for them, but...
My files are in different places, can I use links to get them together?
In Windows 7, Libraries were introduced exactly for this purpose. Done with music files that are located in this folder, and that folder and that folder. From a lower level of view, a library can be viewed as multiple links. They are again implemented as a file system object that can contain multiple references. It is in essence a one-to-many relationship...
My brain explodes... Can you summarize when to use them?

*

*Shortcut links: Use them when you need quick access to an executable or website, a file that you launch very often or when you need to specify parameters to an application and a batch file is an overkill. Don't use it when you intend to manipulate the file through its shortcut.

*Junction points: Use them when you want a directory to be elsewhere, this allows you to move directories to faster or slower drives without losing the ability to access the original path. Another use is when you want access to a directory through another path. These can't be used to link to a share.

*Soft links: Use them where a shortcut link does not suffice, it is often used when you do intend to manipulate the file through its shortcut. Or when you want the file to be on a faster or slower drive without losing the ability to access the original path.

*Hard links: Use them when you only want a file to be gone when all hard links to it are removed. This can't be used for folders.

*Volume mount points: Use them when you run out of drive letters, or when you find it more feasible to access a volume through a path rather than through a drive letter.

*Libraries: Use them when you have the same type of file at many different locations and you need them to be together, this supports removable drives so makes it handy to get the folders on your removable drives show up between those on your computer when you insert it. You can click on the individual folders from the folder tree under the library in the tree view, which facilitates moving files between both.

A: this article has some distinctions
one important distinction is that in a sense, junctions pre win7 were a bit unsafe, in that deleting them would delete the target directory.
http://cects.com/overview-to-understanding-hard-links-junction-points-and-symbolic-links-in-windows/

A Junction Point should never be removed in Win2k, Win2003 and WinXP
  with Explorer, the del or del /s commands, or with any utility that
  recursively walks directories since these will delete the target
  directory and all its subdirectories. Instead, use the rmdir command,
  the linkd utility, or fsutil (if using WinXP or above) or a third
  party tool to remove the junction point without affecting the target.
  In Vista/Win7, it's safe to delete Junction Points with Explorer or
  with the rmdir and del commands.


text:
Q: Android memory issue when scanning bluetooth with thread and handler I'm using a thread and handler to achieve a Bluetooth scanning service of certain scanning period and frequency (scan 1s, sleep 1s, scan 1s, etc) by BluetoothLeScanner (actually migrating from BluetoothAdapter). However, as times goes by, I realise it is eating up the memory.
Then I tried to use the profiler to see what happened and I found that there's something looping recursively. I checked my code and could not find the issue. Anyone can help/encountered the same issue?
public class BleDetectionService extends Service {

    private static Handler handler;
    private static final long SCAN_PERIOD = 1100;

    ...

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        ....

        startBLEScanning();
        return super.onStartCommand(intent, flags, startId);

    }

    private void startBLEScanning() {
        mLeDeviceAdapter = new LeDeviceAdapter();
        mScanning = true;

        Toast.makeText(this, "BLE Service sucessfully started", Toast.LENGTH_SHORT).show();

        bleScanningThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                while (mScanning) {
                    scanLeDevice(true);
                }
            }
        }, "BLE Scanning Thread");

        bleScanningThread.start();
    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    bluetoothLeScanner.stopScan(scanCallback);
                }
            }, SCAN_PERIOD);

            // filter
            ScanFilter.Builder builder = new ScanFilter.Builder();
            ScanFilter filter = builder.build();
            ArrayList<ScanFilter> filters = new ArrayList<>();
            filters.add(filter);

            // scansetting
            ScanSettings.Builder settingsBuilder = new ScanSettings.Builder();
            settingsBuilder.setScanMode(ScanSettings.SCAN_MODE_BALANCED);
            settingsBuilder.setReportDelay(0);
            ScanSettings settings = settingsBuilder.build();

            bluetoothLeScanner.startScan(filters, settings, scanCallback);

        } else {
            bluetoothLeScanner.stopScan(scanCallback);
        }
    }
}

recorded in an earlier time

recorded in a later time

EDIT:
I have removed the thread and handler as I had mixed up the usage of BluetoothLeScanner with BluetoothAdapter. The scanLeDevice() is now called from main thread as suggested by @greeble31

A: Consider the following:
scanLeDevice() is called in a never-ending loop, and always with a parameter of true.
scanLeDevice() returns almost immediately (1ms or less).
Each invocation of scanLeDevice() creates a new Handler, and a new anonymous Runnable. The binding of the Runnable to the Handler involves a Message (one for each call to postDelayed()).
You have omitted the definition of SCAN_PERIOD from your post, but I'm going to take an educated guess, and say it's 60000 (1 minute). That means each new Handler must exist for 1 minute, because it needs to hold a Message for 1 minute, because it is tracking a Runnable which needs be executed when that minute expires.
In other words: You are calling scanLeDevice() roughly 1000 times per second, and each call creates 3 interrelated objects that must exist for at least 1 minute.
Your architectural mistake was probably including bleScanningThread. scanLeDevice() can be safely called on the main thread. It need only be called once. It will return immediately, but the scan will still be conducted (by the OS), in the background. ScanCallback will execute when appropriate, even though you have not supplied an extra thread. The scan will cease when your postDelayed() Runnable executes; this is probably what you intended from the beginning.


text:
Q: How do we get a function that returns a list in Python? So I'm new to Python and heres my code:
def sum_is_less_than(numeric_value, list_of_numbers):
    total = 0
    for number in list_of_numbers:
        total = total + number
        if total > numeric_value:
            break
        print(total)

numeric_value = 100
list_of_numbers = [2, 3, 45, 33, 20, 14, 5]

sum_is_less_than(numeric_value, list_of_numbers)

So what this code is doing, it's adding the values of the list as long as it's under the given numeric value. I want the code to output the first N elements in the list whose sum is less than the given numeric value.
For example: [1,2,3,4,5,6] and given numeric value is 10
I want the code to output [1,2,3] as adding 4 would make the sum greater or equal to the given numerical value.

A: So, if you want to get a list out of your function you need to actually return something. Here, output starts as an empty list and gets appended with values from yout original list list_of_numbers, until the sum is higher then the passed numeric value.
def sum_is_less_than(numeric_value, list_of_numbers):
        total = 0
        output = []
        for number in list_of_numbers:
            total = total + number
            output.append(number)
            if total > numeric_value:
                return output
        return output

A use case would be:
value = 10
list_of_numbers = [3,4,5,6]
list_sum_smaller_then_value = sum_is_less_than(numeric_value, list_of_numbers)

A: def sum_is_less_than(numeric_value, list_of_numbers):
    total = 0
    for number in list_of_numbers:
        total += number
        if total < numeric_value:
            print(number)
        else:
            break

numeric_value = 10
list_of_numbers = [1,2,3,4,5,6]

sum_is_less_than(numeric_value, list_of_numbers)

A: I would do it this way (short, efficient and pythonic). The first expression is a generator, meaning that it does not calculate values unnecessarily.
def sum_is_less_then(numeric_value, list_of_numbers: list):
    res = (sum(list_of_numbers[:idx]) for idx, _ in enumerate(list_of_numbers))
    return [x for x in res if x < numeric_value]

print (sum_is_less_then(30, [1,2,4,5,6,7,8,3,3,6]))
# result: [0, 1, 3, 7, 12, 18, 25]


text:
Q: Speeding up deploy operation in Visual Studio I'm building an application for windows mobile devices, which deals with a database composed of approximately 1500 files. However, the size of each file is under 50kB, and the overall size is under 15MB.
When Visual Studio deploys the app to a mobile device, it takes from 25 to 30 minutes. I was wondering whether there is a way to speed up the process.
I guess the high amount of files is what is slowing it down, but since I turned on the "Copy only if newer" option for every file, I don't really see how I could change anything else. Furthermore, the longest stage seems to be "Deploy started..."
Any idea of how I could improve the overall performance?

A: The main problem is that filesystem driver on all WM devices.  Basically the filesystem driver does not handle creating lots of directory entries in a single directory.  The 'create' directory entry time increases with every file you create in a single directory, when you get up to the thousands of files the create time can take hours.
I've seen it lots of times when backing up devices with mail messages folder where someone has 7000+ email files (created over a long period of time).  Backup is fast, but restore can take days because of this issue.
To avoid this, try to limit the number of files in one single folder by splitting across multiple folders, that combined with the manually copying the files like Vadmyst suggests should speed you up.

A: At start you can disable option for checking the latest version of the .NET CF framework ( Project options -> Devices -> Deploy the lates version... (checkbox).
If that will not help you can create binaries upload script, that will just copy files (xcopy...) to the destination device.


text:
Q: "Can't it also be" or "Can't it be also" in a question? They both have plenty examples available, but which one is preferable?

*

*"Can't it also be" — 1,310,000 Google results

*"Can't it be also" — 1,430,000 Google results

A: Google books ngram viewer is probably more authoritative source (if you may call search engine authoritative source at all):

(See here)
Unfortunately, I did not find how to search for "can't", above link is for "can it also be" version.
"Can it also be" clearly wins.

A: Whatever Google may say, the first version — "can't it also be" — sounds more natural to my ear. The fact that the second version has more Google hits may simply mean that other things on the page are what generated the hits. In other words, people link to pages that have information they need, regardless of grammar or writing style.
Moreover, in looking through a few I see the latter construction has been used very often in sentences involving what I would consider substandard writing. Take for example

why does java have an interpreator can't it be also a compiler

That is the complete and uncensored title of a blog post that appears on the first page of the "can't it be also" Google search. No capitalizations, no punctuation, misspellings — certainly these are not the hallmarks of a writing style you wish to emulate, are they?
And, in fact, if you Google the entire sentence you will see that it accounts for about 50 of the total 1.43 million hits. Polling Google for usage tips is not the best way to separate the wheat from the chaff, at least when it comes to grammar or spelling.


text:
Q: Select Where Query sqlite and Qt I want to find a word in all record of a column base on QlinEedit::textChanged. .
connect(ui->PoemSrch, &QLineEdit::textChanged, this, &MainWindow::updateTextPoem);

void MainWindow::updateTextPoem(const QString & st){
foreach (const QStringList &var, lst) {
    qDebug() << var.filter(st);
    QSqlQueryModel * modal1 = new QSqlQueryModel();
    QSqlQuery qry;
    qry.prepare("select * from Poems where Poem like ?");
    qry.addBindValue(QString("%1%").arg(st));
    modal1->setQuery(qry);
    ui->tableView->setModel(modal1);
 }
}

A:  void MainWindow::updateTextPoem(const QString & st)
{
    QSqlQuery query("SELECT * FROM Poems where Poem like '%' || ? || '%'");
    query.addBindValue(QString("%1%").arg(st));
    QSqlQueryModel * modal = new QSqlQueryModel();
    query.exec();
    modal->setQuery(query);
    ui->tableView->setModel(modal);
}


text:
Q: Run Function to animate content on .load complete I've built a site using the History API in modernizr that includes CSS3 page transitions for smooth loading. This is the code for that.
$(document).ready(function(event){
  var isAnimating = false,
  firstLoad   = false;

  $('.menu a').on('click', function(event){
event.preventDefault();
var newPage = $(this).attr('href');
if( !isAnimating ) changePage(newPage, true);
firstLoad = true;
  });

  $(window).bind('popstate', function() {
if(firstLoad) {
  var newPageArray = location.pathname.split('/'),
    newPage = newPageArray[newPageArray.length - 1];
  if( !isAnimating ) changePage(newPage, false);
}
firstLoad = true;
  });

  function changePage(url, bool) {
  isAnimating = true;
  $('body').addClass('page-is-changing').removeClass('show-menu');
  $('#open-button').removeClass('open');
  $('.loader').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
  loadNewContent(url, bool);
  $('.loader').off('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend');
});
if(!transitionsSupported()) loadNewContent(url, bool);
  }

  function loadNewContent(url, bool) {
url = ('' == url) ? 'index.html' : url;
var section = $('

');

//$.getScript('#page-script', function(){});

console.log(url);

section.load(url + ' .content-wrap > *', function(event){
  $('.wrapper').html(section);

  var delay = ( transitionsSupported() ) ? 1200 : 0;

  setTimeout(function(){
    $('body').removeClass('page-is-changing').remove('#page-script').load('#page-script');
    $('.loader').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
      isAnimating = false;
      $('.loader').off('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend');
    });
    if( !transitionsSupported() ) isAnimating = false;
  }, delay);

  if(url!=window.location && bool){
    window.history.pushState({path: url},'', url);
  }
});
  }

  function transitionsSupported() {
return $('html').hasClass('csstransitions');
  }

What I wanted to know is how would I call a function on completion of the loadNewContent function? I'd like to animate the content in from each page, but I need it to wait to fire until the content loads.
Thanks!
Jesse

A: You can do this by using jQuery's .promise() and .done()
$('example').fadeOut().promise().done(function(){
 // code here executes when the animation is finished.
});

Adding here that .load() has a callback like so :
$( "#result" ).load( "ajax/test.html", function() {
  alert( "Load was performed." );
});

More info : http://api.jquery.com/load/


text:
Q: MVC 5 WebApi FormDataCollection duplicates data as NameValueCollection I have an external service that POSTs emails to an MVC 5 WebApi endpoint as form data. Since the fields can change, I am trying to receive the POST body as a FormDataCollection. When I call the ReadAsNameValueCollection method, the results are inconsistent with the POSTed data.
For example, the beginning of the raw form data looks like this:
recipient=test%40example.com&sender=user%40gmail.com&subject=subject&from=UserName+%3Cuser%40gmail.com%3E
After some URL decoding the values should be:
recipient = test@example.com
sender = user@gmail.com
subject = subject
from = UserName <user@gmail.com>

But when I convert to a NameValueCollection and iterate over the keys and values, a couple of the values are returned as two copies of the data separated by a comma:
subject = subject,subject
from = UserName <user@gmail.com>,UserName <user@gmail.com>

There are 26 fields in my test emails (it would vary if there were attachments, for example), and this problem only affects the subject and from fields, as shown above -- both of which are just plain text, nothing special about them.
Anybody know what causes this or how to avoid it?
Edit: Posting code, but I didn't bother earlier because it's literally as simple as taking the input parameter and converting. (BlobWriter is just a helper class to write a string to Azure blob storage.)
public async Task<IHttpActionResult> ReceiveEmail(FormDataCollection postBody)
{
    NameValueCollection email = postBody.ReadAsNameValueCollection();

    // Debug: dump key/vals
    StringBuilder sb = new StringBuilder();
    foreach(string key in email.AllKeys) sb.AppendLine($"{key} == {email[key]}");
    await BlobWriter.Write("debug-container", "email.txt", sb.ToString());

    return Ok();
}

Edit 2: I should also note, requesting a specific key/value from the FormDataCollection (rather than dumping them iteratively) confirms the incorrect content. For example, postBody.Get("subject") yields subject,subject as the stored value.


text:
Q: Creating a Photo Editor with Brightroom | Swift The code I was shown for creating a Brightroom photo editor, that offers all of the different Brightroom features, was:
@IBAction func editImage(_ sender: Any) {
        guard let image = image else { return }
        let editor = Brightroom.Editor(image: image)
        present(editor.controller, animated: true, completion: nil)
    }

This code is now out-of-date and inaccurate. Additionally, the GitHub documentation is not very thorough. Would someone please show me how I could create the editor shown in the GitHub visual examples (image editor, photo cropping, masking)?
Brightroom Library

A: If you want to create a Photo Editor (or, add that functionality to your app), your best bet is to go through that Brightroom code and learn how to do it.
However, if you want a quick example of presenting its built-in editor:
@IBAction func editImage(_ sender: Any) {

    guard let image = UIImage(named: "samplePic")
    else {
        print("Could not load image named \"samplePic\"!")
        return
    }

    let imageProvider: ImageProvider = ImageProvider(image: image)

    let editingStack = EditingStack(imageProvider: imageProvider)

    let controller = ClassicImageEditViewController(editingStack: editingStack)

    present(controller, animated: true, completion: nil)

}

Edit - to answer question in comment...
If you want to use this BrightRoom library - it's open-source. You really, really, REALLY need to spend time going through all of its code so you know and understand how to use it.
After a quick look, it appears the approach to saving the edited image is to render it via the editing stack class.
Here's a really simple, sample implementation...
Notes:

*

*ViewController must be in a navigation controller, as the "Classic" editor UI uses navBar buttons

*

*view will turn red if it is NOT in a nav controller and print a message to the debug console

*sample code loads an image named "samplePic" from assets (replace with your image name)

*

*view will turn red if it CANNOT load the image and print a message to the debug console

If we pass the above tests, we should see this (with whatever image you added):

Tapping the "Start Editing" button will push to the "Classic" editor controller. Tapping "Done" in the nav bar of that controller will pop back to this view and update the image view with the edited image.
Please keep in mind -- This is Sample Code Only!!! I wouldn't expect it to be anything close to actual production use.
import UIKit
import BrightroomEngine
import BrightroomUI

class ViewController: UIViewController {

    var imgView = UIImageView()
    var editBtn = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let _ = self.navigationController
        else {
            print("This controller must be in a UINaviagationController !!!")
            view.backgroundColor = .red
            return
        }

        // replace with your image resource name
        let imgName: String = "samplePic"

        guard let image = UIImage(named: imgName)
        else {
            print("Could not load image named \"\(imgName)\"!")
            view.backgroundColor = .red
            return
        }

        imgView.image = image
        imgView.contentMode = .scaleAspectFit
        imgView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)

        editBtn.setTitle("Start Editing", for: [])
        editBtn.setTitleColor(.white, for: .normal)
        editBtn.setTitleColor(.lightGray, for: .highlighted)
        editBtn.backgroundColor = .systemBlue

        [imgView, editBtn].forEach { v in
            v.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(v)
        }

        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([

            imgView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            imgView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
            imgView.heightAnchor.constraint(equalTo: imgView.widthAnchor),
            imgView.centerYAnchor.constraint(equalTo: g.centerYAnchor),

            editBtn.topAnchor.constraint(equalTo: imgView.bottomAnchor, constant: 20.0),
            editBtn.widthAnchor.constraint(equalToConstant: 240.0),
            editBtn.centerXAnchor.constraint(equalTo: g.centerXAnchor),

        ])

        editBtn.addTarget(self, action: #selector(editTapped(_:)), for: .touchUpInside)

    }

    @objc func editTapped(_ sender: Any?) {

        guard let image = imgView.image
        else {
            print("Could not load image from image view!")
            return
        }

        let imageProvider: ImageProvider = ImageProvider(image: image)

        let editingStack = EditingStack(imageProvider: imageProvider)

        // create the "Classic" editing controller
        let controller = ClassicImageEditViewController(editingStack: editingStack)

        // set the closure for NavBar "Cancel" tap
        controller.handlers.didCancelEditing = { [weak self] vc in
            guard let self = self else { return }
            self.navigationController?.popViewController(animated: true)
        }

        // set the closure for NavBar "Done" tap
        controller.handlers.didEndEditing = { [weak self] vc, editStack in
            guard let self = self else { return }

            var img: UIImage!
            do {
                let r = try editStack.makeRenderer().render()
                let imgData = r.makeOptimizedForSharingData(dataType: .png)
                img = UIImage(data: imgData)
            } catch {
                print("error?", error)
            }
            if let img = img {
                self.imgView.image = img
            }
            self.navigationController?.popViewController(animated: true)

        }

        // push to the editing controller
        self.navigationController?.pushViewController(controller, animated: true)

    }

}


text:
Q: Help with the Android Cursor So I have a Cursor that is getting a result from a query to the application database. I know that there is at least one correct entry in the database since I was able to retrieve the string from the row previously.
I then changed some of the logic to accommodate the result and am suddenly getting null returned when calling c.getString(0). The relevant code is posted below.
I'm new to Android and Java, so I might be missing some subtlety that's causing the problem.
   Cursor c = context.getContentResolver().query(tempJobName.build(),
           null, null, null, null);

   for (c.moveToFirst(); c.isAfterLast() == false; c.moveToNext())
   {
       Log.w(TAG, c.getString(0));
       if (c.getString(0).equalsIgnoreCase(jobName))
       {
           existed = true;
           break;
       }
    }

A: You might want to add more details. But since you did find some records, the solution for your problem is easy. Could you please replace this line with this? ( First column of table might change right :))
c.getString(0);

with
int columnIndex = c.getColumnIndex(COLUMN_NAME);// You could also use getcolumnIndexorThrow variant.
c.getString(columnIndex);

if this does not work, then your table does not have the column. You are simply barking up the wrong tree.


text:
Q: flutter Firestore where query not displaying when using variable values in flutter Firestore the where query is not displaying the values when using a variable.
Firestore.instance.collection('Schedules')
        .where('from', isEqualTo: widget.from)
        .where('to', isEqualTo: widget.to)
        .snapshots();

when i tried to call it with specified value it displays the items.
.where('from', isEqualTo: "Ethiopia")

Firestore data structure is here...
how can i fix such problem?

A: Posting as Community Wiki, based in the comments.
The issue here is within the variables that you are trying to compare the values - widget.to and widget.from - as the where clause works. You will need to change the way you are passing this variables in the where part of the query, so you have the certain, that the values are being passed correctly, as right now, this is the issue.
I would recommend you to change the way you are checking the values, so it's confirmed that the variables have the values in the needed context.


text:
Q: How to define a callable mathematical function when using plot in tikz Suppose I have f(x)=x^2+x+sin(x). Then I want to plot g(f(x)), where g(x) is polynomial in x, then I want to further plot h(g(f(x))), where h(x) is another polynomial in x, and the it continues. Is there a way to save f(x), g(x) and give them a name instead of rewriting it every time?
Currently I just rewrite everything as follows: let g(x)=2x
\begin{tikzpicture}
\draw[domain=-1:1] plot (\x^2+\x+sin(\x));
\draw[domain=-1:1] plot (2*(\x^2+\x+sin(\x)));
% I have to rewrite f(x)
\end{tikzpicture}

I'd like to define a variable f that represents the function f I can just call and plot. Is there a way to do this?

A: \documentclass[tikz, border=1cm]{standalone}
\begin{document}
\begin{tikzpicture}[
declare function={
 f(\x)=(\x)^2+\x+sin(\x);
 g(\x)=2*\x;
 h(\x)=(\x)^2;
}]
\draw[red] plot[domain=-1:1]  ( \x, {f(\x)} );
\draw[green] plot[domain=-1:1]  ( \x, {g(f(\x))} );
\draw[blue] plot[domain=-1:1]  ( \x, {h(f(\x))} );
\end{tikzpicture}
\end{document}


text:
Q: How to not affect current route and change 'Title' of NavigationBarRouteMapper directly -- React Native? Following is snippet:
var NavigationBarRouteMapper = {
    ...
   ,
    RightButton(route, navigator, index, navState){
      return(
        <TouchableHighlight onPress={()=>{
            //Once clicked, I would like it to rerender the NavigationBarRouteMapper's Title directly without having to change the current route
          }
        }>
          <Text>Button</Text>
        </TouchableHighlight>
      )
    },
    Title(route, navigator, index, navState){
        //e.g. if(route.name == 'ButtonPressed'){return <Text>New Title</Text>} else return null

Once the RightButton is clicked, I would want it to render the Title to
<Text>New Title</Text>

if not just return null. Is there a way to do so without having to change the current route?

A: I don't think it is supported at the moment. The NavigatorIOS module was dumped by Facebook and now maintained by the community, so I doubt that it will be resolved any time soon.. you can track the issue here.
Instead, you can use NavigationExperimental to achieve the same result (although it might get hairier as this is only half-backed). Check out NavigationExperimental in UIExplorer to see for yourself.


text:
Q: Why flask app context is lost in child thread when application factory pattern is used? Somewhat a mystery question.
Spawning a thread from flask app works well works well when all code is placed in the single app.py file, but application context gets lost when factory pattern is used.
Exception in thread Thread-2:
Traceback (most recent call last):
  File "/XXX/flaskthreading/venv/lib/python3.9/site-packages/sqlalchemy/util/_collections.py", line 1008, in __call__
127.0.0.1 - - [07/Jun/2022 14:06:53] "GET / HTTP/1.1" 200 -
    return self.registry[key]
KeyError: <greenlet.greenlet object at 0x7f4f541ad040 (otid=0x7f4f54199d00) current active started main>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.9/threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
  File "/XXX/flaskthreading/app2/views.py", line 12, in printer
    print(User.query.all())
  File "/XXX/flaskthreading/venv/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 552, in __get__
    return type.query_class(mapper, session=self.sa.session())
  File "/XXX/flaskthreading/venv/lib/python3.9/site-packages/sqlalchemy/orm/scoping.py", line 47, in __call__
    sess = self.registry()
  File "/XXX/flaskthreading/venv/lib/python3.9/site-packages/sqlalchemy/util/_collections.py", line 1010, in __call__
    return self.registry.setdefault(key, self.createfunc())
  File "/XXX/flaskthreading/venv/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 4225, in __call__
    return self.class_(**local_kw)
  File "/XXX/flaskthreading/venv/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 174, in __init__
    self.app = app = db.get_app()
  File "/XXX/flaskthreading/venv/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 1042, in get_app
    raise RuntimeError(
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

Any idea why is this happening or what docs we have missed ?
MVP provided https://github.com/bodik/flaskthreading-experiments/
git clone
pip install -r requirements.txt

# working app
FLASK_APP=app1 flask run
curl http://localhost:5000/

# produces error
FLASK_APP=app2.app flask run
curl http://localhost:5000/

A: From https://flask.palletsprojects.com/en/2.1.x/reqcontext/#lifetime-of-the-context:

When a Flask application begins handling a request, it pushes a request context, which also pushes an app context. When the request ends it pops the request context then the application context.
The context is unique to each thread (or other worker type). ...

In the case of a global app and db = SQLAlchemy(app), db always has self.app.
In the case of application factory pattern, db gets the app context from the thread.
Pass an AppContext to be pushed onto the thread:
# def printer():           # Change this
def printer(app_context):  # to this
    app_context.push()     #
    print(User.query.all())

@blueprint.route('/')
def index():

    # athread = Thread(target=printer, args=(), daemon=True)                          # Change this
    athread = Thread(target=printer, args=(current_app.app_context(),), daemon=True)  # to this
    athread.start()

    return 'ok'


text:
Q: Volume buttons stay pressed If I try to turn the volume on my laptop up/down/mute, it is always like I kept the button pressed. I believe I have to change something in /lib/udev/hwdb.d/60-keyboard.hwdb, but I don't know what.
I have a medion laptop
System Information
    Manufacturer: Medion
    Product Name: P6669 MD60147

A: I have the same issue on a Medion P6689 MD61019.  You were on the right track; this seemed to do the trick:
Create a text file containing:
# Fix for volume keys on Medion keyboards
evdev:atkbd:dmi:bvn*:bvr*:svnMEDION:pnP*:pvr*
evdev:atkbd:dmi:bvn*:bvr*:svnMedion:pnP*:pvr*
 KEYBOARD_KEY_a0=!mute
 KEYBOARD_KEY_ae=!volumedown
 KEYBOARD_KEY_b0=!volumeup

Save it to /lib/udev/hwdb.d/99-keyboard-medion-vol-fix.hwdb and run the following commands as root:
systemd-hwdb update
udevadm trigger --verbose --sysname-match="event*"

and done!  Volume keys now work normally.
Depending on how many models this affects, the :pnP* field could be changed to match only a few models.
(You may want to check /sys/class/dmi/id/modalias for your specific vendor ID.)

From /lib/udev/hwdb.d/60-keyboard.hwdb:
# Supported hardware matches are:
...
#  - AT keyboard DMI data matches:
#      evdev:atkbd:dmi:bvn*:bvr*:bd*:svn<vendor>:pn<product>:pvr*
#    <vendor> and <product> are the firmware-provided strings
#    exported by the kernel DMI modalias, see /sys/class/dmi/id/modalias
...
# An '!' as the first character of the key identifier string
# will add the scan code to the AT keyboard's list of scan codes
# where the driver will synthesize a release event and not expect
# it to be generated by the hardware.
...
# To update this file, create a new file
#   /etc/udev/hwdb.d/70-keyboard.hwdb
# and add your rules there. To load the new rules execute (as root):
#   systemd-hwdb update
#   udevadm trigger /dev/input/eventXX
# where /dev/input/eventXX is the keyboard in question. If in
# doubt, simply reload all input rules
#   udevadm trigger --verbose --sysname-match="event*"
...
# Akoya
evdev:atkbd:dmi:bvn*:bvr*:svnMEDION*:pnS3409*:pvr*
evdev:atkbd:dmi:bvn*:bvr*:svnMedion*:pnAkoya*:pvr*
 KEYBOARD_KEY_a0=!mute
 KEYBOARD_KEY_ae=!volumedown
 KEYBOARD_KEY_b0=!volumeup
 KEYBOARD_KEY_19=!p
 KEYBOARD_KEY_df=sleep

In short, some Medion laptop keyboards need a ! for the volume keys (and maybe also the p key, whatever it is) because they don't generate key release events; however, not all Medion models are covered by default in /lib/udev/hwdb.d/60-keyboard.hwdb.
Strangely enough, after this fix, pressing and holding the volume keys DOES auto-repeat them until you release the key.


text:
Q: Excluding quotes while scraping text on a forum site I am struggling with excluding quotes on a forum website. I need to scrape message texts some of which include quotations as a reference to an earlier message. Scraping all messages that have quotes means I get the same text on scraped data multiple times. In which case analyzing it becomes difficult. Can anybody help me with bypassing quoted text while scraping?
Here is an example page: https://forum.donanimhaber.com/toyota-touch-2-ve-touch-go-2-kullanici-tecrubeleri-ve-klavuzda-yazmayanlar--88405838
Here is the html code of a message with quotation:

**
quote:

Orijinalden alıntı:  DBolanci

  Beyler albüm kapağı ve klasör listelemeyi bende yapamadım. Mp3leri tek tek düzenledim en ince ayrıntısına kadar yazdım ama göstermiyor. Nasıl yapacaz bilgisi olan? Ayrıca araçta navigasyon özelliğini nasıl kazandırabiliriz? servis yazılım için ücret istiyor :(

**

  aynı soruların cevabını bende bekliyorum. yardımcı olabilecek kimse yokmu?

A: If you look at the html structure of the message you can see that it follows this format:

 QUOTED TEXT

    TEXT CONTENT

All you have to do is select msg>table content and do not select msg>table>table content. In xpath selectors this can be achieved in something like:
//span[@class="msg"]/table/tbody/tr/td/text()


text:
Q: TileMill and Geojson; Datasource could not be loaded Im following this article to get a geojson file from an excel using Google Refine.
http://support.mapbox.com/kb/tilemill/converting-addresses-in-spreadsheets-to-custom-maps-in-tilemill
Now I've got the weird issue that I sometimes get the error message that the Datasource could not be loaded, while I'm using the exact same template everytime. The only thing different seems to be the data I'm loading.
Also if I compare the 2 geojson files (1 that is working and 1 that is not) I can see no difference.
Does anyone know what the problem could be? .. is it the use of spaces/breaks or whatever perhaps??
This one is working:
    {
        "type": "FeatureCollection",
        "features": [
        {
          "type": "Feature",
          "id": 25.019909,
          "geometry": { "type": "Point", "coordinates": [121.365599, 25.019909] },
          "properties":

      {
          "Users" : 1
        }
    },
        {
          "type": "Feature",
          "id": 24.446706,
          "geometry": { "type": "Point", "coordinates": [117.818197, 24.446706] },
          "properties":

      {
          "Users" : 1
        }
    },
        {
          "type": "Feature",
          "id": 25.100632,
          "geometry": { "type": "Point", "coordinates": [117.03403, 25.100632] },
          "properties":

      {
          "Users" : 1
        }
    },
        {
          "type": "Feature",
          "id": 47.354348,
          "geometry": { "type": "Point", "coordinates": [123.918186, 47.354348] },
          "properties":

      {
          "Users" : 1
        }
    },
        {
          "type": "Feature",
          "id": 30.199652,
          "geometry": { "type": "Point", "coordinates": [115.03852, 30.199652] },
          "properties":

      {
          "Users" : 3
        }
    },
...
...
...

}
  ]
}

While this one is giving me the error;
{
    "type": "FeatureCollection",
    "features": [    {
      "type": "Feature",
      "id": 25.019909,
      "geometry": { "type": "Point", "coordinates": [121.365599, 25.019909] },
      "properties":

  {
      "Users" : 1
    }
},
    {
      "type": "Feature",
      "id": 24.446706,
      "geometry": { "type": "Point", "coordinates": [117.818197, 24.446706] },
      "properties":

  {
      "Users" : 1
    }
},
    {
      "type": "Feature",
      "id": 25.100632,
      "geometry": { "type": "Point", "coordinates": [117.03403, 25.100632] },
      "properties":

  {
      "Users" : 1
    }
},
...
...
...
}
  ]
}

A: You have an extra '}' in the second one. But, of course this may only look this way because of what you removed when adding the ..., so its impossible to say unless you post the whole thing that is not working.
Hint: find a text editor that highlights matching braces - most should do this if you tell the editor you are viewing javascript or json code.

A: I'm sorry.. it was something in the data after all :( .. tilemill is very strict in what it accepts and what not apparently..


text:
Q: 404 after posting a big file with .net I have the following JS code, this function calls a WEBAPI service which receives a file and saves it to the server.
Please check the .onfail,
File size is 500MB
function GuardarOrigen() {
        var NombreOrigen = $("#Nombre").val()
        if (NombreOrigen == '') {
            info('Debe ingresar un nombre');
            return;
        }
        var rgx = new RegExp("^[a-zA-Z0-9]+$");

        if (!rgx.test(NombreOrigen)) {
            info('El nombre no debe tener espacios en blanco ni caracteres especiales.');
            return;
        }
        var files = $('#Archivo').get(0).files;

        if (files.length > 0) {
            if (window.FormData !== undefined) {
                var data = new FormData();
                for (var x = 0; x < files.length; x++) {
                    data.append("file" + x, files[x]);
                }

                $("#bntGuardar").prop('disabled', true);
                $("#imgLoader").show();
                $.ajax({
                    url: urlCrearOrigen + '?NombreOrigen=' + NombreOrigen,
                    method: "POST",
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (result) {
                        info("Guardado con éxito.");
                        window.location.href = urlEditarOrigen + result
                    },
                }).fail(function (jqXHR, textStatus) {
                    info("Error guardando el origen");

                    console.log('Error:' + jqXHR.responseText + textStatus);

                }).always(function () {
                    $("#imgLoader").hide();
                    $("#bntGuardar").prop('disabled', false);

                });
            }
        } else {
            info('Debe seleccionar el archivo');
        }

    }

On the WEB API Controller I have this code:
[HttpPost]
        [Route("/CrearOrigen")]
        public async System.Threading.Tasks.Task<HttpResponseMessage> CrearOrigen(string NombreOrigen)
        {

            if (!Request.Content.IsMimeMultipartContent())
            {
                return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No se recibieron archivos");

            }

            string root = HttpContext.Current.Server.MapPath("~/App_Data/CargaOrigenes");
            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }
            var provider = new MultipartFormDataStreamProvider(root);
            await Request.Content.ReadAsMultipartAsync(provider);
            if (provider.FileData.Count == 0)
            {
                return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Parámetros invalidos - sin archivo");
            }

            string FileName = provider.FileData[0].LocalFileName;
            string[] FileParts = provider.FileData[0].LocalFileName.Split(Convert.ToChar("."));
            string FileExt = String.Empty;
            if (provider.FileData[0].Headers.ContentDisposition.FileName.Contains(".csv"))
            {
                FileExt = "csv";
            }
            else
            {
                return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Archivo no soportado");
            }

            try
            {

                CargasMasivasManager cmm = new CargasMasivasManager();
                int idOrigen = cmm.CrearOrigen(FileName, FileExt, NombreOrigen);

                return this.Request.CreateResponse(HttpStatusCode.OK, idOrigen.ToString());
            }
            catch (Exception e)
            {
                return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
            }

        }

After 10 or 15 minutes I get a 404, the resource you are looking for is not on the server or is unavailable.
However when the files are smaller the process works fine.
Also, this works locally but when deployed on one server I get the error, and I cant debug on the server because I cant install Visual studio there.

A: Try updating your web.config to allow a large file
<configuration>
  <system.web>
    <httpRuntime maxRequestLength="xyz" />
  </system.web>
</configuration>

xyz are in KB, so 2048kb = 2mb.
So 500mb = 512000kb


text:
Q: Sending out direct marketing an address at a time I wasn't sure where to ask this and my knowledge of this kind of application is limited.
If I was to build a PHP Web app that sends out a pregenerated email using phpmailer or swift using SMTP with a pdf attached using mail server (1and1) likely to ban me? Do I need an opt out service if I only allow one message to be sent? There would be no follow up emails.
Basically the client would locate an email address he believes may benefit from his service (from other websites) enter their details (a database would keep track of recipients) and then click send fo send the email. He may end up sending up to 100 emails a day with a few minutes between sends.
Is this acceptable to implement?

A: No. You need permission to send the first message - even sending an unsolicited message asking permission is enough to fall foul of legal issues and incur heavy fines - FlyBe found this out just recently and were fined £70,000.
What you're describing - harvesting emails from web sites, and sending them unsolicited marketing emails - has a more common name: spamming, and it's illegal.


text:
Q: EXTJS4 - For TreeStore, how to pass parameters and action methods? I am using Extjs4 TreeStore, i want to know how to pass parameters (like mode = 'list') and action methods (POST or GET).
Thanks in advance.
EXTJS 3.x i have used like this it's working fine:
loader: new Ext.tree.TreeLoader({
    dataUrl: 'content/permissions/server.php',
    baseParams: {
        mode: 'getPermissions'
    }
})

EXTJS 4.x i have used like this but it is not working:
Ext.create('Ext.data.TreeStore', {
    autoLoad: true,
    proxy: {
        type: 'ajax',
        url: 'server.php'
    },
    extraParams: {
        mode: 'getTree'
    },
    actionMethods: 'POST',
    root: {
        text: 'Tree',
        id: 'src',
        expanded: true
    }
});

Thanks,
Riyaz

A: You should carefully check your configuration parameters with the current Ext JS 4 API Documentation.
What I see at first glance:

*

*actionMethods is an object and not a string value configuration. It's implemented in both the AJAX and the REST proxies. If your need a full featured editable tree, consider a REST proxy. Only if you go beyond CRUD, you need to provide additional actionMethods to the REST proxy.

*extraParams belongs to the Proxy and not to the tree configuration.
So your store configuration should look like:
Ext.create('Ext.data.TreeStore', {
  autoLoad: true,
  proxy: {
    type: 'ajax',
    url: 'server.php',
    extraParams: {
      mode: 'getTree'
    },
  },
  root: {
      text: 'Tree',
      id: 'src',
      expanded: true
  }
 });

Have you verified if at least an Ajax request has been sent to the server? You can easily check this with FireBug.

A: example of correct setting:
  actionMethods: {
                destroy:'DELETE',
                create: 'POST',
                update: 'POST',
                read: 'GET'
            },

A: This the correct one
Ext.create('Ext.data.TreeStore', {
    autoLoad: true,
    proxy: {
        type: 'ajax',
        url: 'server.php',
        extraParams: {
            mode: 'getTree'
        },
        actionMethods: 'POST'
    },
    root: {
        text: 'Tree',
        id: 'src',
        expanded: true
    }
});


text:
Q: How to override Bloomberg API RefData I want to return more than the default amount of RefData for "BZCPI INDEX"
I know it is available because I can see it in Excel:
=BDH("BZCPI INDEX","PX_LAST","20110101","","cols=2;rows=101")

BUT I am unable to get earlier data, because I think START_DT is being ignored.
The below, give me a couple of years, but not from 2011 as I request:
    Globals.Masterform.iUpdateStatus("Connected sucessfully");
    Service refDataService = d_session.GetService("//blp/refdata");
    // create reference data request
    Request request = refDataService.CreateRequest("ReferenceDataRequest");
    // set request parameters
    Element securities = request.GetElement("securities");
    Element fields = request.GetElement("fields");
    Element requestOverrides = request.GetElement("overrides");
    request.Set("returnEids", true);

    Element overrides = request.GetElement("overrides");
    Element ovr = overrides.AppendElement();
    ovr.SetElement(FIELD_ID, "START_DT");
    ovr.SetElement("value", "20110101");

What might I be doing wrong?

A: Here are few more items further to the provided answers:

*

*Excel's =BDH() is implemented in the Api using HistoricalDataRequest to //blp/refdata service. If you have access to the Bloomberg terminal please type WAPI then click 'Translating Excel Formulas to API' link, the click 'BDH - Historical "End of Day" data'

*The code example in C# is HistoryExample.cs

*the endDate must be explicitly specified in the Api.
4.BZCPI INDEX ticks once a month, the last day of each month, so you need to specify a date range that includes one or more last days of the month(s), otherwise no data will return.


text:
Q: Unable to install Ease due to missing dependencies Getting the following error message while installing Ease even the required packages are there. Please see below for full details. Please let me know what went wrong.
...

configure: error: Package requirements ( clutter-gst-1.0 clutter-gtk-0.10 >= 0.10 gee-1.0 gmodule-2.0 json-glib-1.0 >= 0.7.6 libarchive poppler-glib rest-0.6  rest-extras-0.6 unique-1.0) were not met:

No package 'clutter-gst-1.0' found

No package 'gee-1.0' found

No package 'poppler-glib' found

No package 'rest-0.6' found

No package 'rest-extras-0.6' found

No package 'unique-1.0' found

Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix.

Alternatively, you may set the environment variables EASE_CFLAGS and EASE_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details.

-------------------------------------------------------------------

 $ apt-cache policy clutter-gst-1.0

gir1.2-clutter-gst-1.0:
  Installed: (none)
  Candidate: 1.3.6-1
  Version table:
     1.3.6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ natty/universe i386 Packages
libclutter-gst-1.0-0:
  Installed: 1.3.6-1
  Candidate: 1.3.6-1
  Version table:
 *** 1.3.6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ natty/universe i386 Packages
        100 /var/lib/dpkg/status
     1.2.0-0ppa1natty0 0
        500 http://ppa.launchpad.net/natesm/ease/ubuntu/ natty/main i386 Packages
libclutter-gst-1.0-dbg:
  Installed: (none)
  Candidate: 1.3.6-1
  Version table:
     1.3.6-1 0
        500 http://us.archive.ubuntu.com/ubuntu/ natty/universe i386 Packages
     1.2.0-0ppa1natty0 0
        500 http://ppa.launchpad.net/natesm/ease/ubuntu/ natty/main i386 Packages
libclutter-gst-1.0-dev:
  Installed: (none)
  Candidate: 1.2.0-0ppa1natty0
  Version table:
     1.2.0-0ppa1natty0
        500 http://ppa.launchpad.net/natesm/ease/ubuntu/ natty/main i386 Packages

A: You need to install the *-dev packages. These contain the headers and other files that are required by the source files you are trying to compile.
Also please note Ease does not seem to be under active development (I emailed the author and never got a reply either).


text:
Q: Preloading and prerendering an image in a webpage So I have 3 separate background images in 3 separate divs. I have a page set up to auto-scroll from one div to the next when the user hits continue. I am currently having an issue where the user can see the background images loading (quickly, but still...) I want a smooth user experience and am trying to let the images preload before the user starts playing with the app. Once I have cycled through all 3 pages everything runs smoothly. How do I have the browser load all that into memory beforehand and why is it not already doing that? Only the first div is visible to the user on page load but only because the others are hidden under overflow. I tried javascript new Image().src = URL but that didn't help. I tried HTML/CSS <link rel="preload" href="./assets/img/inputs.jpg" as="image"> and that didn't help either. This is a head-scratcher for me... Any suggestions? I plan on adding a loading screen to the web app but I want to put an elegant solution behind that loading screen.
Thanks!
Brett

A: I believe that the following (setting style to display:none) should work in most cases, assuming that parent container not hidden. It doesn't necessarily have to be container is which it is ultimately displayed:
   <img src="/assets/img/inputs.jpg" style="display: none;" />

Alternatively, you can try setting the height and width of the img's to 1px each.


text:
Q: How to get directive to apply focus to its wrapped input? I've built an attribute directive (focus-on-event) which watches for an event on the $rootScope and when it's triggered sets the focus onto the attached element.
The problem is when I want to add that directive to another custom directive wrapping an input (wrapped-input). I need it to go into my element and apply the focus to the input.
I tried binding to the focus event of wrapped-input, but that never seems to be triggered. I also tried broadcasting another event but that doesn't seem to work. If I can make either approach work, I can just put the focus on the wrapped input element right from wrapped-input's link function.
How can I make this work?

angular
  .module('app', [])

  .directive('wrappedInput', function() {
    return {
      template: '<input placeholder="wrapped input">',
      link: function(scope, element, attrs) {
        scope.$on('hello', function() {
          alert('This never gets called');
        });
        element.bind('focus', function() {
          alert('This never gets called either');
        });
      }
    }
  })

  .directive('clickTriggers', function($rootScope) {
    return {
      scope: { clickTriggers: '@' },
      link: function(scope, element, attrs) {
        element.bind('click', function() {
          $rootScope.$broadcast(scope.clickTriggers);
        });
      }
    }
  })

  .directive('focusOnEvent', function() {
    return {
      scope: { focusOnEvent: '@' },
      link: function(scope, element, attrs) {
        scope.$on(scope.focusOnEvent, function(onEvent, keypressEvent) {
          element[0].focus();
          scope.$broadcast('hello');
        });
      }
    }
  });

    <wrapped-input focus-on-event="event1"></wrapped-input>
    <button click-triggers="event1">Trigger 'event1'</button>

    <input type="text" focus-on-event="event2" placeholder="native input">
    <button click-triggers="event2">Trigger 'event2'</button>

A: Options:

*

*broadcast from rootScope.

*broadcast from parentScope

*emit from directive and have parent scope controller catch and broadcast it.


text:
Q: 20x4 lcd with arduino and xbee im using an arduino mega attached to a 20x4 lcd and xbee. LCD is a i2c interface. Im using the following the code to write the data received by the xbee on the LCD.
/*****************************************************************
XBee_Serial_Passthrough.ino

Set up a software serial port to pass data between an XBee Shield
and the serial monitor.

Hardware Hookup:
  The XBee Shield makes all of the connections you'll need
  between Arduino and XBee. If you have the shield make
  sure the SWITCH IS IN THE "DLINE" POSITION. That will connect
  the XBee's DOUT and DIN pins to Arduino pins 2 and 3.

*****************************************************************/
// We'll use SoftwareSerial to communicate with the XBee:
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LCD03.h>
 LCD03 lcd;
// XBee's DOUT (TX) is connected to pin 2 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 3 (Arduino's Software TX)
SoftwareSerial XBee(10, 11); // RX, TX

void setup()
{
  // Set up both ports at 9600 baud. This value is most important
  // for the XBee. Make sure the baud rate matches the config
  // setting of your XBee.
  XBee.begin(9600);
  Serial.begin(9600);
    // Initialise a 20x4 LCD
  lcd.begin(20, 4);

  // Turn on the backlight
  lcd.backlight();

  // Write to the LCD
  lcd.print("Hello world");

  // Wait for 5 seconds
  delay(5000);

  // Clear the LCD
  lcd.clear();
}

void loop()
{
  if (Serial.available())
  { // If data comes in from serial monitor, send it out to XBee
    XBee.write(Serial.read());
  }
  if (XBee.available())
  { // If data comes in from XBee, send it out to serial monitor
    Serial.write(XBee.read());
   lcd.write(XBee.read());

  }
}

However, it shows black boxes on the LCD instead of words.
If i use lcd.print("test"); it shows 'text' which means that the LCD is receiving the data sent from xbee but i cannot use lcd.print as the data received is random.
Moreover, how can i clear the screen after every word as all the words come in a single line.

A: There are two reasons why i think this problem is occurring :-

*

*Probably the data is getting corrupted while getting transmitted, so might have to implement some error check method (eg: checksum), and request again for data if that is the case.

*You have to check what is the format of data that is being transmitted from your transmitter module. I mean LCD expects the data to be in ASCII format, is that the same format received from xbee.

Basically you have to check your data at multiple points and find out where exactly the problem occurs.
Since you are saying that writing
 lcd.print("test");

does work properly hence i believe the I2C is set correctly, so above mentioned problems are the only things i can think of.
Approach:-
Why don't you display the serial data received xbee on serial monitor of arduino and check if the data received is correct or not.


text:
Q: CH and embeddings of $\aleph_2$ into Pow($\omega$) CH is false iff $\aleph_2$ is embeddable in Pow($\omega$).
But in this paper they write on the very first line the opposite: CH is apparently true if
$\aleph_2$ is emebeddable in Pow($\omega$).
So why , what's wrong ?

A: *

*The term "true" is subject to understanding that some people expect mathematics to have an objective and concrete truth value, independent of our thoughts. They may argue that certain axioms are more plausible than others, and are therefore more likely to be true. This, in time, and with some mathematical work, can lead certain people to make claims about mathematical "truth".

*The text says exactly the opposite of what you claim that it says. It says that if $\aleph_2$ could be embedded into $2^{\aleph_0}$, that should have been apparent. It's not, apparent to the author, and therefore they claim that it is false, and in fact much more is true.

*The text is building upon previous work of the author where they already claim that the Continuum Hypothesis is true, and they now chose to extend this claim to say that $V=L$ is true.

The problem with "apparent", of course, that it is very much a cultural thing, based on the exact coordinates of your existence in the spacetime continuum. Different things are apparent to different people in different times and different places. So I'd take any claim about "truth" with a grain of salt. Including my claims that there isn't any.


text:
Q: QA query system on corpus We have a question - answer corpus like shown below
Q: Why did Lincoln issue the Emancipation Proclamation?
A: The goal was to weaken the rebellion, which was led and controlled by slave owners.

Q: Who is most noted for his contributions to the theory of molarity and molecular weight?
A: Amedeo Avogadro

Q: When did he drop John from his name?
A: upon graduating from college

Q: What do beetles eat?
A: Some are generalists, eating both plants and animals. Other beetles are highly specialised in their diet.

Consider question as queries and answers as documents.
We have to build a system that for a given query (semantically similar to one of the questions in the question corpus) be able to get the right document (answers in the answer corpus)

Can anyone suggest any algorithm or good way to proceed in building it.

A: Your question is too broad and the task you are trying to do is challenging. However, I suggest you to read about IR-based Factoid Question Answering. This document has reference to many state-of-art techniques. Reading this document should lead you to several ideas.
Please note that, you need to follow different approach for IR-based Factoid QA and knowledge-based QA. First, identify what type of QA system you want to build.
Lastly, I believe simple document matching technique for QA won't be enough. But you can try simple approach using Lucene @Debasis suggested and see whether it does well.

A: Consider a question and its answer (assuming there is only one) as one single document in Lucene. Lucene supports a field view of documents; so while constructing a document make question the searchable field. Once you retrieve the top ranked questions given a query question, use the get method of the Document class to return the answers.
A code skeleton (fill this up yourself):
//Index
IndexWriterConfig iwcfg = new IndexWriterConfig(new StandardAnalyzer());
IndexWriter writer = new IndexWriter(...);
....
Document doc = new Document();
doc.add(new Field("FIELD_QUESTION", questionBody, Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("FIELD_ANSWER", answerBody, Field.Store.YES, Field.Index.ANALYZED));
...
...
// Search
IndexReader reader = new IndexReader(..);
IndexSearcher searcher = new IndexSearcher(reader);
...
...
QueryParser parser = new QueryParser("FIELD_QUESTION", new StandardAnalyzer());
Query q = parser.parse(queryQuestion);
...
...
TopDocs topDocs = searcher.search(q, 10); // top-10 retrieved
// Accumulate the answers from the retrieved questions which
// are similar to the query (new) question.
StringBuffer buff = new StringBuffer();
for (ScoreDoc sd : topDocs.scoreDocs) {
    Document retrievedDoc = reader.document(sd.doc);
    buff.append(retrievedDoc.get("FIELD_ANSWER")).append("\n");
}
System.out.println("Generated answer: " + buff.toString());


text:
Q: Get a blank new relation from existing ActiveRecord::Relation In my project I use closure_tree gem and want to write custom method on my Product model which returns all parents for given collection.
I tried to write class method:
class Product < ActiveRecord::Base
  has_closure_tree

  def self.tree_parents
    root_product_ids = []

    all.each do |product|
      root_product_ids << (product.root? ? product.id : product.parent_id)
    end

    Product.where(id: root_product_ids)
  end
 end

The returning relation is being merged with the previous, but I need this method to return absolutely new independent ActiveRecord::Relation:
»  leaf_product = Product.where(id: 219)
  Product Load (0.7ms)  SELECT "products".* FROM "products"  WHERE "products"."deleted_at" IS NULL AND "products"."id" = 219
=> #<ActiveRecord::Relation [#<Product id: 219, name: ... ]>
»  leaf_product.tree_parents
  Product Load (1.0ms)  SELECT "products".* FROM "products"  WHERE "products"."deleted_at" IS NULL AND "products"."id" = 219
  Product Load (0.7ms)  SELECT "products".* FROM "products"  WHERE "products"."deleted_at" IS NULL AND "products"."id" = 219 AND "products"."id" IN (1)
=> #<ActiveRecord::Relation []>

In short I want this method to return ONLY Product.where(id: root_product_ids) and do not chain it with Product.where(id: 219).
How do I return a new relation containing only IN statement without a statement from a parent relation WHERE id ...?

A: Not quite sure what you are doing but it sounds like you are looking for the unscoped method:
Product.unscoped.where(id: product_ids)


text:
Q: Unable to load standard library for target arm64 error in XCode on Macbook Air M1 On new Mac with M1 chip get the error after the build of React Native app in XCode 12.4:
unable to load standard library for target 'arm64-apple-ios8.0'

failed to build module 'SciChart' from its module interface; the compiler that produced it, 'Apple Swift version 5.1.3 (swiftlang-1100.0.282.1 clang-1100.0.33.15)', may have used features that aren't supported by this compiler, 'Apple Swift version 5.3.2 (swiftlang-1200.0.45 clang-1200.0.32.28)'

What I already tried:

*

*Reinstall XCode;

*Changed Swift Language Version;

*Deleted VALID_ARCHS reference according Xcode 12 Beta 2 - unable to load standard library for target 'arm64-apple-ios14.0-simulator'
On Macbook with intel chip there are no errors with the same app. And both of my Macbook have the same swift version:
Apple Swift version 5.3.2 (swiftlang-1200.0.45 clang-1200.0.32.28)
Target: x86_64-apple-darwin20.3.0

Can you help me please!

A: Guys if you have old React Native projects just build it on Xcode with rosetta and you will save your nerves and time. I was looking the decision all week, but in the total it was so easy, just run Xcode with rosetta on M1: please try to open Xcode through Rosetta - Right click on Xcode in applications folder -> Get Info -> set Open with Rosetta to true


text:
Q: Trying to open Sql connection to Northwind database in C# with build error I am currently trying to learn how to connect an Sql server database to C#. I am trying to connect to the Northwind sample DB but I keep getting a build error. Can someone help point me in the direction where I am going wrong, here is my code and thank you in advance:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace TestConnection1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public string conString = "Data Source=TONYSPC\anthony;Initial Catalog=Northwind;Integrated Security=True";

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(conString);
            con.Open();

            if (con.State==System.Data.ConnectionState.Open)
            {
                string q = "insert into Employees(EmployeeID,FirstName)values('"+txtId.Text.ToString()+"','"+txtName.Text.ToString()+"')";
                SqlCommand cmd = new SqlCommand(q,con);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Connection made Successfully..!");
            }
        }
    }
}


text:
Q: Regression SPSS : How to see which IV is the strongest predictor of my DV?
Hey all, I run Multiple Regression. How to see which IV is the strongest predictor of my DV? From SPSS Table.
My IVs
1. Attitude
2. SN
3. PBC
My Dvs
Intention

A: In a multiple regression, the standardized coefficients (Beta) answer the question which of the independent variables have a greater effect on the dependent variable. Beta can be interpreted like the Pearson coefficient r on a scale -1 to 1. According to the table, the two independent variables AttitudesTotal and PBC_Total have similar magnitudes but opposite signs; in other words, they exhibit an inverse relationship. This suggests that they are equally "strong". However, determining which predictor (independent variable) is more important can only be determined in context using subject matter knowledge.


text:
Q: Predicate Logic - translation How can I translate the following sentence into Predicate Logic: "I hate flies" (F – [1] are flies, G – [1] hate [2], а – I). I was thinking of ∃a(Fx∧Gx), is the sentence correct?
Thank you

A: No. $G$ needs two argument: the hater and the hated.  The hater is 'I', i.e. $a$, and the hated is flies .... and presumably all flies!
So, you need a universal statement, and you'll need $Gax$ in there.
Try again.

A: $aGF$, or $G(a,F)$, or $GaF$, depend on the notation you choose to use.
Perhabs this helps : $a$ and $F$ are constants whereas $G$ is binary relation.

A: Your translation would apply if there exists least one fly that you hate. Saying "I hate flies" suggests that you hate ALL flies.
Instead, how about:
$\forall x: [Fly(x) \implies IHate(x)]$
where $Fly$ and $IHate$ are unary predicates.


text:
Q: TExcelApplication - connecting to different servers I have 2 excel.exe instances running. How to make my TExcelApplication object to connect to specific excel.exe instance? (I see ConnectTo method but do not understand how to enum running excel com servers)
I'd like to select excel process by PID that I have...


text:
Q: "Communications Error - Check baud rate" after flashing NodeMCU with Latest .bin file After flashing my ESP8266 NodeMCU from https://github.com/nodemcu/nodemcu-firmware/releases/tag/1.5.4.1-master_20161201 latest firmware file, it constantly gives "Communications Error - Check baud rate" error over LuaLoader Software, while on Arduino Software gives "Unable to read" error.
Why is it so? Do help.

A: I had the same problem, I solved it erasing all the flash memory (4Mb in my case) before flashing. Here you'll find how to. http://www.pratikpanda.com/completely-format-erase-esp8266-flash-memory/
Another way to do a complete flash memory erase is with "esptool.py" and the "erase_flash" instruction. https://github.com/espressif/esptool


text:
Q: UI Elements jump way off the current view controller after adding to stack view (iOS) What I want to discuss here is the issues that I have encountered using stack views.
Problem:
Have:
Image lets say 200 x 300
UILabel - as a header
UILabel - as a body text
UIButton - background image 150 x 50
the UILabel labels jump way off the current view controller and have a size of 9,000 + width and height something strange as well.
Problem in detail:

Why does this happen? How to prevent this and how to fix this?
Solution?
Note: I welcome everybody's feed back with this one. It has not happened just once but many many times to me.


text:
Q: What is unsafe in this extreme simple thread Monitor implementation? I am new in thread syncronization. I was reading many implementations of conditional variables, like boost::threads and pthread for win32. I just implemented this quite simple monitor with wait/notify/noifyall, and i guess that there are many hidden problems with it, that I would like to discover from more experienced people. Any suggestion?
class ConditionVar
{

public :
    ConditionVar () : semaphore ( INVALID_HANDLE_VALUE ) , total_waiters (0)
    {
        semaphore = ::CreateSemaphoreA ( NULL , 0 /* initial count */ , LONG_MAX /* max count */ , NULL );
    }

    ~ConditionVar ()
    {
        ::CloseHandle ( semaphore ) ;
    }

public :
    template <class P>
    void Wait ( P pred )
    {
        while ( !pred() ) Wait();
    }

public :

    void Wait ( void )
    {
        INTERLOCKED_WRITE_RELEASE(&total_waiters,total_waiters + 1 );
        ::WaitForSingleObject ( semaphore , INFINITE );
    }

    //! it will notify one waiter
    void Notify ( void )
    {
        if ( INTERLOCKED_READ_ACQUIRE(&total_waiters) )
        {
            Wake (1);
        }
    }

    void NotifyAll (void )
    {
        if ( INTERLOCKED_READ_ACQUIRE(&total_waiters) )
        {
            std::cout << "notifying " << total_waiters ;
            Wake ( total_waiters );
        }
    }

protected :
    void Wake ( int count )
    {
        INTERLOCKED_WRITE_RELEASE(&total_waiters,total_waiters - count );
        ::ReleaseSemaphore ( semaphore , count , NULL );
    }

private :
    HANDLE semaphore;
    long    total_waiters;
};

A: I think bad things will happen if you copy your instance since both copies will use the same sempahore. This isn't necessarily a bad thing, but it might confuse people if the semantics aren't entirely clear.
You can easily fix this with a similar approach to what boost::noncopyable uses (or use boost).

A: I prefer Boost's implementation of wait(), because it takes an RAII lock object to make sure access to the shared condition state is synchronized. RAII makes it easier to write exception-safe code.
I have annotated the sample code found here:
boost::condition_variable cond;
boost::mutex mut;
bool data_ready;

void process_data();

void wait_for_data_to_process()
{
    boost::unique_lock<boost::mutex> lock(mut);  // Mutex acquired here (RAII).
    while(!data_ready) // Access to data_ready is sync'ed via mutex 'mut'
    {
        // While we are blocking, the mutex is released so
        // that another thread may acquire it to modify data_ready.
        cond.wait(lock);

        // Mutex is acquired again upon exiting cond.wait(lock)
    }
    process_data();

    // Mutex is released when lock goes out of scope.
}

A: if your using WinAPI functions, its probably better to use InterlockedIncrement(...) and InterlockedDecrement(...) instead of INTERLOCKED_WRITE_RELEASE(&total_waiters,total_waiters + 1 ); and INTERLOCKED_WRITE_RELEASE(&total_waiters,total_waiters - count ); respectively.

A: (self answer)
i found a big mistake.
CondVars have an external lock... and this hasnt.