text:
Q: Wait for AddIn uninstallation I'm in the process of writing some PowerShell script to do some work with SharePoint Online AddIns (.app), have a look at the image below:

As you can see from the highlighted syntax, I'm telling the session to have a 10 sec nap after the removal of the AddIn to make sure that next statement doesn't crash saying that the AddIn instance already exists, and it works fine, but sometimes these processes could hang for many minutes, or even hours, therefore,
I want the session to know when the current job is done without me specifying 10 seconds.
I have searched and tried using below,
Start-Job -Name "MyJob" -ScriptBlock { Do some work that could take time }

function WaitForJobToFinish([string]$currentJob)
{
    $JobName = $currentJob
    $job = Get-Job | ?{ $_.Name -like $JobName }
    if ($job -eq $null)
    {
        Write-Host 'Timer job not found'
    }
    else
    {
        $JobFullName = $job.Name
        Write-Host -NoNewLine "Waiting to finish job $JobFullName"
        while ((Get-Job $JobFullName) -ne $null)
        {
            Write-Host -NoNewLine .
            Start-Sleep -Seconds 2
        }
        Write-Host  "Finished waiting for job.."
    }
}

WaitForJobToFinish MyJob

No matter what I put inside the -ScriptBlock the session gets stuck:

Any ideas on how to achieve that?


text:
Q: Unable to Get Syntax Correct for Writing to Text File in .NET Core 2.2 Razor Pages It used to be simple to find the path to a folder with text files and either create and write or add to an existing file.
Now, I just can't get the syntax right.
var userData = firstName + "," + lastName +
    "," + email + Environment.NewLine;

var dataFile = Server.MapPath("~/App_Data/data.txt");
File.AppendAllText(@dataFile, userData);
result = "Information saved.";

_context.Courses_New.Add(Courses_New);
await _context.SaveChangesAsync();

The "File." is underlined in red and so is the "Server.".
I have seen examples that mentioned adding this code to get the "environment", but I get all red saying that HomeController must have a return value. The Create page is the return value.
private IHostingEnvironment _env;

public HomeController(IHostingEnvironment env)
{
    _env = env;
}

The code below is at the top of my Razor Page and it uses up the return value. So no matter what I name HomeController to, it gives me an error:
private readonly OESAC.Models.MyDbContext _context;

public CreateModel(OESAC.Models.MyDbContext context)
{
    _context = context;
}

Supposedly I can reference the _env variable to combine a path.
Goal is to simply write success and failure to a text file during a Create row Task.

A: If I understand the question correctly you are using Razor Pages. Controllers are used for WebApi and MVC but not needed for Razor Pages. But the same principles can be applied. As long as the other classes you need are configured with Dependency Injection (DI) you can just add them onto your page model constructor. So modify CreateModel as follows:
private readonly OESAC.Models.MyDbContext _context;
private IHostingEnvironment _environment { get; private set; }

public CreateModel(OESAC.Models.MyDbContext context, IHostingEnvironment hostingEnvironment)
{
    _context = context;
    _environment = hostingEnvironment;
}

Then later in a Page event you could do something like the following:
public async Task<IActionResult> OnPostAsync() {
    var webRootPath = _environment.WebRootPath;
    var dataPath = Path.Combine(webRootPath, "data.txt");
    ...
}

Note this will write a file in your web root which might be publically accessible and not what you want. Using a Logger might be a better approach if you are looking to record info about the inner runnings of your task (see here for more info)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I connect 2 laptops using bluetooth of ubuntu 11.10 & transfer files? I have used "hcitool scan" command but it can'nt find any address of other laptops but can detect phones . How can i connect 2 laptops ?

A: Make sure the other laptop is visible. Use the gnome or unity UI or if you don't have a desktop refer to this link- http://ubuntuforums.org/showthread.php?t=1530253.
You can also make an adhoc network and then share the files.


text:
Q: Reasons behind the analogy between "order of groups" and "sets" (if it exists). I had this question which I had to prove:
Let G be a group and H,K < G. Then if H,K are finite subgroups,
$$|HK| = |H||K|\div|H\cap K|$$
As I was trying to solve this question, it struck my mind that something of the form:
$$|H \cup K| = |H|+|K|-|H\cap K|$$
is true for sets.
Analogies I found

*

*$-$ (in set expression) $\leftrightarrow \div$ (in group expression)

*$+$ (in set expression) $\leftrightarrow \times$ (in group expression)

*Take the order of all separate sets seen in the equality for sets to obtain the corresponding equality for groups.

*$\cup$ (in set expression) $\leftrightarrow$ group operation (in group expression)

My curiosity
Do these analogies exist always, or is it just an accidental similarity? If they do, then what are the reasons behind such a similarity.
Thanks

A: Note: Question has now been edited; first paragraph applies to original write-up.

Your "set equation" is wrong; if by $H+K$ you mean, as you say in comments, "the set of all elements of $H$ and of $K$ combined", then that's nothing more than $H\cup K$. But then your "equation" is:
$$H\cup K = H\cup K - H\cap K$$
which is incorrect: the left hand side is the union, the right hand side is the symmetric different, the set of all elements that are in $H$ or in $K$, but not in both.
There is also a serious problem in that $HK$ is not in general the smallest subgroup containing both $H$ and $K$; that is, it does not play the same role as the union for sets (the least upper bound in the corresponding lattice).
At best, you could (if you look at this sideways) think of the equation
$$|HK| = \frac{|H|\,|K|}{|H\cap K|}$$
as an instance of "inclusion/exclusion", in which case the corresponding set equation would be
$$|H\cup K| = |H| + |K| - |H\cap K|.$$
(Note that both equations only hold in the finite case; for groups, the correct equation which holds in the sense of cardinality is $|HK|\,|H\cap K| = |H|\,|K|$; for sets, the corresponding equation would be $|H\cup K| + |H\cap K| = |H| + |K|$; h/t to Paul K for pulling my ears and reminding me of it.)
It's a stretch. What you have is two instance of overcounting-adjusting. In the latter case, you count everyting, then remove the things you counted twice. In the former case, you are counting all products (the cardinality of $|HK|$) by counting all possible pairs (the product $|H||K|$), and then dividing by the number of repetitions of the count. They are both very standard counting techniques, though the one for sets is when you are adding things, and the one in groups is when you are combining things. They both involve overcounting, then adjusting the overcount by a calculable quantity to get the correct result.

A: It turns out that one of these two facts can be seen as a special case of the other.
If $S$ is a set, we can make the power set $G=\mathcal{P}(S)$ into a group using the symmetric difference $A\Delta B = (A-B)\cup (B-A)$. (to see quickly that this is a group, note that it is isomorphic to the vector space $\mathbb{F}_2^S$ under addition)
Then, if $A,B\subset S$, we have subgroups $H=\mathcal{P}(A)$ and $K=\mathcal{P}(B)$ of $G$.  The counting formula for subgroups gives us:
$$|H\Delta K| \cdot |H\cap K| = |H| \cdot |K|$$
It is straightforward to verify that $H\Delta K = \mathcal{P}(A\cup B)$ and $H\cap K = \mathcal{P}(A\cap B)$.  So this gives us:
$$|\mathcal{P}(A\cup B)|\cdot|\mathcal{P}(A\cap B)| = |\mathcal{P}(A)|\cdot|\mathcal{P}(B)|$$
But this is just:
$$2^{|A\cup B|} \cdot 2^{|A \cap B|} = 2^{|A|} \cdot 2^{|B|}$$
...which is equivalent to:
$$|A\cup B| + |A\cap B| = |A| + |B|$$
In general, I think we can see both of these facts as special cases of something like the excision theorem for calculating the Euler characteristic, but I haven't worked out the details. (the Euler characteristic is tightly related to the principle of inclusion/exclusion, we can maybe use Eilenberg-MacLane spaces to bring groups in)


text:
Q: Swapping two elements' position logic behind I came across using insert and removeAt methods to make 2 elements swap their position in a list, like in the following code example:
var list = [1, 2];
list.insert(1, list.removeAt(0));

I did my best to grasp the logic behind, but I can't no matter what.
there is insert at position 1 and then remove at position 2. Is that mean that we insert in P1 what we remove from P2?
Could you explain how it works. Thanks

A: list.removeAt(int index1) removes the value at  and returns the value at given index1.
Similarly list.insert(int index2, E element) inserts element E at given index2.
So what's happening is, when you call
var list = [1, 2];
list.insert(1, list.removeAt(0));

list.removeAt(0) removes the element at index 0 first and then returns 1(the element at position 0) then the list looks like [2] and the statement looks like list.insert(1,1); and , with element 2 at index 0, now the statement means to insert element 1 at index 1 so the list will be updated to [2,1] which is equivalent to swapping.
This works only because the element at position 0 is 1 what if there is some other element at position 0 then the insertion would result in undesired output.
Hope you get my point.


text:
Q: Prove that for all $x$, $\sum_{j=0}^{n}ℓ_j(x)=1$ Prove that for all $x$, $\sum_{j=0}^{n}ℓ_j(x)=1$
$ℓ_j(x)$ are obtained by means of Lagrange interpolation and are defined as $ℓ_j(x)=\prod_{i=0, i\neq j}^{n}\frac{x-x_i}{x_j-x_i}$ where
$x_i, i=0,1,...,n$ are the nodes given to interpolate, with which I have to prove that $\sum_{j=0}^{n}\prod_{i=0, i\neq j}^{n}\frac{x-x_i}{x_j-x_i}=1$ but I do not know how to do this, could someone help me please? Thank you very much.

A: Consider the polynomial
$$
Q(x) \stackrel{\rm def}{=} \sum_{j=0}^n \ell_j(x) -1\,.
$$
which is a polynomial of degree at most $n$ as every $\ell_j$ is.
It is easy to check that, for any $j$ and $i$, $$\ell_j(x_i) = \begin{cases} 0&\text{ if } i\neq j\\
1&\text{ if } i=j
\end{cases}$$
and therefore, we have, for every $0\leq i\leq n$,
$$
Q(x_i) = \sum_{j=0}^n \ell_j(x_i) - 1 = \ell_i(x_i) - 1 = 1-1=0
$$
and since $Q$ is a polynomial of degree at most $n$ with $n+1$ roots, it has to be identically zero.

A: $ \sum_{j=0}^{n}\ell_j(x)= \sum_{j=0}^{n} 1 \ell_j(x)$ is the expression of Lagrange interpolation for the constant function $1$.


text:
Q: Netlify says, "error Gatsby requires Node.js 14.15.0 or higher (you have v12.18.0)"—yet I have the newest Node version? After migrating from Remark to MDX, my builds on Netlify are failing.
I get this error when trying to build:
10:13:28 AM: $ npm run build
10:13:29 AM: > blog-gatsby@0.1.0 build /opt/build/repo
10:13:29 AM: > gatsby build
10:13:30 AM: error Gatsby requires Node.js 14.15.0 or higher (you have v12.18.0).
10:13:30 AM: Upgrade Node to the latest stable release: https://gatsby.dev/upgrading-node-js

Yet when I run node -v in my terminal, it says v17.2.0.
I assume it's not a coincidence that this happened after migrating. Can the problem be because of my node-modules folder? Or is there something in my gatsby-config.js or package.json files I need to change?
My package.json file:
{
  "name": "blog-gatsby",
  "private": true,
  "description": "A starter for a blog powered by Gatsby and Markdown",
  "version": "0.1.0",
  "author": "Magnus Kolstad <kolstadmagnus@gmail.com>",
  "bugs": {
    "url": "https://kolstadmagnus.no"
  },
  "dependencies": {
    "@mdx-js/mdx": "^1.6.22",
    "@mdx-js/react": "^1.6.22",
    "gatsby": "^4.3.0",
    "gatsby-plugin-feed": "^4.3.0",
    "gatsby-plugin-gatsby-cloud": "^4.3.0",
    "gatsby-plugin-google-analytics": "^4.3.0",
    "gatsby-plugin-image": "^2.3.0",
    "gatsby-plugin-manifest": "^4.3.0",
    "gatsby-plugin-mdx": "^3.4.0",
    "gatsby-plugin-offline": "^5.3.0",
    "gatsby-plugin-react-helmet": "^5.3.0",
    "gatsby-plugin-sharp": "^4.3.0",
    "gatsby-remark-copy-linked-files": "^5.3.0",
    "gatsby-remark-images": "^6.3.0",
    "gatsby-remark-prismjs": "^6.3.0",
    "gatsby-remark-responsive-iframe": "^5.3.0",
    "gatsby-remark-smartypants": "^5.3.0",
    "gatsby-source-filesystem": "^4.3.0",
    "gatsby-transformer-sharp": "^4.3.0",
    "prismjs": "^1.25.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-helmet": "^6.1.0",
    "typeface-merriweather": "0.0.72",
    "typeface-montserrat": "0.0.75"
  },
  "devDependencies": {
    "prettier": "^2.4.1"
  },
  "homepage": "https://kolstadmagnus.no",
  "keywords": [
    "blog"
  ],
  "license": "0BSD",
  "main": "n/a",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/gatsbyjs/gatsby-starter-blog.git"
  },
  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,md}\"",
    "start": "gatsby develop",
    "serve": "gatsby serve",
    "clean": "gatsby clean",
    "test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1"
  }
}

What am I doing wrong here?

Update #1
7:11:59 PM: failed Building production JavaScript and CSS bundles - 20.650s
7:11:59 PM: error Generating JavaScript bundles failed
7:11:59 PM: Module build failed (from ./node_modules/url-loader/dist/cjs.js):
7:11:59 PM: Error: error:0308010C:digital envelope routines::unsupported
7:11:59 PM:     at new Hash (node:internal/crypto/hash:67:19)
7:11:59 PM:     at Object.createHash (node:crypto:130:10)
7:11:59 PM:     at getHashDigest (/opt/build/repo/node_modules/file-loader/node_modules/loader-utils/lib/getHashDigest.js:46:34)
7:11:59 PM:     at /opt/build/repo/node_modules/file-loader/node_modules/loader-utils/lib/interpolateName.js:113:11
7:11:59 PM:     at String.replace (<anonymous>)
7:11:59 PM:     at interpolateName (/opt/build/repo/node_modules/file-loader/node_modules/loader-utils/lib/interpolateName.js:110:8)
7:11:59 PM:     at Object.loader (/opt/build/repo/node_modules/file-loader/dist/index.js:29:48)
7:11:59 PM:     at Object.loader (/opt/build/repo/node_modules/url-loader/dist/index.js:127:19)
7:11:59 PM:
7:11:59 PM: ────────────────────────────────────────────────────────────────
7:11:59 PM:   "build.command" failed
7:11:59 PM: ────────────────────────────────────────────────────────────────
7:11:59 PM:
7:11:59 PM:   Error message
7:11:59 PM:   Command failed with exit code 1: npm run build
7:11:59 PM:
7:11:59 PM:   Error location
7:11:59 PM:   In Build command from Netlify app:
7:11:59 PM:   npm run build
7:11:59 PM:
7:11:59 PM:   Resolved config
7:11:59 PM:   build:
7:11:59 PM:     command: npm run build
7:11:59 PM:     commandOrigin: ui
7:11:59 PM:     publish: /opt/build/repo/public
7:11:59 PM:     publishOrigin: ui
7:11:59 PM:   plugins:
7:11:59 PM:     - inputs: {}
7:11:59 PM:       origin: ui
7:11:59 PM:       package: '@netlify/plugin-gatsby'
7:11:59 PM:   redirects:
7:12:00 PM:     - from: /api/*
      status: 200
      to: /.netlify/functions/gatsby
    - force: true
      from: https://magnuskolstad.com
      status: 301
      to: https://kolstadmagnus.no
  redirectsOrigin: config
Caching artifacts

A: The problem is that you have Node 17.2.0. locally but in Netlify's environment, you are running a lower version (by default it's not set as 17.2.0). So the local environment is OK, Netlify environment is KO because of this mismatch of Node versions.
When Netlify deploys your site it installs and builds again your dependencies so you should ensure that both environments work under the same conditions. Otherwise, both node_modules will differ so your application will have different behavior or eventually won't even build because of dependency errors.
You can easily play with the Node version in multiple ways but I'd recommend using the .nvmrc file. Just run the following command in the root of your project:
node -v > .nvmrc

This should create a .nvmrc file containing the Node version (node -v) in it. When Netlify finds this file during the build process, it uses it as a base Node version so it installs all the dependencies accordingly.
The file is also useful to tell other contributors which Node version are you using and works along with NVM using nvm use command.

A: You can also set the Node and NPM versions by adding a netlify.toml file to the root of your website project before committing your build to Netlify:
[build.environment]
    NODE_VERSION = "14.15.0"
    NPM_VERSION = "8.5.5"

Credits : https://www.surinderbhomra.com/Blog/2022/06/16/Netlify-Error-Gatsby-Requires-Node-JS-xxx-or-higher


text:
Q: Im trying to get this code to do a multiple keyword search When I type about three keywords or more it seems to only search the last keyword i.e sydney+region+nsw it will only search nsw.
I want it to search multiple keywords or the complete search term when inputted.
This is the code:
if($_REQUEST['searchkey']!="" && $_REQUEST['searchkey']=="search_record"){
    //Remove any html/javascript.
    $keyword = secureValue($_REQUEST['keyword']);
    $cat_id = intval($_REQUEST['cat_level_root']);
    $subcat_id = intval($_REQUEST['cat_level_one']);
    $sub_subcat_id = intval($_REQUEST['cat_level_two']);
    $stateId = intval($_REQUEST['classi_state']);
    $hometownId = intval($_REQUEST['classi_zipcode']);
    $servicesId = intval($_REQUEST['classified_desc9']);
    $cityId = intval($_REQUEST['classi_city']);
    $priceId = intval($_REQUEST['classified_title9']);
    $ad_key = intval($_REQUEST['ad_id']);

    $types = array();
    $types_x = explode(" ",$keyword);
    $keyword = trim($_REQUEST['keyword']);
    foreach($types_x as $keyword) {
        $x++;
        if($x==0)
            $types[]=($keyword!="" && $keyword!="Enter Your Keywords..") ? " " : "";
    }
    $types=implode($types);
    $columns = "SELECT SQL_CALC_FOUND_ROWS *  ";
    $sql = " FROM tbl_classified
        WHERE  clsd_sub_subcat_id=1395 AND CONCAT(classified_title, ' ',
            classified_desc, '   ',  classified_type6, ' ', classified_title2, ' ",
            classified_type, ' ', classified_type2, ' ', classified_type3, ' ',
            classified_desc3, ' ', classified_type5) LIKE '%$keyword%'
            and classified_status='Active'
            and paid_status!='Pending'
        ORDER BY classified_post_date,classified_featured asc $types";
    $sql = $columns.$sql;
    $rs_classi=db_query($sql);
    $res_classi = mysql_fetch_array(db_query("Select FOUND_ROWS() as total"));
    $reccnt=$res_classi['total'];
}

A: You explode the keyword string with spaces. $types_x = explode(" ",$keyword);
Explode with + (eg. explode("+", $keyword)) or use urldecode before explode.


text:
Q: Send an Email to new users added to an ACF User Field I am trying to have an email send when a user is added to an ACF user field, I don't want existing users that are in the field already to be notified. Below are a few options I have tried, but am not having luck with. Any assistance would be greatly appreciated.
Option 1:
add_action( 'acf/save_post', 'my_acf_save_hook_email'); function my_acf_save_hook_email( $post_id ) {
// // Get the list of user ids that are currently in the ACF field
$current_pds_project_managers = get_field('pds_project_manager');

// Get the list of user ids that were just added to the ACF field
$added_pds_project_managers = $_POST['pds_project_manager'];

// Get the list of user ids that are newly added, and not already in the ACF field
$newly_added_pds_project_managers = array_diff($added_pds_project_managers, $current_pds_project_managers);

// Send an email to each newly added user
foreach ($newly_added_pds_project_managers as $user) {
    $user_email = $user['user_email'];
    wp_mail( $user_email, 'You have been added to a project', 'You can now access the project from your dashboard.' );
}
}

Option 2: (this ends up sending 2 emails to the existing users in the field and one email to the new user, I then started with option one to see if I could only get the new users to no avail)
add_action( 'acf/save_post', 'my_acf_save_hook_email', 5); function my_acf_save_hook_email( $post_id ) {

// bail early if no pds_project_manager
if( empty('pds_project_manager') ) {
return; }

// Get the value of the ACF field
$project_managers = get_field('pds_project_manager', '');
// Create an empty array to store the emails
$emails_to_send = array();

// Loop through the project managers
foreach ($project_managers as $project_manager) {
// Get the user data
$user_email = $project_manager['user_email'];
$user_id = $project_manager['ID'];

// Check if the user already exists in the array
if (!in_array($user_id, $project_managers)) {
// Add the user to the emails to send
$emails_to_send[] = $user_email; } }
// Send emails to the users
foreach ($emails_to_send as $email_to_send) {
// Send the email
wp_mail($email_to_send, 'You Have Been Added To A Project', 'You have been added to a project. Please check the project page for more information.'); } }


text:
Q: Mollifier at the discontinuous point Let $f\in C^0(S^1\backslash\{p\})\cap L^\infty(S^1)$ for some $p\in S^1$. I guess $$\lim_{\epsilon\rightarrow 0}f_\epsilon(p)=\frac{1}{2}\lim_{x\rightarrow p-}f(x)+\frac{1}{2}\lim_{x\rightarrow p+}f(x)$$ when $f$ is nice enough, where $f_\epsilon$ is $\epsilon-$mollification of $f$.
Question : Is my guess true? If so, what gives sufficient condition for $f$ so the guess is satisfied?

A: Let $$f_-(x):=\bigg\{\begin{array}{cc} f(x)\quad \text{on}\quad [p-1/2,p]\\ f(-x) \quad\text{on}\quad[p,p+1/2]\end{array},$$$$f_+(x):=\bigg\{\begin{array}{cc} f(-x)\quad \text{on}\quad [p-1/2,p]\\ f(x) \quad\text{on}\quad[p,p+1/2]\end{array}.$$ Then $f_-$ and $f_+$ are even at $p$, and continuous. Therefore, $$f_\epsilon(p)=\int_{(p-\epsilon/2,p+\epsilon/2)}\eta_\epsilon(x-p)f(x)dx=\int_{(p-\epsilon/2,p)}\eta_\epsilon(x-p)f(x)dx+\int_{(p,p+\epsilon/2)}\eta_\epsilon(x-p)f(x)dx=\frac{1}{2}\int_{(p-\epsilon/2,p)}\eta_\epsilon(x-p)f_-(x)dx+\frac{1}{2}\int_{(p,p+\epsilon/2)}\eta_\epsilon(x-p)f_+(x)dx=\frac{1}{2}{f_-}_\epsilon(p)+\frac{1}{2}{f_+}_\epsilon(p)\xrightarrow{\epsilon\rightarrow 0}\frac{1}{2}(f_-(p)+f_+(p))=\frac{1}{2}(\lim_{x\rightarrow p-}f(x)+\lim_{x\rightarrow p+}f(x)).$$


text:
Q: Mysql few left join duplicate results The results of the two left joins are duplicated as many times as the record in the second left join
A problem occurs when there is more than one left join.
How can I edit it to solve the problem?
Thanks in advance.
    SELECT
            `p`.*,
            GROUP_CONCAT(CONCAT(`pi`.`id`, '-', `pi`.`img_path`) SEPARATOR ',') AS `images`,
            GROUP_CONCAT(`fp`.`filter_id` SEPARATOR \',\') AS `filter_options`
        FROM
            `products` AS `p`
        LEFT JOIN
            `product_images` AS `pi` ON (`pi`.`product_id` = `p`.`id`)
        LEFT JOIN
            `filters_products` AS `fp` ON (`fp`.`product_id` = `p`.`id`)
        WHERE
            `p`.`id` = ?
        GROUP BY
            `p`.`id`

A: The problem here is that if left joins are having multiple rows with given ID, results in group_concat will be multiplied also. There are several ways to tackle this problem, but likely easiest way is to use DISTINCT keyword. Although, it won't work correctly if it's intended that results could have multiple similar values. Another approach would be using subqueries instead of joins.
Here is an example use of DISTINCT in given query:
SELECT
            `p`.*,
            GROUP_CONCAT(DISTINCT CONCAT(`pi`.`id`, '-', `pi`.`img_path`) SEPARATOR ',') AS `images`,
            GROUP_CONCAT(DISTINCT `fp`.`filter_id`  SEPARATOR \',\') AS `filter_options`
        FROM
            `products` AS `p`
        LEFT JOIN
            `product_images` AS `pi` ON (`pi`.`product_id` = `p`.`id`)
        LEFT JOIN
            `filters_products` AS `fp` ON (`fp`.`product_id` = `p`.`id`)
        WHERE
            `p`.`id` = ?
        GROUP BY
            `p`.`id`

A: This solved the problem.
Tnx to all
    SELECT
        `p`.*, `pi`.`images`, `fp`.`filter_options`
    FROM
        `products` AS `p`
    LEFT JOIN
    (
        SELECT
            `product_id`,
            GROUP_CONCAT(CONCAT(`id`, '-', `img_path`) SEPARATOR ',') AS `images`
        FROM
            `product_images`
        GROUP BY
            `product_id`
    ) AS `pi` ON (`pi`.`product_id` = `p`.`id`)
    LEFT JOIN
    (
        SELECT
            `product_id`,
            GROUP_CONCAT(`filter_id` SEPARATOR ',') AS `filter_options`
        FROM
            `filters_products`
        GROUP BY
            `product_id`
    ) AS `fp` ON (`fp`.`product_id` = `p`.`id`)
    WHERE
        `p`.`id` = ?
    GROUP BY
        `p`.`id`


text:
Q: Best way to store some data Android i'm developing an Android app as a client of a cloud webservice. In the login screen, i download a lot of data as JSONs, like a contact list and a list of folders (only name and some feature, not the files included). After a deserialization of this JSONs, i'm storing the list of contacts and the list of folder in two static public list element on the .application file,  but in some phones (like galaxy S3 and Galaxy Note 2) when the application goes in background, they saves activities but not this list of data, so if the user come back from background after sometimes he found the app's contactlist empty or with a null pointer exception, because some phose erase this lists. Why? is that possible to save them in other ways? the data is complex, because a contact list object is complex and create a daabase is a lot of work. Another option can be the shared preferences, to store the serialized json of the contactlist, but it can be up to 2MB json.

A: this can be a good solution for you :
http://www.couchbase.com/communities/couchbase-lite

A: Here's the documentation for data storage.
Data Storage
Internal Storage will be the easiest solution. And would fit to requirements.

A: I think that static variables are almost the first thing that are being garbage collected for memory purposes, so that's why you loose this data.
In your onResume method check if your list is null, if it is start the download task again.

A: If you store your data which comes from cloud to database, then you must use transaction which will safely store all data first, then do other tasks.
Please, visit the following links to watch:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#beginTransaction%28%29

A: I normally use a very nice content-provider approach based on a small little project called Data Droid (http://www.datadroidlib.com/). The patter is very nice and reusable!


text:
Q: Using Sphinx's spellcheck in very large databases How do I implement Sphinx's companion Suggest feature on databases with large numbers of rows?
Right now, Sphinx's Suggest feature works fine on around 1,000 rows. But I am afraid that actually using Suggest, on a database with hundreds of thousands of rows, will not work out well especially if there are  new rows are added regularly (say, 100 at a time). My database also contains very specific and technical terms, so I need to actually lower the frequency limit from the default 40 to 1.
How should I work on this? My primary concern is that using by using suggest.php --builddict, I am actually rewriting the whole suggest table from scratch. Is there a better way to do this?


text:
Q: python's .replace leaves empty lines I'm using scrapy to pull data from a website. The unadulterated version comes like this:
{eps: 25}
{eps:[]}
{eps:[]}
{eps:[]}
{eps: 50}
{eps:[]}
{eps:[]}
{eps:[]}

Now I am not sure why the blank ones show up, but I am able to remove them with .replace. The issue is when I use .replace the result is like this:
25

50

# Code comment to show extra spaces.

I've tried .split, .sub, .strip to no avail. I'm not sure what else to try.
UPDATE:
Adding source code
# coding: utf-8
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.exporter import CsvItemExporter
import re
import csv
import urlparse
from stockscrape.items import EPSItem

class epsScrape(BaseSpider):
        name = "eps"
        allowed_domains = ["investors.com"]
        ifile = open('test.txt', "r")
        reader = csv.reader(ifile)
        start_urls = []
        for row in ifile:
                url = row.replace("\n","")
                if url == "symbol":
                        continue
                else:
                        start_urls.append("http://research.investors.com/quotes/nyse-" + url + ".htm")
        ifile.close()

        def parse(self, response):
                f = open("eps.txt", "a+")
                sel = HtmlXPathSelector(response)
                sites = sel.select("//tbody/tr")
                items = []
                for site in sites:
                        item = EPSItem()
                        item['eps']  = site.select("td[contains(@class, 'rating')]/span/text()").extract()
                        strItem = str(item)
                        newItem = strItem.replace(" ","").replace("'","").replace("{eps:[","").replace("]}","").replace("u","").replace("\\r\\n",'').replace('$
                        f.write("%s\n" % newItem)
                f.close()

text.txt has a stock symbols in it like this:
MSFT
A
H

so on and so forth

A: Empty lines contain newlines; replace the \n too.
If you find that you are end up removing all newlines, then split on newlines and remove any empty string values:
outputstring = '\n'.join([line for line in inputstring.splitlines() if line.strip()])

This removes any empty lines, rejoining the remaining non-empty lines with fresh newlines.
If instead you are producing the output line by line by printing or writing to a file, simply not print or write when the line is empty:
newItem = newItem.replace(.., ..)
if newItem.strip():
    print newItem
    f.write('{}\n'.format(newItem))

The if statement tests for a line that contains more than just whitespace.


text:
Q: Change Combobox dropdown items to specific colors in XAML I'm currently trying to add a Combobox in a WPF Project. The Combobox will be used to Chose between multiple Colors.
But how can i Change the Combobox items to specific Colors in XAML is my question?
I'm pretty sure how to do it in the actual Code but i would be glad if there'd be a way to "outsource" it into XAML instead.
Thanks to everyone in advance who will read/answer my question. :)

A: Well ok somehow after hours of searching i just now found the answer....
so a simple
<ComboBoxItem Background="Orange">Orange</ComboBoxItem>

The question can be closed. Sorry. :D


text:
Q: Update one property value of one object in array of objects, return updated array I am trying to update one value is_deleted in an array of objects for the deleted object.
  const handleDelete = (idx) => {
    const filteredCards = cards.map((card, i) => {
      if(i == idx) {
        card.is_deleted = true;
        return {...cards}
      }
    })
   setCards(filteredCards);
  }

Output
cards = [
  undefined,
  [
   { id: 1, is_deleted: false },
   { id: 2, is_deleted: true },
  ]
]

Desired Output
cards = [
 { id: 1, is_deleted: false },
 { id: 2, is_deleted: true },
]

The output is partially right - at index 1 I see the two cards, with the second is_deleted being set to true. However, at index 0 there is an "undefined".
Any insight into why this is would be helpful! Thank you and let me know if I missed a key piece of info.

A: You could just access the card directly, rather than using map:

let cards = [
  { id: 1, is_deleted: false },
  { id: 2, is_deleted: false },
]
const setCards = c => cards = c(cards.slice())

const handleDelete = idx => setCards(cards => (cards[idx].is_deleted = true, cards))

handleDelete(1)
console.log(cards)

The setCards function is just mimicking react's useState.


text:
Q: Dynamic Column Alias Creation & Joining I'm trying to query some data in snowflake and save myself a bunch of hard-coding
My data rows (let's call this subquery A) look something like this
| my_index  | score | some_enum |
|-----------|-------|-----------|
| abc.      | 100.  | x.        |
| abc.      | 50.   | x.        |
| abc.      | 50.   | y.        |
| abc.      | 60.   | y.        |
| def.      | 90.   | z.        |

I want to group by my_index and test_name, compute average scores, and then join all of this data back together with dynamic column names based on some_enum, so it would look something like
| my_index  | avg_score_x | avg_score_y | avg_score_z | avg_score |
|-----------|-------------|-------------|-------------|-----------|
| abc.      | 75.         | 55.         | 0/NaN/-1.   | 65.       |
| def.      | 0/NaN/-1.   | 0/NaN/-1.   | 90.         | 90.       |

Does anybody have a clean way of dynamically creating these column names and joining this data?

A: You can do conditional aggregation:
select
    myindex,
    avg(case when some_enum = 'x' then score end) avg_score_x,
    avg(case when some_enum = 'y' then score end) avg_score_y,
    avg(case when some_enum = 'z' then score end) avg_score_z,
    avg(score) avg_score
from a
group by myindex
order by myindex


text:
Q: Cannot remove fragment What I'm trying to do here is to add a fragment on incoming "show" broadcast (this works fine) and then remove it on incoming "hide" broadcast - this doesn't work, fragment is not hidden (but the broadcast is sent). Both fragmentTransaction.add() and fragmentTransaction.remove() are called but only fragmentTransaction.add() works. After calling fragmentTransaction.remove() the fragment is still present.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get extra data included in the Intent
        String message = intent.getStringExtra("message");
        Log.v("receiver", "Got message");

  if(intent.getStringExtra("message").equals("show")) {

      Log.v("fragment", "I'm trying show!");

      fragmentManager = getFragmentManager();
      fragmentTransaction = fragmentManager.beginTransaction();
      Remote fragment2 = new Remote();
      fragmentTransaction.add(R.id.fragment_container, fragment2, "RecordingRemote");
      fragmentTransaction.commit();
      fragmentManager.executePendingTransactions();

        } else if (intent.getStringExtra("message").equals("hide")) {

      Log.v("fragment", "I'm trying to hide!");

      fragmentManager = getFragmentManager();
      fragmentTransaction = fragmentManager.beginTransaction();
      Fragment fragment = fragmentManager.findFragmentByTag("RecordingRemote");
      fragmentTransaction.remove(fragment);
      fragmentManager.executePendingTransactions();

  }

    }
};

Registration:
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("Recording"));

// ...

}

A: You're missing a Commit in the whole transaction.
    fragmentTransaction.remove(fragment);
    fragmentManager.executePendingTransactions();
    fragmentTransaction.commit(); // THIS ONE YOU DON'T HAVE


text:
Q: Remove white modal image background I have an image that is showed in a modal. Unfortunately this image has a white background.
Only the image should be shown and the white shouldn't be visible.

HTML:

X

CSS:
.modal-content {
  max-height: 850px;
  max-width: 1700px;
  width: auto;
  height: auto;
  margin:0 auto;
  margin-top: 20px;
  object-fit: scale-down;
  background-color: #fff;
}
#myModal{
  height: 100%;
  width:100%;
  position:absolute;
  background-color: rgba(0, 0, 0, .5);
  display: none;
  z-index: 20;
}

JS (if needed):
$('.gallery-img').click(function(){
    $('#myModal').css('display', 'block');
    var src = $(this).attr('src');
    $('.modal-content').attr('src', src);
    $('.modal-content').data('src', src);
});
$('#close').click(function(){
    $('#myModal').css('display', 'none');
});

Edit:
Second picture for comparison:

Edit 2:
Code Pen: Link

A: You could set a transparent background color.
.modal-content {
  background-color: transparent;
}

A: Try this:
.modal-backdrop {
   background: none;
}


text:
Q: Strange margin in IE6 Here is the code:

    asdasd

    asdasd

    asdasd

    asdasd

    asdasd

    asdasd

These 2 div in IE6 are separated by white column. In FireFox it's ok (divs aren't separated). Can you please give me some advice to fix this in IE6?

A: That's a known IE6 bug. It's best to read here: http://www.positioniseverything.net/explorer/threepxtest.html
A quick fix would be to float to the left both your divs (but it's not always applicable).


text:
Q: How to call names from sub-packages from a python script running in the root directory? I have the following directory structure for my project
project_Rosa

  Rosa
      __init__.py

      filehandle
          __init__.py
          fmain.py

      punnet
          __init__.py
          pmain.py

      sequences
          __init__.py
          smain.py

  current_code.py

Rosa is the main package I am developing and I am testing the imports from current_code.py. All the __init__.pys are empty right now. fmain.py module has a function string_fasta(). The problem is I can directly import it in current_code.py with
import Rosa.filehandle.fmain as f
function = f.string_fasta

or by
import Rosa.filehandle.fmain.string_fasta as function

but when I write this
import Rosa.filehandle as R
a = R.fmain.string_fasta

I get an error
module 'Rosa.filehandle' has no attribute 'fmain'

Please address what is wrong here, and how to call names from modules shallower or deeper than the current script inside it ?


text:
Q: Getting Synthetic Base Event in console instead of that particular item Below is the code. Whenever I am clicking on add to cart, for every item. I can see an alert.
And Instead of item if I console.log something static it is also working but with item. I am getting a Synthetic Base Event in console
function Product() {
    useEffect (() => {
        fetchItems();
    },[]);

    const [items, setItems] = useState([]);

    const fetchItems = async() => {
        const data = await fetch('/product',{
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json"
            },
            credentials: "include"
        });
        const items = await data.json();
        setItems(items);
    };

    const clickMe = (item) => {
        alert("Working");
        console.log(item);
    };

    return (

Product Page

            {
                items.map(item => (

{item.productname} {item.productprice}  {item.type} add to cart

                ))
            }

    )
}

export default Product

A: Here .bind doesn't do what you think it does.
Function.prototype.bind
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
With onClick={clickMe.bind(item)} you are only binding item to the this of the function and the onClick event is still passed as the first argument to the callback.
If you are wanting to pass the currently mapped item then this needs to be passed as an additional argument.
onClick={clickMe.bind(null, item)}

You could also just use an anonymous callback function.
onClick={() => clickMe(item)}

Or declare clickMe to be a curried function and return the click handler with the item closed over in callback scope.
const clickMe = (item) => () => {
    alert("Working");
    console.log(item);
};

...

onClick={clickMe(item)}


text:
Q: How to configure epel repository manually How to configure epel repository manually when we do not have internet connection or subscription to the channel.

A: This guide shows what needs to be done to set up EPEL on CentOS 6 & 7:
6
$ sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm

7
$ yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

If you take a look at one of the RPMs you can see what files it'll set up when installed:
$ rpm -qlp epel-release-latest-7.noarch.rpm
/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
/etc/yum.repos.d/epel-testing.repo
/etc/yum.repos.d/epel.repo
/usr/lib/systemd/system-preset/90-epel.preset
/usr/share/doc/epel-release-7
/usr/share/doc/epel-release-7/GPL

The key pieces are the epel.repo and the GPG key file RPM-GPG-KEY-EPEL-7. You can manually install these 2 files and your system will be enabled for the EPEL repo.
References

*

*https://fedoraproject.org/wiki/EPEL


text:
Q: Python Twisted: twisted conch filetransfer verifyHostKey I playing around with the sftp example from here: Stackoverflow: twisted conch filetransfer
I am using this here to connect. So I can use a key from a string instead of a password or the keys in ~/.shh. Now I want to deliver a hostkey or a fingerprint from a hostkey to avoid to prompt the user to verify the hostkey
def sftp(user, host, port, key, hostkey):
    options = ClientOptions()
    options['key'] = keys.Key.fromString(key.strip()).keyObject
    options['host'] = host
    options['port'] = port
    conn = SFTPConnection()
    conn._sftp = Deferred()
    auth = SSHUserAuthClient(user, options, conn)
    connect(host, port, options, verifyHostKey, auth)
    return conn._sftp

I tried to give some arguments to verifyHostkey, as you can read in it's source the param fingerprint is not used and I haven't found a valid value for transport.
def verifyHostKey(transport, host, pubKey, fingerprint):
     """
     Verify a host's key.
     ....

Any ideas how I can omit the user to be prompted to verify a hostkey without writing the hostkey to ~/.shh/known_hosts?
Okay, I have wrote a function based on the answer of Jean-Paul Calderone. I is quite naive but does it job nice. The goal was to omit the need for an known-host file. I want all the keys only to live in memory.
def verifyHostKey(transport, host, pubKey, fingerprint):
    keytype, key = transport.factory.options['hostkey'].split(" ")[1:]
    hostkey = keytype + " " + key
    key = Key.fromString(hostkey)
    if key.fingerprint() == fingerprint:
       return succeed(True)
    else:
       raise BadKeyError

A:
I tried to give some arguments to verifyHostkey

Are you saying you tried calling verifyHostKey yourself?  It sounds like that's not going to help you avoid prompting the user for unknown host keys.  Instead, you want to pass a different function for that parameter to connect.  Instead of using the verifyHostKey function supplied by twisted.conch.client.default, use one something like this:
from twisted.internet.defer import succeed

def verifyHostKey(transport, host, pubKey, fingerprint):
    return succeed(True)

Or, if you want to implement your own checking, not just accept any host key, define a function that has that checking in it.  Return a Deferred, and if the check succeeds, fire that Deferred with True.  If the check fails, fire it with False.


text:
Q: anonymous block completed in oracle SQL Whilst trying to create a query cursor as follows:
DECLARE CURSOR Query1
IS
SELECT * FROM RACE
WHERE Race_Time='22-SEP-14 12.00.00.000000000';
BEGIN
OPEN Query1;
END;

I get the following error. anonymous block completed. Does anyone know how to fix this? I tried setting the
 'SET SERVEROUTPUT ON;'
before the declare but this did not seem to fix the error. Thanks in advance!

A: It seems that dbms_output is turned off
you can see you out put if you put SET SERVEROUTPUT ON; in the beginning of your script.
or you can view dbms_output  window (View then DBMS Output) then press the "+" at the top of the Dbms Output window and then select an open database

A: "anonymous block completed" means your PL/SQL code was successfully executed.
To Display: try using a output statement...
For example:
 BEGIN
    dbms_output.put_line ('Hello, world!');
END;

A: If you want to control the process in PL/SQL, you could do something like
DECLARE
  l_race_rec race%rowtype;

  CURSOR Query1
  IS
    SELECT *
      FROM RACE
     WHERE Race_Time='22-SEP-14 12.00.00.000000000';
BEGIN
  OPEN Query1;
  LOOP
    FETCH query1 INTO l_race_rec;
    EXIT WHEN query1%notfound;

    dbms_output.put_line( l_race_rec.column1 || ' ' || l_race_rec.column2 || ... || l_race_rec.columnN );
  END LOOP;
  CLOSE Query1;
END;

Unless your assignment requires the use of explicit cursors, though, implicit cursors are likely easier to use
BEGIN
  FOR x IN( SELECT *
              FROM RACE
             WHERE Race_Time='22-SEP-14 12.00.00.000000000')
  LOOP
    dbms_output.put_line( x.column1 || ' ' || x.column2 || ... || x.columnN );
  END LOOP;
END;

If you are using SQL*Plus, you can also do something like
VAR rc REFCURSOR;
BEGIN
  OPEN :rc
   FOR SELECT *
         FROM race
        WHERE race_time = '22-SEP-14 12.00.00.000000000';
END;
PRINT rc

If race_time is really a timestamp, you should really be comparing a timestamp with another timestamp rather than comparing a timestamp to a string.  Use explicit conversion with an explicit format mask to avoid errors due to different sessions having different NLS settings
WHERE race_time = to_timestamp( '22-SEP-14 12.00.00.000000000',
                                'DD-MON-RR HH24:MI:SS.FF9' )

Of course, I'm not sure why you would use a timestamp in the first place here-- it seems unlikely that you really know the nanosecond at which a race started.


text:
Q: Is there any way to optimise this code that uses pandas to read a TSV file, do transformations and write to a table using spark?     df_pandas = pd.read_csv('filepath/filename' , delimiter='\t' , encoding = 'utf-8', error_bad_lines=False )

    #defining the schema for the spark dataframe
    df_schema_file = StructType([StructField("Col1", StringType(), True),StructField("Col2", StringType(), True)])

    spark_df = spark.createDataFrame(df_pandas,df_schema_file)
    spark_df = spark_df.withColumn("CreatedOn", lit(from_unixtime(unix_timestamp())))
    spark_df = spark_df.withColumn("CreatedOn", spark_df["CreatedOn"].cast(TimestampType()))
    spark_df.write.mode('append').saveAsTable('tbl_name')

    #Creating dataframe from existing table
    spark_df = spark.table('tbl_name')
    df_name = spark_df.toPandas()

I am using the above code to read a TSV file, create a permenant table with the data in Databricks. This is why the conversion to spark dataframes is necessary. I also have to add the created timestamp to the table and specify the Timestamp datatype. I do not want it to be taken as string.
Then i need to create a pandas dataframe from the table so i can do some simple transformations on the data. The pandas dataframe should be made from the existing table.
Right now, this piece of code takes 2.48 minutes to run in databricks. Its too much as this used to complete in under 6seconds when i do not use the code to create a new timestamp column and specify its datatype.
Is there any way to optimise this code?
I do not know if there is any way to directly save a pandas dataframe as a table. Hence the conversion to spark dataframes. And i need to do the transformations in Pandas dataframe itself. And i dont know any method to create a pandas dataframe from the table directly. Hence first to spark and then to pandas.
Is there any way to optimise this code?

A: There is two concepts in Spark that you need to understand first:
Transformations - That means lazy operations that creates one or more other RDDs. That means nothing is actually executed just planned. Reference
Actions - that produce a non RDD result like your toPandas() this actually executes all the planning with the transformations. Reference
And about the time of execution, Spark has a really huge overhead to start the execution of any task. But it get a better performance when it is related to bigger tasks. There is a lot of cases that spark will be slower than pandas or numpy. But when you reach a specific case of Huge data the execution of Spark will by faster than any local execution. If you are running with a single machine with a small dataset like yours, pandas will be faster. Spark need to start a Session, find nodes, serialize data and etc. That is why you have this overhead. Keep learning and try with files of 100GB or more to see the performance.


text:
Q: Jquery animation on page load I've already looked at a few answered questions and none of them worked.
I am trying to make my logo rotate and translate from off the page when the page loads. I am rotating with css but using .animate to translate it. I can't find anything that makes my code work
Fiddle


text:
Q: How to update Immutable js new version using command prompt..? Environment: Windows
I am working in react immutable js with the function deleteAll() which shows error as deleteAll is not a function and also for removeAll().
deleteAll() function listed in OrderedMap official documentation.
Checked that deleteAll() is available only in version 4.0.0-rc.2 in this link.
Noticed that the file => node_modules\immutable\package.json, showing version as "version": "3.8.2" in my project.
Using the below code in my reducer also shows error, due to the old version 3.8.2:
const {OrderedMap } = require('immutable@4.0.0-rc.9');

Also tried again the command npm install immutable, same version(3.8.2) persist.
What is the windows command to update immutable js to new version 4.0.0-rc.2..?

A: Manually:
Change the version in package.json to the version you want, delete your node_modules folder and run npm install.
Via CLI:
npm install immutable@4.0.0-rc.2


text:
Q: "ModuleNotFoundError: No module named 'lxml'", although it should be imported when trying to run my Python script, I get the following error:
from lxml import objectify, etree
ModuleNotFoundError: No module named 'lxml'

I'm using a venv python environment. Before running the python script, I already activated the Virtual Environment (source myenv/bin/activate) and selected it in VS Studio Code as my Python Interpreter.
When I run "pip3 install lxml" to install to python module, I receive the following in the console:
Defaulting to user installation because normal site-packages is not writeable enter code here`Requirement already satisfied: lxml in /Users/XXXX/Library/Python/2.7/lib/python/site-packages (4.6.3)

When typing "python3" I get the following details:
Python 3.8.2 (default, Dec 21 2020, 15:06:04) [Clang 12.0.0 (clang-1200.0.32.29)] on darwin

I'm running macOS.


text:
Q: AWS Lambda Code in S3 Bucket not updating I am using cloudformation to create my lambda function with the code in a S3Bucket with versioning enabled.
"MYLAMBDA": {
      "Type": "AWS::Lambda::Function",
      "Properties": {
        "FunctionName": {
          "Fn::Sub": "My-Lambda-${StageName}"
        },
        "Code": {
          "S3Bucket": {
            "Fn::Sub": "${S3BucketName}"
          },
          "S3Key": {
            "Fn::Sub": "${artifact}.zip"
          },
          "S3ObjectVersion": "1e8Oasedk6sDZu6y01tioj8X._tAl3N"
        },
        "Handler": "streams.lambda_handler",
        "Runtime": "python3.6",
        "Timeout": "300",
        "MemorySize": "512",
        "Role": {
          "Fn::GetAtt": [
            "LambdaExecutionRole",
            "Arn"
          ]
        }
      }
    }

The lambda function gets created successfully. When i copy a new artifact zip file to the s3bucket, a new version of the file gets created with the new version  "S3ObjectVersion"  string. But the lambda function code is still using the older version.
The documentation of aws cloudformation clearly says the following

To update a Lambda function whose source code is in an Amazon S3
  bucket, you must trigger an update by updating the S3Bucket, S3Key, or
  S3ObjectVersion property. Updating the source code alone doesn't
  update the function.

Is there an additional trigger event, i need to create to get the code updated?

A: I also faced the same issue , my code was in Archive.zip in S3 bucket , when I uploaded a new Archive.zip , lambda was not responding according to new code .
Solution was to again paste the link of S3 location of Archive.zip in lambda's function code section and Save it again.
How I figured out lambda was not taking new code?
Go to your lambda function --> Actions --> Export Function --> Download Deployment Package and check if the code is actually the code that you've recently uploaded to S3 .

A: You have to update the S3ObjectVersion value to the new version ID in your CloudFormation template itself.
Then you have to update your Cloudformation stack with the new template.
You can do this either on the Cloudformation console or via the AWS CLI.

A: In case anyone is running into this similar issue, I have figured out a way in my case. I use Terraform + Jenkins to create my lambda functions through s3 bucket. In the beginning, I can create the functions but it won't update once it created. I verified my zip files in s3 is updated. It took me some time to figure out that I need do one of following two changes.
solution 1: Giving a new object key when load the new zip file. In my terraform I add the git commit id as part of the s3 key.
resource "aws_s3_bucket_object" "lambda-abc-package" {
  bucket = "${aws_s3_bucket.abc-bucket.id}"
  key    = "${var.lambda_ecs_task_runner_bucket_key}_${var.git_commit_id}.zip"
  source = "../${var.lambda_ecs_task_runner_bucket_key}.zip"
}

solution 2: add source_code_hash in lambda part.
resource "aws_lambda_function" "abc-ecs-task-runner" {
  s3_bucket         = "${var.bucket_name}"
  s3_key            = "${aws_s3_bucket_object.lambda-ecstaskrunner-package.key}"
  function_name     = "abc-ecs-task-runner"
  role              = "${aws_iam_role.AbcEcsTaskRunnerRole.arn}"
  handler           = "index.handler"
  memory_size       = "128"
  runtime           = "nodejs6.10"
  timeout           = "300"
  source_code_hash  = "${base64sha256(file("../${var.lambda_ecs_task_runner_bucket_key}.zip"))}"

So do either one should work. Also when checking lambda code, refresh the URL from the browser won't work. Need go back Functions and open that function again.
Hope this helps.

A: From AWS CLI you can do an update-function-code call like this post mentions : https://nono.ma/update-aws-lambda-function-code


text:
Q: What is the difference between __int and "char, short, int, long long int"? I am surprised to see also my C++ compiler supports __int8, __int16, __int32, and __int64; But I just see they are equivalent to char, short, int, and long long. What is the difference between them?
sizeof(__int8) == sizeof(char) == 1
sizeof(__int16) == sizeof(short) == 2
sizeof(__int32) == sizeof(int) == 4
sizeof(__int64) == sizeof(long long) == 8

A: The sizes of the primitive types int, char, short, long, etc. are implementation-defined and can vary from system to system.  All that you're guaranteed is that

*

*sizeof(char) == 1, and

*sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long).

As a result, many platforms provide their own custom, non-portable types that are guaranteed to be the given sizes.  For example, I am fairly confident that Microsoft guarantees that __int8 is always eight bits, __int16 is always 16 bits, etc.
Hope this helps!


text:
Q: Parse facebook JSON data I have problem with parsing Facebook JSon data my data formate is like this.I googled lot spend much time for this but didn't get the value.Please suggest me how to solve this problem.Your valuable answer will be great appreciated.
Json
{
   "id": "",
   "name": "",
   "first_name": "",
   "middle_name": "",
   "last_name": "",
   "link": "",
   "username": "",
   "birthday": "",
   "location": {
      "id": "",
      "name": ", "
   }

Update
Actullay i have
https://graph.facebook.com/me?access_token=
getting session.getAccessToken() and making it complete url
URL_PREFIX_FRIENDS
                    + session.getAccessToken()
then sending url for http connection and getting Jsonobject
Problem is this instead of jSonObject it gives true falue(not getting why and how)
Code for httpConnection
public class JsonParsing {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JsonParsing() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

            StringBuilder buffer = new StringBuilder();

    BufferedReader reader = new BufferedReader(new InputStreamReader(
            in, HTTP.UTF_8));

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
            json = buffer.toString();

    } finally {
        in.close();
        reader.close();
    }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

After that sending this to parser and getting following error
Logcat
E/JSON Parser( 5660): Error parsing data org.json.JSONException: Value true of type java.lang.Boolean cannot be converted to JSONObject

A: use following code.
 JSONObject json=new JSONObject(result);
      String detail=json.getString("id");
      String image=json.getString("name");

A: UPDATE : replace your function with this
public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        InputStream is = null;
        JSONObject jobj = null;
        String json = null;
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpPost = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

            StringBuilder buffer = new StringBuilder();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8));

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                json = buffer.toString();

            } finally {
                is.close();
                reader.close();
            }

            try {
                jobj = new JSONObject(json);
                System.out.println("JSON : " + jobj);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // try parse the string to a JSON object

        // return JSON String
        return jobj;

    }

Try this
This function will iterate your json recursively. Any json will parsed dynamically.
private void parseJson(JSONObject data) {

        if (data != null) {
            Iterator<String> it = data.keys();
            while (it.hasNext()) {
                String key = it.next();
                try {
                    if (data.get(key) instanceof JSONArray) {
                        JSONArray arry = data.getJSONArray(key);
                        int size = arry.length();
                        for (int i = 0; i < size; i++) {
                            parseJson(arry.getJSONObject(i));
                        }
                    } else if (data.get(key) instanceof JSONObject) {
                        parseJson(data.getJSONObject(key));
                    } else {
                        System.out.println("Key :" + key);
                        System.out.println("Value :" + data.getString(key));
                    }
                } catch (Throwable e) {
                    try {
                        System.out.println("Key :" + key);
                        System.out.println("Value :" + data.getString(key));
                    } catch (Exception ee) {
                    }
                    e.printStackTrace();

                }
            }
        }
    }

Call this function and see your logcat.
Hope this helps you.

A: Make Facebook Response as a graphObject and fetch the value of its keys.
GraphObject facebookResponseGraphObject = facebookResponse.getGraphObject();
JSONObject facebookResponseJSONObject = facebookResponseGraphObject.getInnerJSONObject();

String id = json_obj.getString("id");
String name = json_obj.getString("name");
.
.
.

facebookResponse is the response you are getting in onCompleted()


text:
Q: Xamarin.Forms Android app SQLite data disappears I am writing a Xamarin.Forms app for Android using C#. I setup the Sqlite dB at: System.Environment.SpecialFolder.Personal
When the app is deployed on device I can add data and then retrieve it.
However, when I check the app next day(offline, without debugging from pc) all the dB data is gone.
Does it mean that the dB file is gone after some time?

A: Data from DB should not gone.
Are your sure that your DB initialization code is ok? Maybe every time you started the app, tha data is restoring to some start state?

A: The mysterious dissappearance of data in a sqlite db can have multiple causes.
Make sure that your db file exists, maybe you can implement a small debug button somwhere which will throw an alert which tells you if the file exists.
However using System.Environment.SpecialFolder.Personal shouldn't be the cause, I use that folder for my apps as well.
Second, do you actively commit your transactions? Especially when your app gets backgrounded, i would recommend calling Commit() in order to make sure that every pending transaction gets written into database, since you never know when the garbage collector comes around while your app is backgrounded.
If you are working with multiple threads, make sure that you are opening your database in a mode supporting a multithreaded environment.
If you open your sqlite db with a simple
SQLiteConnection conn = new SQLite.SQLiteConnection(path);

the database will open single-threaded.
Try this instead:
SQLiteConnection conn = new SQLite.SQLiteConnection(path, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.NoMutex);

If that doesn't help, please give a bit more insight into your code (how do you open the db, how do you insert/update data, etc...)


text:
Q: Dynamically filter results with RxSwift and Realm I have a very simple project, where I want to dynamically filter content in UITableView regarding pressed index in UISegmentedControl. I'm using MVVM with RxSwift, Realm and RxDataSources. So my problem, that if I want to update content in UITableView I need to create 'special' DisposeBag, only for that purposes, and on each selection in UISegmentedControl nil it and create again. Only in this case, if I'm understand right, subscription is re-newed, and UITableView displays new results from Realm.
    So is there any better way to do such operation? Without subscribing every time, when I switch tab in UISegmentedControl. Here's my code:
//ViewController
class MyViewController : UIViewController {

  //MARK: - Props
  @IBOutlet weak var tableView: UITableView!
  @IBOutlet weak var segmentedControl: UISegmentedControl!

  let dataSource = RxTableViewSectionedReloadDataSource<ItemsSection>()
  let disposeBag = DisposeBag()

  var tableViewBag: DisposeBag!
  var viewModel: MyViewModel = MyViewModel()

  //MARK: - View lifecycle
  override func viewDidLoad() {
    super.viewDidLoad()
    self.setupRxTableView()
  }

  //MARK: - Setup observables
  fileprivate func setupRxTableView() {
    dataSource.configureCell = { ds, tv, ip, item in
      let cell = tv.dequeueReusableCell(withIdentifier: "ItemCell") as! ItemTableViewCell
      return cell
    }

    bindDataSource()

    segmentedControl.rx.value.asDriver()
      .drive(onNext: {[weak self] index in
        guard let sSelf = self else { return }
        switch index {
        case 1:
          sSelf.bindDataSource(filter: .active)
        case 2:
          sSelf.bindDataSource(filter: .groups)
        default:
          sSelf.bindDataSource()
        }
      }).disposed(by: disposeBag)
  }

  private func bindDataSource(filter: Filter = .all) {
    tableViewBag = nil
    tableViewBag = DisposeBag()
    viewModel.populateApplying(filter: filter)
      }).bind(to: self.tableView.rx.items(dataSource: dataSource))
      .disposed(by: tableViewBag)
  }
}

//ViewModel
   class MyViewModel {
      func populateApplying(filter: Filter) -> Observable<[ItemsSection]> {
       return Observable.create { [weak self] observable -> Disposable in
         guard let sSelf = self else { return Disposables.create() }
         let realm = try! Realm()
         var items = realm.objects(Item.self).sorted(byKeyPath: "date", ascending: false)
         if let predicate = filter.makePredicate() { items = items.filter(predicate) }
         let section = [ItemsSection(model: "", items: Array(items))]
         observable.onNext(section)

         sSelf.itemsToken = items.addNotificationBlock { changes  in
           switch changes {
             case .update(_, _, _, _):
             let section = [ItemsSection(model: "", items: Array(items))]
             observable.onNext(section)
             default: break
          }
        }
        return Disposables.create()
       }
     }
   }

A: Don't recall if this is breaking MVVM off the top of my head, but would Variable not be what you're looking for?
Variable<[TableData]> data = new Variable<[TableData]>([])

func applyFilter(filter: Predicate){
  data.value = items.filter(predicate) //Any change to to the value will cause the table to reload
}

and somewhere in the viewController
viewModel.data.rx.asDriver().drive
        (tableView.rx.items(cellIdentifier: "ItemCell", cellType: ItemTableViewCell.self))
{ row, data, cell in

    //initialize cells with data
}


text:
Q: Using LINQ in an Update Method - trouble with where clause I'm writing an update method that passes in a list of objects to be updated, I'm wondering how I would write a LINQ query to grab all the objects from the database that need to be updated
This is an example of my update method with the linq query that I'm trying to make (pseudo-code used for the part I don't know how to do)
void UpdateObjects(List<MyObjects> updatedObjects)
{

    DatabaseContext myContext = new DatabaseContext();

    var originalObjectsThatRequireUpdating = from o in myContext.MyObjects
                                             where o.ID matches one of updatedObjects.ID
                                             select o;

    foreach (var originalObject in originalObjectsThatRequireUpdating )
    {
         IEnumerable<MyObjects> tmpItem = updatedObjects.Where(i => i.ID == originalObject.ID);

         originalObject.Field1 = tmpItem.ToList()[0].Field1;
         //copy rest of the fields like this
    }

    myContext.SubmitChanges();

}

I don't know how to create a linq query easily with something like
 where o.ID matches one of updatedObjects.ID

also if someone knows an easier way to accomplish what I'm doing please tell, this seems sort of like an odd way to do it, but was the only way I can think of / know how to do at this point.

A: you can do that with:
where updatedObjects.Any(uo => uo.ID == o.ID)

A: You should be looking to implement batch updates with linq for example like it's described at http://www.aneyfamily.com/terryandann/post/2008/04/Batch-Updates-and-Deletes-with-LINQ-to-SQL.aspx

A: You could create a lambda or another method that performs the check for you; for example
where IDMatches(o.ID, updatedObjects)

and then define IDMatches as a simple iteration over updatedObjects.
static void IDMatches(int id, List<MyObject> updatedObjects)
{
    foreach (MyObject updated in updatedObjects)
    {
        if (id == updated.ID)
            return true;
    }
    return false;
}


text:
Q: Word for "have an effect over surroundings" Is there one word for "having an effect/impact/influence over the surroundings/environment"?
For example,

20th century was ____, which may have resulted in changes to earth's soil microorganisms.

I considered the word influential, but it doesn't seem to be specifically about the surroundings/environment.
The kind of impact can be either positive or negative, I'm looking for the technical ability to change one's environment.
Another example,

while most animals have indirect effect on their environment, beavers are ____, with their engineering abilities

Perhaps the word I'm looking for might be a term from Biology,
or a term from Mechanics, like an object's potential of exerting force, doing an action which results in an effect over something else.

A: Good question.
I don't really think there is 'one' specific word you can utilise to define something which impacts an environment. If you are specifically talking about the change that the 20th Century has had on the environment, you could use a word such as 'alter', 'modified', 'metamorphosed', 'transformed' or 'transmuted'.
Also I don't think your sentence example really works. Maybe a better example would be 'The 20th Century has markedly altered the earth's microorganism composition in soil.'
All the best

A: I presume you're looking for an adjective here. Taking a cue from Electron Ninja's answer, I offer transformative.

causing or able to cause an important and lasting change in someone or something

Even if students end up in different fields, the skills learned in the mechatronics program are transformative, instructor Sheldon Ingersoll said.
— Emily Donaldson, Dallas News, 30 May 2021
[Merriam-Webster]


text:
Q: PDF issue while reaching end of page Well I'm having some troubles when creating new pages.
I get my data from a query.
Sorry if I post a lot of code, but it's all needed and I'm not sure how to do a MCVE as I'm pretty new at working with PDF.
This issue is:
Before writing next block of code I check current Y coord, I can achieve this, but when I need to create new Page and start writing again, well happens this
Here are the codes used in the PDF:
public float checkContentStream(float y) throws Exception {
    float newY = checkYCoord(y, 3, 10);
    if (newY == 700) {
        if (content != null) {
        content.close();
        }

        File file = new File(logoPath);
        PDJpeg logoImg = new PDJpeg(doc, new FileInputStream(file));
        PDPage page = new PDPage(PDPage.PAGE_SIZE_LETTER);
        doc.addPage(page);
        content = new PDPageContentStream(doc, page);
        content.drawImage(logoImg, 50, 720);
        rHeader();
    }
    return newY;
    }

This method checks if reached BOTTOM MARGIN = 60
private float checkYCoord(float y, int lines, int space) {
    float newY = y;
    for (int i = 0; i < lines; i++) {
        if ((newY - space) <= BOTTOM_MARGIN) {
        newY = 700f;
        return newY;
        } else {
        newY = newY - space;
        }
    }
    return y;
    }

This method does the same as 1st but used both, I know I shouldn't and must not use hardcoded values, like 10 or 3.
public float checkContentStream(float y, int lines, int space) throws Exception {
    float newY = checkYCoord(y, lines, space);
    if (newY == 700) {
        if (content != null) {
        content.close();
        }
        File file = new File(logoPath);
        PDJpeg logoImg = new PDJpeg(doc, new FileInputStream(file));
        PDPage page = new PDPage(PDPage.PAGE_SIZE_LETTER);
        doc.addPage(page);
        content = new PDPageContentStream(doc, page);
        content.drawImage(logoImg, 50, 720);
        rHeader();
    }
}

public float rText(float x, float y, int space, String labelField, String value, int fieldSize) throws Exception {
    if(fieldSize == 1){
        return rText(x, y, space, labelField, value, FIELD_WIDTH, VALUE_WIDTH);
        }
    else{
        if(fieldSize == 2){
        return rText(x, y, space, labelField, value, FIELD_WIDTH, DESC_WIDTH);
        }
        else{
        return rText(x, y, space, labelField, value, FIELD_WIDTH, TEXT_WIDTH);
        }
    }
}

I'm almost sure the error comes from this method:
public float rText(float x, float y, int space, String labelField, String value, int fieldWidth, int valueWidth) throws Exception {
    PDFont font = PDType1Font.TIMES_BOLD;
    content.setFont(font, 9);
    float y1 = 0f;
    float y2 = 0f;
    //y = y >= 700 ? 700 : checkContentStream(y, 3, 10);
    if (value == null) {
        //y = checkYCoord(y, 1, 10);
        return rText(labelField, fieldWidth, x, y - 19, space, font, false);
        }else {
        //y = checkYCoord(y, 3, 10);
        y1 = rText(labelField, fieldWidth, x, y - 20, space, font, false);
        font = PDType1Font.TIMES_ROMAN;
        content.setFont(font, 9);
        y = checkYCoord(y, 3, 10); // Comment / Uncoment this line
        y2 = rText(value, valueWidth, x + fieldWidth + 10, y - 20, space, font, true);
        if (y1 >= y2) {
        return y2;
        } else {
        return y1;
        }
    }
}

This method paints text
private float rText(String text, int width, float x, float y, int space, PDFont font, boolean isValue) throws Exception {
    float newY = y;
    int rowHeight = 0;
    ArrayList<String> rowList = getRows(text, width, font);
    if(isValue){
        newY = checkContentStream(newY);
        newY = newY == 700 ? 680 : newY;
        for (String row : rowList) {
        if(rowHeight >= 10){
            newY = checkContentStream(newY - 10);
            newY = newY == 700 ? 680 : newY;
        }
        else{
            newY = checkContentStream(newY);
            newY = newY == 700 ? 680 : newY;
        }
        content.beginText();
        content.moveTextPositionByAmount(x, newY);
        content.drawString(row);
        content.endText();
        rowHeight = rowHeight + 10;
        }
    }
    else{
        newY = checkContentStream(newY, rowList.size(), space);
        newY = newY == 700 ? 680 : newY;
        for(String row : rowList){
        content.beginText();
        content.moveTextPositionByAmount(x, newY - rowHeight);
        content.drawString(row);
        content.endText();
        rowHeight = rowHeight + 10;
        }
        newY -= (rowHeight - 9);
    }
    return newY;
}

This method which is in another class brings data from query:
private float renderSubscriptionNew(PdfRenderingPC pdf, float y, SubscriptionNew sNew) throws Exception {
    DataResponse dr = dataSvc.buildResponse(folio, sNew, unitSvc);
    List<Data> dataList = dr.getDataList();

    int i = 0;
    int j = 0;
    float y2[] = new float[3];
    for (Data data : dataList) {
        String labelField = constants.getString(data.getName());
        String value = getValue(data);
        float xCoord = 0;
        boolean getNewRow = false;
        int fieldSize = 1;
        switch (i) {
        case 0:
        case 4:
        xCoord = LEFT_MARGIN;
        break;
        case 1:
        case 5:
        xCoord = MIDDLE_COL;
        break;
        case 2:
        case 6:
        xCoord = RIGHT_COL;
        getNewRow = true;
        break;
        case 3:
        xCoord = LEFT_MARGIN;
        getNewRow = true;
        break;
        }
        if (getNewRow) {
        if(j == 0){
            y = pdf.rText(xCoord, y, 10, labelField, value, fieldSize);
        }
        else{
            y = pdf.rText(xCoord, y, 10, labelField, value, fieldSize);
            float min = y;
            for(int k = (j - 1); k >= 0; k--){
            if(y2[k] < min){
                min = y2[k];
            }
            }
            y = min;
            j = 0;
        }
        } else {
            y2[j] = pdf.rText(xCoord, y, 10, labelField, value, fieldSize);
            j++;
        }
        i++;
}

Any help, guide, would be pretty apreciated and thanks in advance

A: Thanks to @mkl for his comment, I solved it like this:
I added the following code on 'renderSubscriptionNew'
if(visible){
    if (getNewRow) {
        if(j == 0){
        y = pdf.checkContentStream(y, 3, 10);
        y = pdf.rText(xCoord, y, 10, labelField, value,
                  fieldSize);
        }
        else{
        y = pdf.rText(xCoord, y, 10, labelField, value,
                  fieldSize);
        float min = y;
        for(int k = (j - 1); k >= 0; k--){
            if(y2[k] < min){
            min = y2[k];
            }
        }
        y = min;
        j = 0;
        }

    } else {
        if(j == 0){
        y = pdf.checkContentStream(y, 3, 10);
        }
        y2[j] = pdf.rText(xCoord, y, 10, labelField, value,
                  fieldSize);
        j++;
    }
    }
    i++;
}

And this is rText (the last one):
private float rText(String text, int width, float x, float y, int space,
        PDFont font, boolean isValue) throws Exception {
float newY = y;
int rowHeight = 0;
ArrayList<String> rowList = getRows(text, width, font);
if(isValue){
    for (String row : rowList) {
    if(rowHeight >= 10){
        newY = checkContentStream(newY - 10);
        newY = newY == 700 ? 680 : newY;
    }
    else{
    }
    content.beginText();
    content.moveTextPositionByAmount(x, newY);
    content.drawString(row);
    content.endText();
    rowHeight = rowHeight + 10;
    }
}
else{
    for(String row : rowList){
    content.beginText();
    content.moveTextPositionByAmount(x, newY - rowHeight);
    content.drawString(row);
    content.endText();
    rowHeight = rowHeight + 10;
    }
    newY -= (rowHeight - 9);
}
return newY;
}


text:
Q: Flutter - Show Row on extra scroll - Top of column (Like Whatsapp Archived Chats) I want to put a row on top of a column, which will not be visible initially. It will only be visible when the scroll offset of the SingleChildScrollview is negative.
In other words, only if the user scrolls further than normal (downwards motion) will this Row show. This is an example in Whatsapp. The "Search Box" widget is not shown initially, only if you scroll up, and disappears once scroll is downwards.

UPDATE
Using @Lulupointu's answer, I was able to get to this:

The top widget shows and hides on scroll with a smooth animation.
@Hooshyar's answer also works but is less smooth and uses a different method.

A: Using singleChildScrollView here is what I came up with using s NotificationListener() widget, there are other solutions but this one is the simplest one:
have a bool to determine Container visibility:
  bool shouldIShowTheUpperThing = false;

the have your SingleChildScrollView() wrapped with a NotificationListener() :
NotificationListener(
        child: SingleChildScrollView(
          child: Column(
            children: [
              shouldIShowTheUpperThing == false ? Row(
    children: [
      Container(height: 0,),
    ],
    ) :   Row(
    children: [
      Expanded(child: Container(color: Colors.red , height: 100 , child: Text('the hidden box'),)),
    ],
    ),
              Container(
                padding: EdgeInsets.all(130),
                child: Text('data'),
                color: Colors.blueGrey,
              ),
              Container(
                padding: EdgeInsets.all(130),
                child: Text('data'),
                color: Colors.blueAccent,
              ),
              Container(
                padding: EdgeInsets.all(130),
                child: Text('data'),
                color: Colors.amber,
              ),
              Container(
                padding: EdgeInsets.all(130),
                child: Text('data'),
                color: Colors.black12,
              ),
              Container(
                padding: EdgeInsets.all(130),
                child: Text('data'),
              ),
            ],
          ),
        ),

        onNotification: (t) {
          if (t is ScrollNotification) {
            if (t.metrics.pixels < 1.0) {
              setState(() {
                shouldIShowTheUpperThing = true;
              });
            }
          }
          return true;
        });
  }

A: try SliverAppBar and set floating and snap named params to true
class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
        const  SliverAppBar(
            pinned: true,
            snap: true,
            floating: true,
            expandedHeight: 160.0,
            flexibleSpace: FlexibleSpaceBar(
              title:  Text('SliverAppBar'),
              background: FlutterLogo(),
            ),
          ),
          const SliverToBoxAdapter(
            child: SizedBox(
              height: 20,
              child: Center(
                child: Text('Scroll to see the SliverAppBar in effect.'),
              ),
            ),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return Container(
                  color: index.isOdd ? Colors.white : Colors.black12,
                  height: 100.0,
                  child: Center(
                    child: Text('$index', textScaleFactor: 5),
                  ),
                );
              },
              childCount: 20,
            ),
          ),
        ],
      ),
    );
  }
}

A: Since this is a unusual scroll effect, if you want it to look good I think you need to use slivers.
Implementation
What I did was copy paste SliverToBoxAdapter and modify it.
Features:

*

*The child is hidden when the widget is first loaded

*The child is snappy

*The child hide when the user scroll down again

Limitations:

*

*If there are not enough children in the CustomScrollView to over-scroll, the child will always be visible and a weird scroll effect will appear on startup

class SliverHidedHeader extends SingleChildRenderObjectWidget {
  const SliverHidedHeader({
    Key? key,
    required Widget child,
  }) : super(key: key, child: child);

  @override
  RenderObject createRenderObject(BuildContext context) {
    return RenderSliverHidedHeader(context: context);
  }
}

class RenderSliverHidedHeader extends RenderSliverSingleBoxAdapter {
  RenderSliverHidedHeader({
    required BuildContext context,
    RenderBox? child,
  })  : _context = context,
        super(child: child);

  /// Whether we need to apply a correction to the scroll
  /// offset during the next layout
  ///
  ///
  /// This is useful to avoid the viewport to jump when we
  /// insert/remove the child.
  ///
  /// If [showChild] is true, its an insert
  /// If [showChild] is false, its a removal
  bool _correctScrollOffsetNextLayout = true;

  /// Whether [child] should be shown
  ///
  ///
  /// This is used to hide the child when the user scrolls down
  bool _showChild = true;

  /// The context is used to get the [Scrollable]
  BuildContext _context;

  @override
  void performLayout() {
    if (child == null) {
      geometry = SliverGeometry.zero;
      return;
    }
    final SliverConstraints constraints = this.constraints;
    child!.layout(constraints.asBoxConstraints(), parentUsesSize: true);
    final double childExtent;
    switch (constraints.axis) {
      case Axis.horizontal:
        childExtent = child!.size.width;
        break;
      case Axis.vertical:
        childExtent = child!.size.height;
        break;
    }
    final double paintedChildSize =
        calculatePaintOffset(constraints, from: 0.0, to: childExtent);
    final double cacheExtent = calculateCacheOffset(constraints, from: 0.0, to: childExtent);

    assert(paintedChildSize.isFinite);
    assert(paintedChildSize >= 0.0);

    // Here are the few custom lines, which use [scrollOffsetCorrection]
    // to remove the child size
    //
    // Note that this should only be called for correction linked with the
    // insertion (NOT the removal)
    if (_correctScrollOffsetNextLayout) {
      geometry = SliverGeometry(scrollOffsetCorrection: childExtent);
      _correctScrollOffsetNextLayout = false;
      return;
    }

    // Subscribe a listener to the scroll notifier
    // which will snap if needed
    _manageSnapEffect(
      childExtent: childExtent,
      paintedChildSize: paintedChildSize,
    );

    // Subscribe a listener to the scroll notifier
    // which hide the child if needed
    _manageInsertChild(
      childExtent: childExtent,
      paintedChildSize: paintedChildSize,
    );

    geometry = SliverGeometry(
      scrollExtent: childExtent,
      paintExtent: paintedChildSize,
      paintOrigin: _showChild ? 0 : -paintedChildSize,
      layoutExtent: _showChild ? null : 0,
      cacheExtent: cacheExtent,
      maxPaintExtent: childExtent,
      hitTestExtent: paintedChildSize,
      hasVisualOverflow:
          childExtent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0,
    );
    setChildParentData(child!, constraints, geometry!);
  }

  /// Override to remove the listeners if needed
  @override
  void dispose() {
    final _scrollPosition = Scrollable.of(_context)!.position;
    if (_subscribedSnapScrollNotifierListener != null) {
      _scrollPosition.isScrollingNotifier
          .removeListener(_subscribedSnapScrollNotifierListener!);
    }
    if (_subscribedInsertChildScrollNotifierListener != null) {
      _scrollPosition.isScrollingNotifier
          .removeListener(_subscribedInsertChildScrollNotifierListener!);
    }

    super.dispose();
  }

  /// The listener which will snap if needed
  ///
  ///
  /// We store it to be able to remove it before subscribing
  /// a new one
  void Function()? _subscribedSnapScrollNotifierListener;

  /// Handles the subscription and removal of subscription to
  /// the scrollable position notifier which are responsible
  /// for the snapping effect
  ///
  ///
  /// This must be called at each [performLayout] to ensure that the
  /// [childExtent] and [paintedChildSize] parameters are up to date
  _manageSnapEffect({
    required double childExtent,
    required double paintedChildSize,
  }) {
    final _scrollPosition = Scrollable.of(_context)!.position;

    // If we were subscribed with previous value, remove the subscription
    if (_subscribedSnapScrollNotifierListener != null) {
      _scrollPosition.isScrollingNotifier
          .removeListener(_subscribedSnapScrollNotifierListener!);
    }

    // We store the subscription to be able to remove it
    _subscribedSnapScrollNotifierListener = () => _snapScrollNotifierListener(
          childExtent: childExtent,
          paintedChildSize: paintedChildSize,
        );
    _scrollPosition.isScrollingNotifier.addListener(_subscribedSnapScrollNotifierListener!);
  }

  /// Snaps if the user just stopped scrolling and the child is
  /// partially visible
  void _snapScrollNotifierListener({
    required double childExtent,
    required double paintedChildSize,
  }) {
    final _scrollPosition = Scrollable.of(_context)!.position;

    // Whether the user is currently idle (i.e not scrolling)
    //
    // We don't check _scrollPosition.activity.isScrolling or
    // _scrollPosition.isScrollingNotifier.value because even if
    // the user is holding still we don't want to start animating
    //
    // ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
    final isIdle = _scrollPosition.activity is IdleScrollActivity;

    // Whether at least part of the child is visible
    final isChildVisible = paintedChildSize > 0;

    if (isIdle && isChildVisible) {
      // If more than half is visible, snap to see everything
      if (paintedChildSize >= childExtent / 2 && paintedChildSize != childExtent) {
        _scrollPosition.animateTo(
          0,
          duration: Duration(milliseconds: 100),
          curve: Curves.easeOut,
        );
      }

      // If less than half is visible, snap to hide
      else if (paintedChildSize < childExtent / 2 && paintedChildSize != 0) {
        _scrollPosition.animateTo(
          childExtent,
          duration: Duration(milliseconds: 200),
          curve: Curves.easeOut,
        );
      }
    }
  }

  /// The listener which will hide the child if needed
  ///
  ///
  /// We store it to be able to remove it before subscribing
  /// a new one
  void Function()? _subscribedInsertChildScrollNotifierListener;

  /// Handles the subscription and removal of subscription to
  /// the scrollable position notifier which are responsible
  /// for inserting/removing the child if needed
  ///
  ///
  /// This must be called at each [performLayout] to ensure that the
  /// [childExtent] and [paintedChildSize] parameters are up to date
  void _manageInsertChild({
    required double childExtent,
    required double paintedChildSize,
  }) {
    final _scrollPosition = Scrollable.of(_context)!.position;

    // If we were subscribed with previous value, remove the subscription
    if (_subscribedInsertChildScrollNotifierListener != null) {
      _scrollPosition.isScrollingNotifier
          .removeListener(_subscribedInsertChildScrollNotifierListener!);
    }

    // We store the subscription to be able to remove it
    _subscribedInsertChildScrollNotifierListener = () => _insertChildScrollNotifierListener(
          childExtent: childExtent,
          paintedChildSize: paintedChildSize,
        );
    _scrollPosition.isScrollingNotifier
        .addListener(_subscribedInsertChildScrollNotifierListener!);
  }

  /// When [ScrollPosition.isScrollingNotifier] fires:
  ///   - If the viewport is at the top and the child is not visible,
  ///   ^ insert the child
  ///   - If the viewport is NOT at the top and the child is NOT visible,
  ///   ^ remove the child
  void _insertChildScrollNotifierListener({
    required double childExtent,
    required double paintedChildSize,
  }) {
    final _scrollPosition = Scrollable.of(_context)!.position;

    final isScrolling = _scrollPosition.isScrollingNotifier.value;

    // If the user is still scrolling, do nothing
    if (isScrolling) {
      return;
    }

    final scrollOffset = _scrollPosition.pixels;

    // If the viewport is at the top and the child is not visible,
    // insert the child
    //
    // We use 0.1 as a small value in case the user is nearly scrolled
    // all the way up
    if (!_showChild && scrollOffset <= 0.1) {
      _showChild = true;
      _correctScrollOffsetNextLayout = true;
      markNeedsLayout();
    }

    // There is sometimes an issue with [ClampingScrollPhysics] where
    // the child is NOT shown but the scroll offset still includes [childExtent]
    //
    // There is no why to detect it but we always insert the child when all
    // this conditions are united.
    // This means that if a user as [ClampingScrollPhysics] and stops scrolling
    // exactly at [childExtent], the child will be wrongfully inserted. However
    // this seems a small price to pay to avoid the issue.
    if (_scrollPosition.physics.containsScrollPhysicsOfType<ClampingScrollPhysics>()) {
      if (!_showChild && scrollOffset == childExtent) {
        _showChild = true;
        markNeedsLayout();
      }
    }

    // If the viewport is NOT at the top and the child is NOT visible,
    // remove the child
    if (_showChild && scrollOffset > childExtent) {
      _showChild = false;
      markNeedsLayout();

      // We don't have to correct the scroll offset here, no idea why
    }
  }
}

/// An extension on [ScrollPhysics] to check if it or its
/// parent are the given [ScrollPhysics]
extension _ScrollPhysicsExtension on ScrollPhysics {
  /// Check the type of this [ScrollPhysics] and its parents and return
  /// true if any is of type [T]
  bool containsScrollPhysicsOfType<T extends ScrollPhysics>() {
    return this is T || (parent?.containsScrollPhysicsOfType<T>() ?? false);
  }
}

How to use it
Use it at the top of your list of slivers:
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

void main() {
  runApp(MaterialApp(home: MyStatefulWidget()));
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: CustomScrollView(
          slivers: <Widget>[
            SliverHidedHeader(
              child: Container(
                child: Center(child: Text('SliverAppBar')),
                height: 100,
                color: Colors.redAccent,
              ),
            ),
            const SliverToBoxAdapter(
              child: SizedBox(
                height: 20,
                child: Center(
                  child: Text('Scroll to see the SliverAppBar in effect.'),
                ),
              ),
            ),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  return Container(
                    color: index.isOdd ? Colors.white : Colors.black12,
                    height: 100.0,
                    child: Center(
                      child: Text('$index', textScaleFactor: 5),
                    ),
                  );
                },
                childCount: 20,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Other resource
Check out the pull_to_refresh package if you want a different approach to solve this issue. Beware that their code is quite complex since they also have the auto-hide feature implemented, but it's worth a look if you have time.
Solve the limitation
I'm not sure the limitation can be solved using this approach. The issue is that, for performance reason, the sliver does not know anything about the one bellow it, meaning that it's quite hard to even knowing when we are in the problematic case, let alone handle it.


text:
Q: Python sklearn linear regression error: fit() missing 1 required positional argument: 'y'" I'm very new to Python and scikit-learn. I'm having difficulty working with the scikit-learn Boston data house prices data set. Please find my code below.
Thanks!
import numpy as np
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
import sklearn

bos = pd.DataFrame(boston.data)
bos.head()

bos.columns = boston.feature_names
bos.head()

boston.target[:5]

bos['PRICE'] = boston.target
bos.head()

from sklearn.linear_model import LinearRegression
X = bos.drop('PRICE', axis = 1)
lm = LinearRegression

LinearRegression.fit
lm.fit(X,bos.PRICE)

TypeError Traceback (most recent call last)
<ipython-input-52-f9496290723b> in <module>
      1 LinearRegression.fit
----> 2 lm.fit(X,bos.PRICE)

TypeError: fit() missing 1 required positional argument: 'y'

A: You should be using lm = LinearRegression() and not lm = LinearRegression.
You can use  lm.fit? to see the signature of the method. You would see that it is
Signature: lm.fit(self, X, y, sample_weight=None)

So your X is being assigned to self, and bos.PRICE to X, and it is complaining that y is not provided. Seeing the self there should give you an indication that the wrong method is being called.

A: Your lm = LinearRegression is missing the parentheses, thus the Model Object constructor is not called. Furthermore, you are not correctly fitting the model you just created. The line LinearRegression.fit is not needed.
Try the following and see if it helps:
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.linear_model import LinearRegression

boston = datasets.load_boston() # loading boston dataset
bos = pd.DataFrame(boston.data) # creating dataframe from loaded data
bos.columns = boston.feature_names

bos['PRICE'] = boston.target
bos.head()

X = bos.drop('PRICE', axis = 1)

lm = LinearRegression() # initializing LinearRegression Model
lm.fit(X,bos.PRICE) # fitting data to our LinearRegression Model