text:
Q: Placing Commas Between Names I am trying to find out if certain patterns appear within a data frame.
Suppose I have the following "dictionary of patterns" (notice "james" vs "jamesj"):
patterns <- c("john", "jack", "james", "jamesj", "jason")

The actual data frame ("date_frame") I have looks like this:
  id                                              names
1  1                                     johnjack jameS
2  2                             john/james, jasonjames
3  3                                    peter_jackjason
4  4                                   jamesjasonj jack
5  5 jamesjjason, johnjasonjohn , jason-jack sam _ peter

The final result I am trying to produce should look like this:
  id                                                         names
1  1                                             john, jack, james
2  2                                     john, james, jason, james
3  3                                            peter, jack, jason
4  4                                          jamesj, asonj,  jack
5  5 jamesj, jason, john, jason, john , jason, jack,  sam ,  peter

I tried looking at this post here (R: insert comma after each element from the output) and tried the answer provided there:
> data_frame$parsed_names = dput(data_frame$names)

  id                                                         names                                                  parsed_names
1  1                                             john, jack, james                                             john, jack, james
2  2                                     john, james, jason, james                                     john, james, jason, james
3  3                                            peter, jack, jason                                            peter, jack, jason
4  4                                          jamesj, asonj,  jack                                          jamesj, asonj,  jack
5  5 jamesj, jason, john, jason, john , jason, jack,  sam ,  peter jamesj, jason, john, jason, john , jason, jack,  sam ,  peter

But this is not corresponding to what I wanted.
I then tried this post over here (insert commas in text string after certain words in r) and tried the answer provided there:
library(gsubfn)

data_frame$parsed_names = gsubfn("\\w+", as.list(setNames(paste0(patterns, ","), patterns)),
  format(data_frame$names))

 data_frame
  id                                                         names                                                         parsed_names
1  1                                             john, jack, james     john,, jack,, james,
2  2                                     john, james, jason, james    john,, james,, jason,, james,
3  3                                            peter, jack, jason      peter, jack,, jason,
4  4                                          jamesj, asonj,  jack      jamesj,, asonj,  jack,
5  5 jamesj, jason, john, jason, john , jason, jack,  sam ,  peter jamesj,, jason,, john,, jason,, john, , jason,, jack,,  sam ,  peter

*

*Can someone please show me how to fix this?

Thank you!

A: Here's a somewhat ad-hoc answer but it meets your requirements (no change in the patterns vector):
library(tidyverse)
patterns <- c("john", "jack", "james", "jamesj", "jason")

data_frame %>%
  separate_rows(names) %>%
  mutate(name = str_split(tolower(names), paste0("(?<=(", paste0(patterns, collapse = "|"), "))"))) %>%
  unnest(name) %>%
  filter(nzchar(name)) %>%
  group_by(j = cumsum(!(name == "j"))) %>%
  summarise(name = paste(name, collapse = ""),
            id = unique(id)) %>%
  group_by(id) %>%
  summarise(name = toString(name))

## A tibble: 5 × 2
#     id name
#  <dbl> <chr>
#1     1 john, jack, james
#2     2 john, james, jason, james
#3     3 peter, jack, jason
#4     4 jamesj, asonj, jack
#5     5 jamesj, jason, john, jason, john, jason, jack, sam, peter

Previous answer:
Adding the other possible names in the patterns vector, and reordering the vector so that jamesj is preferred over james, you can then use str_extract_all.
library(stringr)
library(dplyr)

patterns <- c("john", "jack", "jamesj", "james", "jason", "asonj", "peter", "sam")
patterns <- patterns[order(nchar(patterns), decreasing = T)]

data_frame %>%
  mutate(names = lapply(str_extract_all(tolower(names), paste(patterns, collapse = "|")), toString))

#  id                                                     names
#1  1                                         john, jack, james
#2  2                                 john, james, jason, james
#3  3                                        peter, jack, jason
#4  4                                       jamesj, asonj, jack
#5  5 jamesj, jason, john, jason, john, jason, jack, sam, peter

data
data_frame <- tribble(
  ~id, ~names,
  1, "johnjack jameS",
  2, "john/james, jasonjames",
  3, "peter_jackjason",
  4, "jamesjasonj jack",
  5, "jamesjjason, johnjasonjohn , jason-jack sam _ peter"
)

A: Updated to retain whole names not in the pattern:
library(tidyverse)

data_frame <- tribble(
  ~id, ~names,
  1, "johnjack jameS",
  2, "john/james, jasonjames",
  3, "peter_jackjason",
  4, "jamesjasonj jack",
  5, "jamesjjason, johnjasonjohn , jason-jack sam _ peter"
)

patterns <- c("john", "jack", "jamesj", "james", "jason")

data_frame |>
  mutate(names = map_chr(names, ~ str_to_lower(.) |>
                           str_extract_all(str_c(c(patterns, "[a-z]{3,10}"), collapse = "|")) |>
                           unlist() |>
                           stringi::stri_remove_empty() |>
                           str_c(collapse = ", "))
         )
#> # A tibble: 5 × 2
#>      id names
#>   <dbl> <chr>
#> 1     1 john, jack, james
#> 2     2 john, james, jason, james
#> 3     3 peter, jack, jason
#> 4     4 jamesj, asonj, jack
#> 5     5 jamesj, jason, john, jason, john, jason, jack, sam, peter

Created on 2022-05-14 by the reprex package (v2.0.1)

A: It is unclear what rules you are supposed to follow to generate the final output since there seems to be a lot going on.
Here's is what I assumed which are the rules I coded into the regular expressions and the patterns they are replaced with (..let me know if I'm wrong)

*

*Add a ,  after matched words if they occur immediately before any alphabet using regex "jack(?=[:alpha:])" (This is for the words in the middle of the text, followed by other words)

*Replace special characters other than a , with a ,  using regex '(?!,)[:punct:]' (a special negative lookahead like regular expression pulled off from source)

*Add a , before spaces in between words, so   that are sandwiched between alphabets using regex '(?<=[:alpha:]) (?=[:alpha:])'

*Account for the jamesj by ignoring the james followed by a j using regex 'james(?!j)(?=[:alpha:])'
These regex are paired with their replacement texts in a named vector and passed into str_replace_all to do the substitutions.
I like the named vector approach to text substitution because you can print the vector and see at a glance what is going to be replaced with what.
Here's the full code as a reproducible example-
library(tidyverse)

# Load the data frame
# Thanks to @Mael for the code
.df <- tribble(
  ~id, ~names,
  1, "johnjack jameS",
  2, "john/james, jasonjames",
  3, "peter_jackjason",
  4, "jamesjasonj jack",
  5, "jamesjjason, johnjasonjohn , jason-jack sam _ peter"
)

# Load the pattern to place commas after;
# Note jamesj comes before james, which is a sub-pattern of (james)j
patterns <- c("john", "jack", "jamesj", "james", "jason")

# Create a named vector for the string substitutions, format :  c('regex pattern' = 'replacement', ..)
sub_pattern <- setNames(object = paste0(patterns, ', '), # append comma and space
                        nm = paste0(patterns, '(?=[:alpha:])')) # for words occurring immediately before any alphabet

# Address james and jamesj double matching
names(sub_pattern) <-
  str_replace(names(sub_pattern),
              'james(?!j).*', # replace the james matcher with
              'james(?!j)(?=[:alpha:])') # ensures james is not followed by a j

# additional substitutions
sub_pattern <- append(sub_pattern,
                      c('(?!,)[:punct:]' = ', ', # replace non comma punctuations with a comma and space
                        '(?<=[:alpha:]) (?=[:alpha:])' = ', ')) # insert comma for spaces between words
                        # '[:space:],' = ',' # remove spaces before comma if needed

# Perform the string substitutions to the names column
newdf <- mutate(.df, names_with_comma = str_replace_all(tolower(names), sub_pattern))
# converting all the text to lower case (for the S in first column, if that's not a typo..)

newdf$names_with_comma
#> [1] "john, jack, james"
#> [2] "john, james, jason, james"
#> [3] "peter, jack, jason"
#> [4] "jamesj, asonj, jack"
#> [5] "jamesj, jason, john, jason, john , jason, jack, sam ,  peter"

Created on 2022-05-14 by the reprex package (v2.0.1)
And full credits to my eternal regular expression support from the StringR cheatsheet and thanks to @Maël for the code for the data frame

A: paste | between the patterns and compare it with the tolower data_frame$names and on match add   on both sides of the match using gsub.
Replace /_, - with ,  using gsub.
trimws where whitespace is ,
data_frame$names <-
  trimws( gsub("[/_, -]+", ", ",
               gsub( paste0("(", paste(patterns, collapse="|"), ")"), " \\1 ",
                    tolower(data_frame$names) )
               )
       , whitespace = ", ")
data_frame
#  id                                                     names
#1  1                                         john, jack, james
#2  2                                 john, james, jason, james
#3  3                                        peter, jack, jason
#4  4                                       jamesj, asonj, jack
#5  5 jamesj, jason, john, jason, john, jason, jack, sam, peter

Data:
patterns <- c("john", "jack", "james", "jamesj", "jason")

data_frame <- data.frame(id=1:5, names = c("johnjack jameS",
  "john/james, jasonjames", "peter_jackjason", "jamesjasonj jack",
  "jamesjjason, johnjasonjohn , jason-jack sam _ peter"))

A: You can use crossing() from tidyr in combination with str_detect() from stringr to find each of the patterns by id.
names_from_pattern <- data_frame|> tidyr::crossing(patterns)  %>%
  dplyr::rowwise() %>%
  dplyr::filter(stringr::str_detect(names, patterns))|>
  dplyr::select(id, "names" = patterns)

Then find all other names not in the pattern
find.string <- paste(patterns, collapse = "|") #e.g. 'or' separated
other_names <- tibble(id = data_frame$id, other_names = gsub(find.string, replacement = " ", x = data_frame$names)) %>%
tidytext::unnest_tokens(., input = other_names, output = names)
# removes remaining non-letters (e.g "peter", not "peter_")
other_names$names<- gsub("[^a-z]","",other_names$names)

RBind names from the pattern with other all names
df<- rbind(names_from_pattern, other_names)

Then to format the output to your specification, use dplyr's pivot_wider() in combination with unite() from tidyr.
df <-   df |>
pivot_wider(id_cols = id, names_from = names, values_from = names) %>%
unite(.,col='names', 2:length(.), sep=', ', na.rm = TRUE)

Output:
# A tibble: 5 x 2
     id names
  <int> <chr>
1     1 jack, james, john
2     2 james, john, jason
3     3 jack, jason, peter
4     4 jack, james, jason, jamesj, asonj
5     5 jack, james, john, jason, jamesj, peter, sam

libraries:
library(dplyr)
library(stringr)
library(tidyr)
library(tidytext)


text:
Q: using angular service to make $http calls I am trying to make a $http call from angular  service and it doesn't seem to get reflected in the html
var heroSliderApp = angular.module('heroSliderApp', []);

heroSliderApp.service('heroService', function ($http) {
    this.loadSlider = function () {
        $http.get("some url that returns data")
            .then(function (response) {
                return JSON.stringify(response.data);
                //return "Hello World!"; //this doesn't work
            });
    };
});

heroSliderApp.controller('heroSliderController', function ($scope, $http, heroService) {
    $scope.sliderValue = heroService.loadSlider(); // this doesn't work
    $scope.someValue= "Testing"; //this works
});

Here the .then function gets called and response.data contains value, but the value is not getting reflected in the html

A: try this
  this.loadSlider = function () {
      return $http.get("some url that returns data")
            .then(function (response) {
                return JSON.stringify(response.data);
                //return "Hello World!"; //even this doesn't work!
            });
    };

  heroService.loadSlider ().then(function(d) {
    $scope.sliderValue = d;
  });

A: Ok so I modified according to the comments from @JB Nizet and it seem to work
var heroSliderApp = angular.module('heroSliderApp', []);

heroSliderApp.service('heroService', function ($http) {
    this.loadSlider = function () {
        return $http.get("some url here");
    };
});

heroSliderApp.controller('heroSliderController', function ($scope, $http, heroService) {
    $scope.sliderValue = "";
    heroService.loadSlider().then(function (response) {
        $scope.sliderValue = response;
    });
});

A: Change your service like
heroSliderApp.service('heroService', function ($http) {
    this.loadSlider = function () {
        $http.get("some url that returns data")
            .success(function (response) {
                return JSON.stringify(response.data);
                //return "Hello World!"; //even this doesn't work!
            }).error(function {
                 //Erro handler
            });
    };
});

and controller like
heroService.loadSlider().then(function(response) {
   $scope.sliderValue = response;
})

Now the service will return a promise and the controller will receive it. When the controller data receives the response from service, the data will be binded in your controller variable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to sum same rows and find those that are above average in mySQL? This is a sample of my database table:
visitor_id ---- url ---- duration
1 ------------ home ------- 5
1 ------------ about ------ 8
1 ------------ about ------ 3
1 ------------ contact ---- 2
1 ------------ home ------- 3
1 ------------ services --- 2

What I want to achieve is to show the urls that are more than the average of all urls. But first I need to sum the duration group by url.
For example, the average of all pages = 5+8+3+2+3 + 2 = 23 / 6 = 3.8
So the pages that will be shown is home ( 8 secs) and about (11).
How can I achieve this?
This is what I have so far
select sum(duration), url from pages where visitor_id='1' group by url

A: You can join in the average or use a having clause.  I would write this as:
select p.visitor_id, p.url, avg(p.duration)
from pages p
where visitor_id = 1
group by p.visitor_id, p.url
having avg(p.duration) > (select avg(p2.duration)
                          from pages p2
                          where p2.visitor_id = p.visitor_id
                         );

Notes:

*

*I'm guessing that visitor_id is numeric, so the constant is a number instead of a string.

*The subquery in the having clause is correlated to the outer query, so the visitor id is input only once.

*The query aggregates by both visitor id and url, so it will work for any number (or all) visitors.

A: You could use an having on subquery for avg
  select sum(duration) sum_dur, url
  from pages
  where visitor_id='1'
  group by url
  having sum_dur > (
  select avg(duration)
  from  pages
  where visitor_id='1'
  )

A: Try this:
Select url
,visitor_id
,duration
From (
select url
,visitor_id
,sum(duration) as duration
,avg(duration) over (partition by visitor_id) as avg_by_visitor_id
from pages
group by url
,visitor_id
,duration) as data
where data.avg_by_visitor_id<=data.duration


text:
Q: Only allow access to files in directory from the website they are a part of I know there are a lot of similar questions out there, and I've trawled them all, but I can't seem to get any of the solutions to work.
I have a folder on the root of my website containing uploaded files that can be viewed and downloaded from the site when a user is logged in. They are here: https://example.com/uploads (for example). I need the site to continue to be able to access them to display them (some are images) and provide links for download (pdfs etc) so the user can download them, but I want to avoid anyone who get's hold of the url of a particular file being able to download them directly, like this: https://example.com/uploads/2020/02/myfile.pdf. OR these urls getting into search engines (or if they do, the server prevents them from being accessed directly.
I've tried adding an .htaccess file in the uploads directory with the following content:
Order Deny,Allow
Deny from all
Allow from 127.0.0.1

And I've tried
Order Allow,Deny
Deny from all
Allow from 127.0.0.1

...as I read that might allow HTTPS calls from the site itself as well as local urls.
But it forbids the site and a direct url request, which is no good.
Is there a way to do this?

A:
The user interface that provides the 'official' access to the files has user authentication, yes, but the files still exist in a directory than won't stop anyone getting to them if they know the url.

You need to protect the files using the same authentication system that you are using to protect access to the user interface. The only way you could protect these resources by IP address (the client IP address) - as you are currently attempting in .htaccess - is if the client's IP is fixed and known in advance (but if this was the case then you wouldn't need another form of authentication to begin with).
So, this will primarily be an exercise in whatever scripting language/CMS is being used to authenticate the "user interface".
What you can use .htaccess for is to rewrite requests for these files to your server-side script that handles the authentication and then serves the file to the client once authenticated.
For example:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^uploads/. /serve-protected-file.php [L]

Any request for /uploads/<something> (eg. /uploads/2020/02/myfile.pdf), that maps to a valid file is routed to your script: /serve-protected-file.php.
/serve-protected-file.php would then need to do something like the following:
// 1. Parse the file being requested from REQUEST_URI

// 2. Is the requested file "protected"?
//    (Serving both protected and public files from the same directory?)

// 3. If not protected then serve/stream the resource to the client. END

// 4. If protected then authenticate the user...

// 5. If user authenticated then serve/stream the resource to the client. END

// 6. Resource is protected and user not authenticated...
//    Serve a 403 Forbidden. END

(Ideally, the location of these "protected" resources would be entirely outside of the document root - so they are "private" by default - and the URL the user uses to access these resources is entirely virtual - then you probably wouldn't need any additional coding in .htaccess and everything would be implemented by your front-controller - but that all depends on how your site is implemented and the way in which URLs are routed.)


text:
Q: UIImage loaded from URL in Xamarin / C# It has been 4 years since this question has been answered with this blog post.
Is there a standard way to create a UIImage with an image from a URL?  Something like:
UIImage image = UIImage.FromFile("http://foo.com/bar.jpg");

I feel like I'm probably missing something really simple.

A: Not a one-liner, but with very few lines you can roll your own. E.g.
static UIImage FromUrl (string uri)
{
    using (var url = new NSUrl (uri))
    using (var data = NSData.FromUrl (url))
        return UIImage.LoadFromData (data);
}

The calls, including the one from UIImage, are thread-safe.

A: You want to be sure that you load the image async so that you do not block your UI thread.  MonoTouch.Dialog includes an ImageLoader (see sec 5.3) class that you could use.
There are also a couple of variations of UrlImageStore out there to help with async loading images.
Finally, if you want to do it manually, there is a Xamarin Recipe you can use.

A: With new await/async support you can do:
public async Task<UIImage> LoadImage (string imageUrl)
        {
            var httpClient = new HttpClient();

            Task<byte[]> contentsTask = httpClient.GetByteArrayAsync (imageUrl);

            // await! control returns to the caller and the task continues to run on another thread
            var contents = await contentsTask;

            // load from bytes
            return UIImage.LoadFromData (NSData.FromArray (contents));
        }

and you call this with:
someYourUIImageObjectOnUI.Image = await this.LoadImage ("some image url");

A: I tried the above, it looks like a great idea, but I get:
Cannot implicitly convert type System.Threading.Tasks.Task<MonoTouch.UIKit.UIImage>' toMonotouch.UIKit.UIImage'
[found a solution]
The problem was because the
obj.Image = await this.LoadImage (imageUrl)
must also be in a method marked async.
Then it works!
Thanks

A: Below code should work,
public static async Task<UIImage> LoadImage(string imageUrl)
{
            var httpClient = new HttpClient();

            var contents = await httpClient.GetByteArrayAsync(imageUrl);
            return UIImage.LoadFromData(NSData.FromArray(contents));
}


text:
Q: Does the initial position of a particle matter in QM? Will the "exact" position of a particle at time $t=0$ determines its position at $t=t_p$?
For example, if the initial position of particle in a 1-D potential box [-1,1] is at (0,1), how long does it takes for the particle to be distributed as $\psi^*\psi$ in the box?
Sorry if the question is too beginner-ish

A: There is no initial position, any more than any other position. There's an initial wave function, $\psi(x, y, z) = \psi(x, y, z, 0)$. Or more generally an initial state vector $|\psi(0)>$. Yes, the initial wave function matters. And it determines -- unless there's a "measurement" that happens, and even then that depends on how you interpret QM -- the evolution thereafter at succeeding times $t_p$, as that's what Schrodinger equation tells you.
EDIT: You could set up a "wavefunction" with exact position but it's nonsense physically, it's a Dirac delta. Think about this: Dirac delta doesn't belong to the Hilbert space of complex valued square-integrable functions of 3 real variables since it's not a function at all (well not that kind of function anyways). So it's not a physical state of the system as that is the space of physical states of the system and it's not in there. It's kinda like $\pm\infty$ on the (extended) real number line, these are not real numbers they're more like "limits" of the real numbers. In like wise the Dirac delta is like some kind of "limit" of the wavespace. An idealization but not reality.

A: The particle has a definite position at t=0 means that initially the wavefunction is a position eigenstate. If initial position in an 1-D box is $x_0$, the wavefunction at t=0 is
$$\psi(x,t=0) = \delta(x-x_0)$$
Now, with time the initial wavefunction will evolve according to Schrodinger equation. For a system with Hamiltonian $H$, the state at time $t=t_p$ will be
$$\psi(x,t=t_p) = exp(\frac{-iHt_p}{\hbar})\psi(x,t=0)\\=exp(\frac{-iHt_p}{\hbar})\delta(x-x_0)$$
One way to evaluate this equation is to expand $\delta(x-x_0)$ in terms of the eigenfunctions of the Hamiltonian and evolve each eigenfunction individually. In general, the wavefunction will not remain a position eigenstate at $t>0$. It will spread out instantly.

A: In Quantum Mechanics you cannot specify the position of a particle with infinite accuracy as it violates the position-momentum uncertainty relation.  Here you are specifying that the particle is at a specific location at $t=0$.
Infinite accuracy in position ($ \Delta x = 0 $)  results in infinite uncertainty in momentum ($ \Delta p = \infty $)
You can only say that at $t=0$ the particle has a definite probability to be found at a specific position


text:
Q: Google Sheets - Split Data I have these data in Google Sheets
$71,675_x000d_
$80,356_x000d_
$107,361_x000d_
$123,393_x000d_
$116,878

I want them to be split into different columns.
However, when I do so using Data > Split Data into Different Columns, it separates $71 and 675_x000d_ but I need the $71,275 and remove the xoood
Please note that the last number doesn't have those extra characters.
Please help.

A: Your post says you want to "remove the x000d (that is, extract only the dollar amounts). That said, let's say your raw data starts in A2 (i.e., the data is in A2:A). Place the following formula into the first cell of another otherwise empty column (e.g., B1):
=ArrayFormula({"Extracted";IF(A2:A="",,REGEXEXTRACT(SUBSTITUTE(A2:A&"_",",",""),"\d+"))})
How It Works:
ArrayFormula(...) signifies that we'll be processing an entire range and not just one cell.
The outer curly brackets {...} signify that a virtual array will be formed from non-like or non-contiguous pieces.
The first piece of the virtual array is the header. Here, that is "Extracted"; but you can change it as you like.
The semicolon means "place the next information below the previous part."
IF(A2:A="",, ...) is a standard check that basically says "Don't try to process any blank cells in Column A"; or alternatively worded, "If any cell in A2:A is blank/null, do nothing."
Skipping the REGEXEXTRACT for now, A2:A&"_" appends an underscore to every entry in A2:A. This allows entries in A2:A that are just a dollar amount (e.g., from the post, $116,878) to have a consistent symbol following them if not already there. (And adding the underscore to anything that already has an underscore won't matter, because we won't be extracting that far out.)
Now that we've got the new strings, we SUBSTITUTE every comma for a null (i.e., delete all commas).
Finally, REGEXEXTRACT will take all of the virtually modified strings and extract \d+, which means only digits (\d) in an unbroken sequence of any length greater than 0 (+). Note that REGEXEXTRACT will only return the first such match it encounters as written, so 000 will not be extracted.
An IFERROR wrap is placed around the REGEXEXTRACT, just in case you have any situations in real life that don't have any sequence of numbers at all. In these cases, nothing will be returned (whereas, without the IFERROR, an error would have been returned).
Once the extraction is done, you can apply Format > Number > Currency (rounded) to the entire column.
Addendum:
After an additional comment (below), it appears that the raw data is in Column T, that all five entries are in one cell and that the OP would like all five amounts extracted across each row. That being the case, assuming that Columns U:Y are empty to start, place the following in cell U1 (not U2):
=ArrayFormula({"Va11","Val2","Val3","Val4","Val5";IF(T2:T="",,IFERROR(REGEXEXTRACT(SUBSTITUTE(T2:T&"_",",",""),REPT("\$(\d+)[^\$]*",5))))})
This works much the same way as the previous formula. The differences:
There are five headers now.
You'll see REPT(...,5) here. This is an easy way to repeat the same extraction five times.
That repeated extraction is now the following:
\$(\d+)[^\$]*
The backslash in front of the dollar signs means to treat those symbols as literals instead of as their usual meaning (i.e., end-of-string). So the extraction reads as follows:
\$ anything that starts with a dollar sign
(\d+) extract what is between the ( ), which is any group of digits [^$]*` followed by any number (including 0) characters that are not dollar signs
As I said, the REPT will repeat this five times; so five groups matching this pattern will be extracted.
Understand that if you have any groups that don't follow the pattern exactly, resulting in five matching extractions, nothing will be returned.
Be sure to format U:Y as currency rounded, or you will wind up with some of those numbers translating as raw dates and therefore being completely off.

A: Please use the following formula and format cells to your needs.
=ArrayFormula(IFERROR(SPLIT(REGEXREPLACE(A2:A,"\n|_x000d_","√"),"√")))

The big advantage of the above formula compared to others is that it works for any number of lines included within a single cell (as shown in the image below).

Functions used:

*

*ArrayFormula

*IFERROR

*SPLIT

*REGEXREPLACE

A: You can use SPLIT function:
=ArrayFormula(IF(LEN(A:A),SPLIT(A:A,"_x000d_",FALSE),""))


text:
Q: Error when subtracting columns in SQL I have the following query I'm using to attempt to get a date difference by subtracting values between two columns. Here is part of this query:
SELECT
ISNULL(MIN(c.CreatedOn), 0) AS [StartDate],
ISNULL(MIN(s.CreatedOn), 0) AS [EndDate],
Duration = [EndDate]-[StartDate]
FROM MyTable
INNER JOIN...

The error that I am receiving states that I have Invalid Column Names.
Is it possible to write the query this way?

A: Previously defined column aliases can't be used in the same query. Use the actual calculation instead.
SELECT
ISNULL(MIN(c.CreatedOn), 0) AS [StartDate],
ISNULL(MIN(s.CreatedOn), 0) AS [EndDate],
Duration = ISNULL(MIN(s.CreatedOn), 0)-ISNULL(MIN(c.CreatedOn), 0)
FROM MyTable
INNER JOIN...

A: You cannot use aliases within the same query.  If you must use them, then you can use a nested query, or a WITH statement.
Nested Query
Select StartDate, EndDate,
       Duration = [EndDate]-[StartDate]
From
(
    SELECT
    ISNULL(MIN(c.CreatedOn), 0) AS [StartDate],
    ISNULL(MIN(s.CreatedOn), 0) AS [EndDate]
    FROM MyTable
    INNER JOIN...
) InnerQuery

WITH statement
;With InnerQuery AS
(
    SELECT
    ISNULL(MIN(c.CreatedOn), 0) AS [StartDate],
    ISNULL(MIN(s.CreatedOn), 0) AS [EndDate]
    FROM MyTable
    INNER JOIN...
)
Select StartDate, EndDate,
       Duration = [EndDate]-[StartDate]
From InnerQuery

A: there is a datediff function
select datediff(day, min('12/01/2014'), min(getdate()))

P.S., What are you expecting when you isnull a date data type to an int?
select isnull(cast(null as date), 0)


text:
Q: Error: Cannot find module 'data.json' Require stack: - C: The json file is in the same directory as the index.js. Unfortunately i get an error.
Error: Cannot find module 'data.json'
Require stack: - C:\Users\yoan_\Desktop\train\project\index.js

const {render} = require('ejs');
const express = require('express');
const app = express();
const path = require('path');
const redditdata = require('data.json');

app.set('view enginge', 'ejs');
app.set('views', path.join(__dirname, '/views'));
app.get('/q/:term', (req, res) => {
  const {term} = req.params;
  const data = redditData[term];
  console.log(data);
});

app.listen('3000', () => {
  console.log('listening on port 3000');
});

A: This error:
Error: Cannot find module 'data.json'

is caused by this command:
const redditdata = require('data.json');

The require module loader will consider any path name that doesn't start with a "./" or a "/" to be a core module. It will not look in the local folder, so it will not find the 'data.json' file.
The fix: start the path name with a "./":
const redditdata = require('./data.json');

Better: Use `fs.readFileSync` to load JSON
Using require to read JSON data has a drawback: require caches the data it reads, so the JSON data your program gets may be out of date.
The recommended way to read a JSON file is with fs.readFileSync().
const fs = require('fs');
const redditdata = JSON.parse(fs.readFileSync('./data.json'));


text:
Q: N8000 File System: App I need to have a look at the folder structure created by my Android application I deployed to an N8000 device.
I'm very new to Android developer and there seems to be no easy way to access the file system? I downloaded File Explorer on my device, but under Android/data/ I don't see my application, but it's definitely there if I open up the applications grid on the device.
Where or how would I find my application on the device without rooting it?

A: You can do this over USB using ADB. There are lots of explorer tools and command line options on how to do this. I prefer this one: http://sourceforge.net/projects/adbbrowser/files/ but there are lots of others if that one doesn't work for your needs. Just google ADB File Explorer.
Here's a command line as well for you: adb shell ls -R /


text:
Q: POSTGRESQL: Refresh the materialized view which effect when there are change based on columns I have a database in postgresql. There are several materialized view (matview) in this database. In each table, i have a trigger and have a function for trigger to refresh the matview, and it works fine. Can someone help me to make a function so that the trigger only refresh the affected matview based on changes in the column?
for example table_1 has columns a and b. table 2 has columns c and d.
matview_1 takes columns a and c, matview_2 takes columns a and d, matview_3 takes columns b and c. I need if there is a changes in a row of table 1 column a, only matview_1 and matview_2 is refresh by the store procedure trigger. but if there are changes in row of table_1 column b, only matview_3 is refresh.

table_1
a  |  b
"""""""
   |

table_2
c  |  d
"""""""
   |

matview_1
a  |  c
"""""""
   |

matview_2
a  |  d
"""""""
   |

matview_3
b  |  c
"""""""
   |

Here my function trigger for all table:
CREATE OR REPLACE FUNCTION sp_refresh_matview() RETURNS trigger AS
$$
DECLARE
rec RECORD;
BEGIN
    FOR rec IN
        SELECT *
        FROM pg_matviews WHERE (
            definition LIKE '%'||TG_TABLE_NAME||'%')
    LOOP
        EXECUTE 'REFRESH MATERIALIZED VIEW '|| rec.matviewname;
    END LOOP;
    RETURN NULL;
END;
$$
LANGUAGE plpgsql ;

Here my create trigger:
CREATE TRIGGER trigger_tabel AFTER
INSERT OR UPDATE OR DELETE ON name_table
FOR EACH ROW EXECUTE PROCEDURE sp_refresh_matview();

A: The most efficient solution is to not fire the trigger in that case:
CREATE TRIGGER trigger_tabel
AFTER INSERT
   OR UPDATE OF (column_a) --<< only fire the trigger if column_a is updated
   OR DELETE
ON name_table
FOR EACH ROW EXECUTE PROCEDURE sp_refresh_matview();

If you have multiple columns that should trigger the refresh, you can separate them using commas: OR UPDATE OF (column_a, column_c, column_d)

A less efficient solution is to check if the column changed inside the trigger function:
CREATE OR REPLACE FUNCTION sp_refresh_matview() RETURNS trigger A
$$
DECLARE
rec RECORD;
BEGIN
    IF TG_OP = 'INSERT' OR TG_OP = 'DELETE' OR
       -- add all columns that need to be checked for changes
       (old.column_b IS DISTINCT FROM new.column_b)
    THEN
      FOR rec IN
        SELECT *
        FROM pg_matviews WHERE (
            definition LIKE '%'||TG_TABLE_NAME||'%')
      LOOP
        EXECUTE 'REFRESH MATERIALIZED VIEW '|| rec.matviewname;
      END LOOP;
    END IF;
    RETURN NULL;
END;
$$
LANGUAGE plpgsql ;

If you are using the same trigger function for all tables, then obviously this only works if all tables have the same columns that you want to check. But not firing the trigger to begin with will be much more efficient and should be your preferred solution.


text:
Q: Python, введение числа из заданного диапазона Как сделать так что бы пользователь ввел переменную из заданного диапазона от 1 до 8. А если она не из заданного диапазона ошибка выдавалась и пользователь должен ввести переменную заново, и так, до тех пор пока переменная не будет удовлетворять данному диапазону.

A: В переменной a лежит строка из требуемых символов, проверяем пока не введут правильный
a = "12345678"
n = input("Нужно число от 1 до 8: ")
while n not in a:
    print("Нет, Вы ошиблись")
    n = input("Нужно число от 1 до 8: ")
print("Наконец то: ", n)

A: while True:
    try:
        n = int(input('> '))
        if n >= 1 and n <= 8:
            break
        else:
            print('Please enter n ∈ [1;8]!')
    except ValueError:
        print('Please enter number')
print(n)

A: Просто прикольно:
pip3 install getch

from getch import getch
while True:
    try:
        n = int(getch())
    except:
        pass
    if n >= 1 and n <= 8:
        print(n)
        break

A: как вариант можно приводить все значения меньше диапазона к минимульному допустимому значению, а все значения больше, к максимальному допустимому
a = max(min(int(input("введи число от 1 до 8: ) " )),8),1)
print(a)


text:
Q: How to handle localization/string values in an ASP.NET Web MVC project? I am trying to put all of my strings into the resource file, something I do for all my Windows and Web Forms applications.
Works great when it comes to changes string values for labels and/or localizing the application.
I tried adding the string values to my Web MVC project, but cannot seem to access the Resource file from the inline code in the view.
Is this possible? Is there a better way?

A: Where is your resource file?  There are a couple things you have to do.

*

*You have to set the custom tool on the resource file to be "PublicResXFileCodeGenerator", rather than just "ResXFileCodeGenerator".  This makes the resource class that it generates a public class, rather than an internal class.

*Make sure that you are importing the namespace into your View.  For example, if you're using the Properties folder to store your resx files, do
Even then, you can't reference it by "Properties.Resource1.MyString"... you have to either use just "Resource1.MyString", or "MvcApplication1.Properties.Resource1.MyString".
Hope that helps.


text:
Q: how to check app is installed in my fb page or not using PHP, Graph API? How to check particular app is installed in my fb page or not using PHP, Graph API?

A: Using the graph api, you can't view apps you have installed, only apps you own (either as an administrator,developer,tester, or insight user): https://graph.facebook.com/me/accounts/?access_token=ACCESS_TOKEN


text:
Q: Stylesheet not loaded because of MIME-type Angular application I'm Working on a Angular 6.x application where i'm trying to change theme (dynamically).
The CLI compile everything properly but in developer console  im getting this error message.

Refused to apply style from
  'http://localhost:4200/vendor/theme-light.css' because its MIME type
  ('text/html') is not a supported stylesheet MIME type, and strict MIME
  checking is enabled.

My file structure looks like this, the path is correct
project
    |-src
      |-vendor
         |-theme-light.css
          |theme-dark.css

My theme changing code looks this
import { Component, Inject, PLATFORM_ID } from '@angular/core';
import { DOCUMENT, isPlatformBrowser } from '@angular/common';

 @Component({
     ..
     ..
})

linkRef: HTMLLinkElement;

  themes = [
    { name: 'Light', href: '../vendor/theme-light.css' },
    { name: 'Dark', href: '../vendor/theme-dark.css' }
  ];

  constructor(@Inject(DOCUMENT) private document: Document, @Inject(PLATFORM_ID) private platformId: Object) {
    if (isPlatformBrowser(this.platformId)) {
      let theme = this.themes[0];
      try {
        const stored = localStorage.getItem('theme');
        if (stored) {
          theme = JSON.parse(stored);
        }
      } catch (e) {
      }
      this.linkRef = this.document.createElement('link');
      this.linkRef.rel = 'stylesheet';
      this.linkRef.href = theme.href;
      this.document.querySelector('head').appendChild(this.linkRef);
    }
  }

  setTheme(theme) {
    localStorage.setItem('theme', JSON.stringify(theme));
    this.linkRef.href = theme.href;
  }

Now, I don't really understand why this happens. Is am i missing something ? Feel free to ask for more details if needed.
Any help will be really appreciated.
Thanks

A: Looks like the href is wrong.
There is a good answer to a different question exactly like yours:
The usual reason for this error message is that when the browser tries to load that resource, the server returns an HTML page instead, for example if your router catches unknown paths and displays a default page without a 404 error. Of course that means the path does not return the expected CSS file / image / icon / whatever...
The solution is to find the correct path and router configuration so that you get your plain CSS file / image / etc. when accessing that path.
In your case it's the css href.

A: Finally figured out Im giving the wrong path on my path configuration href: '../vendor/theme-light.css'  thats returns http://localhost:4200/vendor/theme-light.css on the browser which is not the correct path.
Solution
themes = [
    //added the missing src ( source root)
    { name: 'Light', href: '../src/vendor/theme-light.css' },
    { name: 'Dark', href: '../src/vendor/theme-dark.css' }
  ];

Thank You for your answers

A: when you're using a static folder , please make sure to use "/" . Let's say for example assets is our static folder , we want the image folder which is under the assets , so you type this src="image/img1.png" , that's wrong you have to add "/" ,,, so it will be like this  src="/image/img1.png"

A: Found this answer here Proper solution
The issue could be with a CSS library starting with comments. While on dev, We do not minify files and We don't remove comments, this meant that the stylesheet started with some comments, causing it to be seen as something different from css.
Removing the library and putting it into vendor file (which is ALWAYS minified without comments) solved the issue.

A: you have to change the place of your file css into the directory assets assets/style.css
and then put these path in your file index.html src/index.html
<link rel="stylesheet" type="text/css" href="assets/style.css" />

in addition you have to modify to file angular.json in styles
"styles": [
          "src/assets/style.css",
          "./node_modules/materialize-css/dist/css/materialize.min.css",
        ],


text:
Q: Xcode sqlite3,use "insert" but fail and defined 1 I wanted to add a line to my table 'Cloth',but failed.I then set breakpoint and found the defined is 1.
Here's the code.
char *addCloth = "INSERT INTO 'Cloth'(Ckind,Ccolor,Cseason,Ctexture,Cstyly) VALUES(?,?,?,?,?);";
sqlite3_stmt *stmt;
int success = sqlite3_prepare_v2(db, addCloth, -1, &stmt, nil);
if(success!= SQLITE_OK){
    NSLog(@"Error: failed to insert:testTable");
    sqlite3_close(db);
}
sqlite3_bind_text(stmt, 1, [strkind UTF8String], -1, NULL);
sqlite3_bind_text(stmt, 2, [strcolor UTF8String], -1, NULL);
sqlite3_bind_text(stmt, 3, [seas UTF8String], -1, NULL);
sqlite3_bind_text(stmt, 4, [texture UTF8String], -1, NULL);
sqlite3_bind_text(stmt, 5, [style UTF8String], -1, NULL);
success = sqlite3_step(stmt);
if(success != SQLITE_DONE)
{sqlite3_close(db);
    NSLog(@"单品新增失败");
}
sqlite3_finalize(stmt);

}
and the run image:enter image description here
it seems my 'stmt' is nil,so I doubt whether if my 'strkind' and 'strcolor'is Chinese character caused it.
Or something else where made this error?
Thanks


text:
Q: Listening on multiple TCP ports I am trying to do the following:
// Create IPv4 TCP/IP sockets.
TcpListener listener = new TcpListener(IPAddress.Any, 11000);
TcpListener listener2 = new TcpListener(IPAddress.Any, 12000);

// Listen for incoming connections.
listener.Start();
listener2.Start();

The second call to TCPListener.Start() throws a socketexception saying that "Only one usage of each socket address (protocol/network address/port) is normally permitted".
Since I am using a different port, I thought a server app can listen on multiple ports?
Is there another way to do this?

A: Your code is ok and works on my box. The firewall pop up appeared only after both listeners started succesfully.
As everybody is pointing out, you have an application open at port 12000.
Execute netstat -a -b and look up which application is using it.
Example:
  TCP    [::]:12000             [::]:0                 LISTENING
 [services.exe]

A: An app can set up a tcp listener on any number of ports.
As the error indicates, there is something else listening on that particular port.
My guess is that your app is running twice OR you haven't properly cleaned up after it.  Note that you have to explicitly close each accepted connection individually.  Stop doesn't do this for you.
Reference on MSDN.


text:
Q: Awaiting a single .NET event with a ValueTask I have a simple ITimer interface that has just a classic Elapsed .NET event that is raised after the a certain timespan.
interface ITimer
{
    void Start(TimeSpan interval);
    void Stop();
    public event EventHandler Elapsed;

}

Now I would like to create a functionality that is similar to Task.Delay(TimeSpan) but it should use that ITimer abstraction instead of the "real" time. Also different form Task.Delay(TimeSpan) I though it might be a good idea to return a ValueTask instead of a Task because it could be implemented allocation-free and might generally be more performant. Also the completion of the delay only needs to be awaited once anyway.
Now a somewhat naive implementation could probably look like this. There problem here is, that there is no benefit of using a ValueTask at all. How could an implementation look like that takes full benefit of what a ValueTask promises (cheap and allocation-free).
ValueTask Delay(TimeSpan duration, CancellationToken cancellationToken)
{
    // We get the ITimer instance from somwhere, doesn't matter for this question.
    ITimer timer = timerFactory.Create();
    var tcs = new TaskCompletionSource<bool>();
    timer.Elapsed += (_, __) => { tcs.SetResult(true); };
    cancellationToken.Register(() =>
    {
        timer.Stop();
        throw new OperationCanceledException();
    });
    timer.Start(duration);
    return new ValueTask(tcs.Task);
}

A: Not much has been written on ManualResetValueTaskSourceCore<TResult>. It's essentially a TaskCompletionSource<T> but for ValueTask<T>.
It's really intended to be used inside a type like your timer, but you can create a wrapper for it if you want to use it as an external method:
public sealed class ManualResetValueTaskSource<T> : IValueTaskSource<T>, IValueTaskSource
{
  private ManualResetValueTaskSourceCore<T> _logic; // mutable struct; do not make this readonly

  public bool RunContinuationsAsynchronously
  {
    get => _logic.RunContinuationsAsynchronously;
    set => _logic.RunContinuationsAsynchronously = value;
  }
  public void Reset() => _logic.Reset();
  public void SetResult(T result) => _logic.SetResult(result);
  public void SetException(Exception error) => _logic.SetException(error);

  short IValueTaskSource.Version => _logic.Version;
  short IValueTaskSource<T>.Version => _logic.Version;
  void IValueTaskSource.GetResult(short token) => _logic.GetResult(token);
  T IValueTaskSource<T>.GetResult(short token) => _logic.GetResult(token);
  ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) => _logic.GetStatus(token);
  ValueTaskSourceStatus IValueTaskSource<T>.GetStatus(short token) => _logic.GetStatus(token);

  void IValueTaskSource.OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => _logic.OnCompleted(continuation, state, token, flags);
  void IValueTaskSource<T>.OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => _logic.OnCompleted(continuation, state, token, flags);
}

You can then use it as such (cancellation removed for simplicity):
ValueTask Delay(TimeSpan duration)
{
  ITimer timer = timerFactory.Create();
  var vts = new ManualResetValueTaskSource<object>();
  TimerElapsed eventHandler = null;
  eventHandler = (_, __) =>
  {
    timer.Elapsed -= eventHandler;
    vts.SetResult(null);
  };
  timer.Elapsed += eventHandler;
  timer.Start(duration);
  return new ValueTask(vts);
}

Note that, since this is an external method, you'd still be allocating the ManualResetValueTaskSource<T> (as well as the delegate). So this doesn't really buy you anything, and I would choose to use TaskCompletionSource<T> here. This is especially true when you add CancellationToken support and have to handle the race condition between the timer firing (vts.SetResult) and the cancellation (vts.SetException), since I'm pretty sure only one of those is supposed to happen per ValueTask operation, and there's no Try* variants in our ManualResetValueTaskSource<T> like TaskCompletionSource<T> has.
ValueTask is really intended to be more of a first-class citizen; i.e., ideally you would update the actual timer implementation (and interface) to support ValueTask Delay(TimeSpan) in its own class instead of an external method. Inside the timer instance, it can reuse the ValueTask backing type (ManualResetValueTaskSource<T>), it can know when to call Reset, and it can avoid the delegate/event completely.


text:
Q: How to change text direction in excel cell using java poi? I want to change Text_Direction (not Alignment) of a single cell (not worksheet) on an excel file using java Apache_poi library.
how can I do it? thanks.

A: after looking a lot I found another way that will fix the problem.
As explained here , it's just needed to change the direction of the text that will be placed in the cell.
the solution will be like below for right to left:
String rtl = "\u200F" + otherTexts;

and like this for LTR:
String left2right_text = "\u200E" + otherTexts;


text:
Q: TypeOrm create OneToOne row Basic postgres+typeorm+nestjs question (that I somehow can´t find a solid answer to):
I have three example tables: customers, products, and orders. For this example orders only has two columns of product and column as oneToOne relations.
Now I want to do the basic step of creating an order. I have the customer id and the product id. Can`t I just put them in the corresponding columns? Do I really have to fetch the customer and product first?
@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
    @InjectRepository(Customer)
    private readonly customerRepository: Repository<Customer>,
    @InjectRepository(Product)
    private readonly productRepository: Repository<Product>,
  ) {}

  async newOrder(order: OrderDto) {
    const [customer, product] = await Promise.all([
      this.customerRepository.findOneBy({
        id: order.customer,
      }),
      this.productRepository.findOneBy({
        id: order.product,
      }),
    ]);

    const newOrder = this.orderRepository.create({
      customer,
      product,
    });
    return this.orderRepository.save(newOrder);
  }
}

A:
For this example orders only has two columns of product and column as oneToOne relations

I believe what you're trying to say is that each record in the orders has one linked record in customers and one linked record in products.
TLDR: You don't need to query either the customers or the products tables.

Make your Order entity class like the below and manually provide the foreign key columns. If you don't, TypeOrm will do this for you but the column names might be customer_id, and product_id.
@Entity('orders')
class Order {
  // Here provide the type based on `id` column in `Customer` entity.
  @Column({ type: 'varchar'})
  customerId: string;

  @ManyToOne(() => Customer)
  @JoinColumn({ name: 'customerId' })
  customer: Customer;

  // Here provide the type based on `id` column in `Product` entity.
  @Column({ type: 'varchar'})
  productId: string;

  @ManyToOne(() => Product)
  @JoinColumn({ name: 'productId' })
  product: Product;
}

Then in your service class, you can do this:
@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
  ) {}

  async newOrder(order: OrderDto) {
    const newOrder = this.orderRepository.create({
      customerId: order.customer,
      productId: order.product,
    });
    return this.orderRepository.save(newOrder);
  }
}


text:
Q: Find the image through $T$ of the square with vertices $1,-1,i,-i$ $T:\mathbb{C}\rightarrow\mathbb{C} $ given by $ T(z)=(1+i)z$.

$ T(1)=1+i $
$T(-1)=-1-i$
$T(i)=-1+i$
$T(-i)=1-i$
So the image is the square with vertices$ T(1),T(-1),T(i)$ and $(T-i)$ ?

A: Yes. Since $T$ is linear it is similarity transformation (preserves the angles and ratio of distances) with factor of similarity $\sqrt{2}$:
$$|T(z)-T(w)| = |(1+i)(z-w)|= |1+i||z-w| = \sqrt{2}|z-w|$$
so it takes square to square which is bigger than first one with factor $\sqrt{2}$.


text: Q: Is there any way how to create an IQueryable from HQL? We want to employ HQL(IQueryOver/ICriteria) in our data layer of application but we want to publish IQueryable for layers above the data layer based on our query in HQL. The reason is simple. It seems that HQL is a better way how to specify more complex queries (please feel free to be opposed to the opinion). There was a way how to achieve that in a previous version of NHibernate (we currently have 3.3.1.4000) using ICriteria. You can find here how to achieve that. Does anybody know how to do that with HQL in the new version?


text:
Q: sql-запрос агрегированных данных таблицы по месяцам Здравствуйте. Объясню, что мне нужно, на примере. Дана таблица:

Мне нужен такой запрос, чтобы получилось следующее:

То есть мне нужен столбец количества пользователей, у которых совпадает сайт магазина, продукт и месяц покупки. Если я правильно понимаю, GROUP BY выводит совпадение по дням, а мне надо по месяцам. Чувствую, что ответ на поверхности, нуждаюсь в вашей помощи.

A: Если вы не справляетесь сразу со сложным запросом - попробуйте разбить проблему на несколько частей и решать их по очереди. Для начала, определить, как именно получить месяц из даты.
Понятно, что просто извлечь месяц недостаточно, т.к. месяц этого года будет равен месяцу прошлого, а это, по всей видимости, не то, чего вы хотите. Как добавить год, вам подсказали в комментариях.
После того, как получили правильный месяц, делайте группировку.
Если я правильно понял, какого результата вы пытаетесь добиться, предполагаю, что ваш итоговый запрос будет выглядеть так:
select [Сайт магазина]
     , [Продукт]
     , cast(year([День покупки]) as varchar(10)) +
       '-' +
       cast(month([День покупки]) as varchar(10)) as [Месяц покупки]
     , count(distinct [Имя пользователя]) as [Количество аккаунтов]
from [Таблица]
group by [Сайт магазина]
       , [Продукт]
       , cast(year([День покупки]) as varchar(10)) +
         '-' +
         cast(month([День покупки]) as varchar(10))


text:
Q: If $z^2 = z_1^2+z_2^2+z_3^2$ then $|\Re(z)| \le|\Re(z_1)|+|\Re(z_2)|+|\Re(z_3)|$ Suppose $z,z_1,z_2,z_3 \in \mathbb{C}$ such that $z^2 = z_1^2+z_2^2+z_3^2$.
Prove that $$|\Re(z)| \le|\Re(z_1)|+|\Re(z_2)|+|\Re(z_3)|$$
where $\Re(z)$ is the real part of $z$.
I think we can use the triangle inequality but I can't complete it.

A: First note that for all complex numbers $z$
$$ \tag{*}
\lvert\operatorname{Re}(z)\rvert^2 = \frac 14 (z + \overline z)^2 =
 \frac 14 (z^2 + \overline z^2 + 2\lvert z\rvert^2) =
\frac 12 \bigl(\operatorname{Re}(z^2)  + \lvert z^2 \rvert\bigr) \quad .
$$
Now we can prove the inequality for an arbitrary number of
complex numbers. If
$$
 z^2 = z_1^2 + z_2^2 + \ldots + z_n^2
$$
then
$$
\begin{aligned}
 \lvert\operatorname{Re}(z)\rvert^2 &= \frac 12 \bigl(
  \sum_{k=1}^n \operatorname{Re}(z_k^2) +  \bigl\lvert \sum_{k=1}^n z_k^2  \bigr\rvert
 \bigr) \\
&\le \frac 12 \bigl(
  \sum_{k=1}^n \operatorname{Re}(z_k^2) +  \sum_{k=1}^n \lvert z_k^2 \rvert
 \bigr) \quad &\text{(triangle inequality)} \\
 &= \sum_{k=1}^n \lvert\operatorname{Re}(z_k)\rvert^2
\quad &\text{(using $(*)$ for all $z_k$)}
 \\
 &\le \bigl(
\sum_{k=1}^n \lvert\operatorname{Re}(z_k) \rvert
 \bigr)^2
\end{aligned}
$$
and therefore
$$ \tag{**}
\lvert\operatorname{Re}(z)\rvert
\le \sum_{k=1}^n  \lvert \operatorname{Re}(z_k) \rvert \, .
$$
When does equality hold?

*

*Equality in the first inequality (triangle inequality)
holds if and only if all $z_k^2$ are real, non-negative multiples of some $z_j^2$,
which means that all $z_k$ are real multiples of $z_j$.

*Equality in the second inequality holds if and only if
$\operatorname{Re}(z_k) \ne 0$ for at most one $k$.

Together it follows that equality holds in $(**)$ if and only if

*

*all $z_k$ are purely imaginary, or

*$z_k \ne 0$ for at most one $k$.

In the first case, $z$ is purely imaginary as well.
In the second case, $z = \pm z_k$.


text:
Q: Passing different type of argument to ApiController in mvc The below link shows how to creat ApiController.
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
So how we can create a new method in controller with different paramaeter.
Something like this.
public bool SaveIttoDB(string name, string email, DateTime dob, int id)
{
    // code here
}

How we can access this method using URL?
Can anubody help me on this.

A: The URL for that type of action (assuming it's a HttpGet) would look like
http://domain/controller/SaveItToDb/name?email=value&dob=value&id=value

Or
http://domain/controller/SaveItToDb?name=value&email=value&dob=value&id=value

A: This would work:
Note, I'm converting a POST action to a GET action for demonstration purposes.
public bool GetSaveItToDB(string name, string email, DateTime dob, int id)
{
    // code here
}

You would call it using this url:
http://localhost/api/MyWebApiControllerName?name=John&email=john@doe.com&dpob=2012-13-05&id=1

It would normally be a POST:
public bool PostItToDB(string name, string email, DateTime dob, int id)
{
    // code here
}

You would then provide the parameters as POST parameters.


text:
Q: how to add html tag in javascript I want to add following html tag in javascript

In javascript file
title: {
            text: 'Properties'
        };

I have done following
title: {
            text: 'Properties'
        };

A: Use querySelector like so:

var myObject = {
  title: {
    text: "Properties"
  }
};

var elem = document.querySelector("i");

myObject.title.text = elem.outerHTML + myObject.title.text;

console.log(myObject);

The \" are just escaped quotes.

A: Get i tag by document.getElementsByTagName('i') and save it into object

var html = document.getElementsByTagName('i');
let obj = {};
obj.text =html[0];

console.log(obj);


text:
Q: import component next js server side to another component (Cannot read property 'map' of undefined) I am testing out a simple next.js react app

Error is as follows; TypeError: Cannot read property 'map' of undefined

server-side.js:
...

export default function Home({books}) {

    return (

        <Grid container spacing={2}>
            {
                books && books.map(row => (
                    <Grid key={row.id} item xs={12} sm={4}>

{row.subject}

                    </Grid>
                ))
            }
        </Grid>

    );
}

export async function getServerSideProps() {

    const { data } = await client.query({
        query: gql`
            query books{
                books{
                    id
                    subject

                }
            }
        `,
    });

    return {
        props: {
            books: data.books,
        },
    };
}

index.js:
...
const books= dynamic(
    () => import('./server-side'),
    { loading: () =>
<LinearProgress />
 }
)

export default function Index() {

    return (
<React.Fragment>
            <books/>
</React.Fragment>
  );
}

TypeError: Cannot read property 'map' of undefined
I'm using Next.js. Please see my code below


text:
Q: Overlaying Text with transparent background on a 24bit webcam feed I'm using the DirectShow.Net library to display a feed from a web cam. I've created the capture graph with an ISampleGrabber interface which uses a callback containing a pointer to the video frame buffer. I use this pointer to create a .net bitmap, and Graphics object which I use to overlay some red text with the method Graphics.DrawString. This takes a Brush object parameter. When I draw the text, it gets displayed in multicolors instead of red. The Brush is correct because I'm using the preset Brushes.Red. At the moment I reckon this is caused by the fact that the Brush is painting in 32bpp but the web cam image is 24bpp. I could create a temporary 24bpp bitmap, draw the text onto that, then overlay it on the video frame, but this wont give me text with a transparent background.
Any ideas? (easy ones are more preferable)
Thanks

A: I think there is a solution: Create a new Bitmap with 32bpp, use this bitmap graphics to draw the webcam image on it "Graphics.FromImage(ourNewBitmap).Draw(theWebcam24Image)", and use the same graphics to draw the string, after that create a new 24 bitmap and draw our generated bitmap to it then append the last generated image to the webcam.


text:
Q: ment.io: how to add menu for a specific type of items I'm using mentio directives for mentioning purpose, there is an ng-model attribute to determine how many menus and for which elements should append to the page, how to define ng-model to make menus only for item of type 'text'?
the structure of items in scope:
[
 {
   type: 'text',
   data: {}
 },
 {
   type: 'image',
   data: {}
 },
 .
 .
 .
]


text:
Q: (STUPIDITY WARNING) Python - nested dictionary creation (and code cleanup?) Python version: 3.9.6
problematic code:
import json

nodelist = { }
appendednodenumbers=0
apidata = input("enter api response:")
data = json.loads(apidata)
nodeinfo = data['nodeinfo']['nodes']
nodenumbers = len(nodeinfo)
for x in nodeinfo:
    nodeserver = x["raw_node"]["server"]
    nodemethod = x["raw_node"]["method"]
    nodelist[appendednodenumbers]["servers"]=nodeserver
    appendednodenumbers+=1

print(nodelist)

errors printed in the terminal is as follows:
Traceback (most recent call last):
  File "/Users/username/PycharmProjects/project/main.py", line 12, in <module>
    nodelist[appendednodenumbers]["servers"]=nodeserver
KeyError: 0

Process finished with exit code 1

However, after changing lines 12&13, it works. This is the change:
    nodelist[appendednodenumbers]={}
    nodelist[appendednodenumbers]["servers"]=nodeserver

does this mean that python3 does not support creating a nested dictionary with a single command? Or is there anything else that I am missing?
Thanks, and I truly apologize if I have wasted your time :(


text:
Q: how to resolve connection not open to send() error when subscribe event from smart contract I am going to subscribe event from polygon mainnet token contract, but connection not open to send() error comes out
const { contractAddress } = process.env;

const Web3 = require('web3');

const url = 'wss://ws-mumbai.matic.today/';
const web3 = new Web3(url);

const options = {
reconnect: {
auto: true,
delay: 1000, // ms
maxAttempts: 1,
onTimeout: false,
},
address: contractAddress,
topics: [
'0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',
],

function initSubscription() {
web3.eth
.subscribe('logs', options, (error, result) => {
if (!error) console.log('got result');
else console.log('error - ', error);
})
.on('data', (log) => {
console.log('got data', log);
})
.on('changed', (log) => {
console.log('changed');
});
}
};

wss url is not right? if so, what is the matter with this issue?


text:
Q: ¿Cómo introducir las 10 primeras filas de una tabla en un array multidireccional de con método procedimental? ¿Cómo podríamos introducir las 10 primeras filas (las marcadas con fondo azul), en un array multidireccional?
1)CONSULTA SQL
$consutla="SELECT * FROM preguntasDeAnimales ORDER BY numeroPregunta ASC LIMIT 10";

2)FUNCIÓN MYSQLI_FETCH_ROW Y ASIGNACIÓN MEDIANTE FOR (NO LO CONSIGO):
$result = mysqli_query($con,$consulta);
$numeros_filas = mysqli_num_rows($result);
    if($numeros_filas>0){
        //METEMOS LOS 10 RESULTADOS EN UN ARRAY MULTIDIMENSIONAL
        if($filas = mysqli_fetch_array($resultadoSi)){
//AQUÍ IRÍA LA ASIGNACIÓN AL ARRAY MULTIDIMENSIONAL... ¿SUPONGO QUE CON DOS FOR?
}

(Decir que el contenido de la tabla son simplemente ejemplos)

A: El problema de tu código está sobre todo aquí:
       //METEMOS LOS 10 RESULTADOS EN UN ARRAY MULTIDIMENSIONAL
        if($filas = mysqli_fetch_array($resultadoSi)){
//AQUÍ IRÍA LA ASIGNACIÓN AL ARRAY MULTIDIMENSIONAL... ¿SUPONGO QUE CON DOS FOR?

Porque $resultadoSi no representa a tu conjunto de resultados, porque no necesitas evaluar nada con if (ya verificaste antes si hay más de 0 filas) y porque no necesitas dos for como hace pensar el comentario de tu código.
También hay un error de sintaxis, tu variable la has llamado $consutla.
Visto esto, paso a explicar algo:
Al ejecutar mysqli_query, si todo va bien, vas a tener en $result algo así como un puntero con los resultados. Entonces, si quieres guardar esos resultados en un array tendrías que usar algunos de los métodos fetch con que cuenta mysqli para leer datos recorriendo el puntero fila por fila (esto se hace así para evitar problemas de memoria, sobre todo en eventuales resultados con miles o millones de filas).
El que los datos están en un puntero significa que los puedes recorrer dentro de un bucle, fila por fila. Generalmente esto se hace con un while como se mostrará en la respuesta. Al hacer por ejemplo: while ( $row = mysqli_fetch_assoc($result) ) { empezamos a recorrer los resultados fila por fila. O sea el puntero se va moviendo fila por fila en los resultados y cada vez $row representará la fila actual. Entonces podemos tener una array previamente declarado al que iremos asignando el valor de $row (la fila con cada columna y su valor).
Veamos todo esto aplicado en código concreto. Nótese que he corregido el nombre de tu variable que tiene el SELECT:
$consulta="SELECT * FROM preguntasDeAnimales ORDER BY numeroPregunta ASC LIMIT 10";

$result = mysqli_query($con,$consulta);
$numeros_filas = mysqli_num_rows($result);
$arrData=array();

if($numeros_filas>0){
    while ( $row = mysqli_fetch_assoc($result) ) {
        $arrData[]=$row;
    }
}

Te recomiendo que evites el uso de mysqli_fetch_array, dando preferencia a una función de guardado más específica. El problema es que mysqli_fetch_array te crea un array numérico y otro asociativo. O sea, que te trae los datos dos veces, recargando la memoria1.
Aquí he usado mysqli_fetch_assoc que crear un array asociativo donde la clave es el nombre de la columna y el valor es el dato que hay en esa columna. En esa caso, para mostrar un dato sería algo así: $row["Pregunta"]  o bien así, dando por hecho que los datos se guardarán en el array resultante: $arrData["Pregunta"].
Si por el contrario te interesa un array numérico (que asocie los valores no por nombre de columnas, sino por números), sólo cambias la línea del while por esto:
    while ( $row = mysqli_fetch_row($result) ) {

y para recuperar cada dato, usarías los índices numéricos: $row[0] por ejemplo o $arrData[0] ... ten en cuenta que siempre puedes usar var_dump o print_r para ver cómo está constituido tu array resultante.
Espero te sea de utilidad.

Notas:

*

*Es el problema que ocurre en esta pregunta: consulta json php con resultados duplicados . El OP estaba obteniendo datos duplicados y no entendía por qué. El motivo era que estaba usando mysqli_fetch_array para obtener el resultado de la consulta.

A: no soy muy experto con PHP, pero creo que esto te podría ayudar:

//nuestro array
$array = array();

//nuestra consulta
$consulta="SELECT * FROM preguntasDeAnimales ORDER BY numeroPregunta ASC LIMIT 10";

// intentamos el query
if($result = mysqli_query($con,$consulta)) {
  // si el query devuelve 'true' obtenemos las filas
  while($fila = mysqli_fetch_assoc($result)) {
    //aqui guardamos el array de fila en nuestro array
    array_push($array,$fila);
  }
  // buena práctica esto de cerrar 'result'
  mysqli_free_result($result);
}

// hemos terminado
// ahora 'array' tiene la información que necesitas.

Espero que te sirva, como dije antes, no soy muy experto en PHP, si hay un error me corriges.
Saludos.


text:
Q: terraform how to describe variable type with changing keys in object I've got an ever changing list of objects as variable and wanted to know how to properly describe its type
variable "lifecycle_rules" {
  type = set(object({
#    set(object({
#      action = map(string)
#      condition = map(string)
#    }))
  }))
  default = [
    {
    first = [
      {
        condition = {
          age = "1"
        }
        action = {
          type = "Delete"
        }
      },
      {
        condition = {
          age = "2"
        }
        action = {
          type = "Delete"
        }
      }
    ]},
    {
     second = [
      {
        condition = {
          age = "3"
        }
        action = {
          type = "Delete"
        }
      },
      {
        condition = {
          age = "4"
        }
        action = {
          type = "Delete"
        }
      }
    ]
  }
  ]
}

Here should be line with smth like this string = set(object({...
the first and second are always changing, so key value should be
string but can't really set it - any other thoguhts, how to write
type for the default below ?

A: You are almost there. I think the correct one is:
  type = set(
      map(
        set(
          object({condition = map(string),
                  action    = map(string)})
           )
       )
     )

In the map you don't specify attributes, as they can be different. In the most inner one you have object as condition and action are constant.


text:
Q: JS - Async Await - second function doesn't wait for first function to complete, then first function executes again I'm trying to use async await in Angular 10to first load a list of users from my backend database (Spring Boot with MariaDB) with an http request and then, after the list is loaded, to filter that list for one specific user.
But somehow the loadUsers() keeps getting executed twice, as you can see in the resulting log at the end of my post.
Here's how I'd expect my code to work:

*

*load all users -> console.log the list of all my users (a)

*filter the users list and then console.log this one filtered user -> (b)
But instead of a) -> b), I get a) -> b) -> a). Where first a) is empty, because the http request wasn't finished yet, then b) which is therefore also empty, since the users are not loaded yet, and then again a), after the users were loaded?
ngOnInit() {
  this.loadOwner();
}

loadOwner = async () => {
  const result = await this.loadUsers()  // I'm not doing anything with the result, maybe that's the reason?
  // do something else here after users loading completes
  this.user= this.users.filter(user => user.id === this.product.userId)[0]
  console.log("The user: " + this.user)  // b) (should get logged as last)
}

loadUsers() {
this._update.currentUsers$.subscribe(users => {
    this.users = users;
    console.log("my users: " + this.users)  // a) (should get logged first)
})
}

This is the final log that I'm getting with a) -> b) -> a) structure:

The filtering and the http request are working, I had the expected end result already but wanted to have cleaner code with async await, instead of nesting the loadUser function into the subscribe scope of the loadUsers. There are other things that I have to do after this and it gets more and more nested.

A: You need to make your loadUsers() a Promise.
In Typescript:
loadUsers(): Promise<any> {
  // some code
  return Promise.resolve(true);
}

Actually, in your case you will have another problem since you should actually await on the subscribe in your loadUsers(). You can therefore do it like so:
async loadUsers(): Promise<any> {
  return this._update.currentUsers$.toPromise();
}

And await the loadUsers() when calling it.


text:
Q: gradient descent using numpy I have a gradientDescent function that takes ini train_X, train_y, test_X, test_y, L, num_iter as its inputs and returns the optimal value of parameters and history of loss (which is just the RSME between predicted and actual y)on training data and testing data respectively.
I have previously wrote a function to calculate the loss:
def RMSEFunction(X, theta, y):

  loss = None
  predicted_y = np.dot(X, theta)
  diff = np.subtract(predicted_y,y)
  diff_sq = np.square(diff)
  MSE = np.mean(diff_sq)
  loss = math.sqrt(MSE)

  return loss

However, I am stuck at trying to write the algorithm for gradient descent. For now, I have:
def gradientDescent(train_X, train_y, test_X, test_y, L, num_iter):

  N_train, D = train_X.shape # number of training samples, number of features
  theta = np.zeros((D,1)) # the parameters of the linear regression model
  opt_theta = None # the optimized parameters on the training data

  # record loss of each iteration - both rmse between training data and target
  # data as well as between testing data and target data.
  loss_history = np.zeros((2,num_iter))
  test_loss = RMSEFunction(test_X, theta, test_y)

  # Gradient descent steps
  for i in range(num_iter):
    predicted_y = np.dot(train_X, theta)
    loss = np.subtract(predicted_y,train_y)
    gradient = np.dot(train_X.T, loss)
    opt_theta -= (1/N_train) * L * gradient

    loss_history[0,i] = RMSEFunction(train_X, theta, train_y)
    loss_history[1,i] = RMSEFunction(test_X, theta, test_y)

    if loss_history[1,i] < test_loss: # store the optimal parameter
        test_loss = loss_history[1,i]
        opt_theta = np.copy(theta)

  return [opt_theta, loss_history]

The problem lies for when I start the gradient descent steps till opt_theta. When I run the code, I get:
TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'
I would like to deal with my flawed logic and the errors in my code if possible. Could someone please provide some guidance?
Thank you.


text:
Q: How to restrict ItemtouchHelper to swipe only left to right Hi I am using recycler view and apply ITEMTOUCHHELPER its working.
I apply Logic (direction == ItemTouchHelper.LEFT) then delete item.
All of these things work correctly.
But when I swipe right side and then swipe left side. It give dX value >0.which means swiping done on right side.
If I delete an item no issue If I leave it as it is and swipe again then this strange behavior start.
When I swipe multiple times from left side then it gives dX<0 means then it starts again working.
Here is my Implementation
  private void initSwipe(){
        ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();

                if (direction == ItemTouchHelper.LEFT){
                    Cursor cursor = ((BookRecyclerAdapter)recyclerView.getAdapter()).getCursor();
                    cursor.moveToPosition(position);
                    int  pageNo = cursor.getInt(cursor.getColumnIndex(BookMarkContract.AddsEntry.COLUMN_NAME_PAGE_NO));
                    dbHelper.deletePageNo(pageNo);
                    bookRecyclerAdapter.swapCursor(dbHelper.getAllBookMarks());
                    bookRecyclerAdapter.notifyItemRemoved(position);
                    bookRecyclerAdapter.notifyDataSetChanged();

                }
                else
                return;

            }

            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {

                Bitmap icon;

                Log.d("dX",""+dX);
                if(actionState == ItemTouchHelper.ACTION_STATE_SWIPE){
                    if(dX>0)
                    {
                        dX=0;
                    }
                    View itemView = viewHolder.itemView;
                    float height = (float) itemView.getBottom() - (float) itemView.getTop();
                    float width = height / 3;
                    if(dX>0)
                        return;
else {

                        p.setColor(Color.parseColor("#D32F2F"));
                        RectF background = new RectF((float) itemView.getRight() + dX, (float) itemView.getTop(), (float) itemView.getRight(), (float) itemView.getBottom());
                        c.drawRect(background, p);
                        icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_rub);
                        RectF icon_dest = new RectF((float) itemView.getRight() - 2 * width, (float) itemView.getTop() + width, (float) itemView.getRight() - width, (float) itemView.getBottom() - width);
                        c.drawBitmap(icon, null, icon_dest, p);
                    }

                }
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }
        };
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
        itemTouchHelper.attachToRecyclerView(recyclerView);
    }

Here is my log cat Snippet of when i Swipping left but it gives me dX >0

PROBLEM IN ONE LINE
SWIPPING LEFT SIDE GIVES dX >0
QUESTION
Why I am getting this strange behavior ? it feels like an app is hanging
But it is not hanging it is swiping right side even When I swipe LEFT.

A: If you only want to allow leftswipe, this is your solution:
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
     //int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
       int swipeFlags = ItemTouchHelper.START;
       return makeMovementFlags(dragFlags, swipeFlags);
}

A: Here is what I think it is a more cleaner and simpler solution.
When you extend ItemTouchHelper.SimpleCallback in order to get the custom behavior, you should pass the directions for your items to be swiped or dragged, you don't need to override getMovementFlags since this method uses the drag and swipe directions we are about to pass. For example:
public class RecyclerItemTouchHelper extends ItemTouchHelper.SimpleCallback {

    public RecyclerItemTouchHelper(int dragDirs, int swipeDirs) {
        super(dragDirs, swipeDirs);
    }

    // ...
}

Now, in your activity or fragment, when you setup your recycler view you can specify the swiping and dragging behavior like this:
// 0 means no dragging at all and the 2nd parameters means only swipe left is allowed
RecyclerItemTouchHelper helper = new RecyclerItemTouchHelper(0, ItemTouchHelper.LEFT);
new ItemTouchHelper(helper).attachToRecyclerView(yourRecyclerView);

Now you can configure your dragging and swiping however you want. I hope it helps!
For more information you can take a look at the official documentation, there's pretty much the exact example you need:
https://developer.android.com/reference/android/support/v7/widget/helper/ItemTouchHelper.SimpleCallback


text:
Q: Error in unziping on EC2 edit: When trying to download files from this address https://www.kaggle.com/c/talkingdata-mobile-user-demographics/data, using
wget https://www.kaggle.com/c/talkingdata-mobile-user-
demographics/download/gender_age_test.csv.zip
the file is not dowloaded correctly - instead of zip format
file gender_age_test.csv.zip
gives
gender_age_test.csv.zip.3: HTML document, ASCII text, with very long lines, with CRLF line terminators
what can i do to downlad it correcly from command line (i'm using EC2 ubuntu)

A: I've eventualy used this guide to http://www.brianlinkletter.com/how-to-run-gui-applications-xfce-on-an-amazon-aws-cloud-server-instance/ to setup  browser on EC2 and download the files through it


text:
Q: WebView onPause method. Memory leak. On my app I have a webview that loads a webpage which contains an online broadcast. The problem is that once I exit the app it seems to keep getting data since my free memory continues to decrease. It comes back to normal only if I close the app manually.
I have found this topic here as well:
How do I pause Flash content in an Android WebView when my activity isn't visible?
I also had the problem described there: my flash content kept working even if the app wasn't on the screen (I could hear it). Now it's fixed with the code shown there, but as I said, it keeps draining memory anyway.


text:
Q: HyperLink ID Pass with ASP.NET Can someone give an idea how I can see details of a selected product (suppose) regarding The productID in another page with HyperLink?? I have Tried To pass The ID with QueryString with Linq. But not done.

A: Mark up
<asp:HyperLink ID ="hyperLink" runat="server" />

C#
Set the url:
hyperLink.NavigateUrl = "somePage.aspx?id=123";

Read the url query string in somePage.aspx
var id = Request.QueryString["id"];

A: You have multiple problems in your code (as given in your comment section).
Here is what you have
 <asp:HyperLink ID = "View" server = "runat" NavigateUrl = '<%# ("~/pageredirect.aspx") + eval("CatergoryID") %>'>View</asp:HyperLink>

Issues:

*

*you have server = "runat" and it should be runat="server"

*you are concatenating CatergoryID with the redirect page and not really passing as   querystring which will really append the value like pageredirect.aspx + categoryid

*you are binding as CatergoryID and retrieving by query string name CategoryID which is not same (notice the typo)

Change your asp:HyperLink definition in the itemtemplate of the gridview in Approve.aspx as below
     <asp:TemplateField>
         <ItemTemplate>
             <asp:HyperLink ID="hlView" runat="server" NavigateUrl='<%# Eval("CategoryID", "~/pageredirect.aspx?CategoryID={0}") %>' Text="View" />
         </ItemTemplate>
    </asp:TemplateField>

and then in your pageredirect.aspx.cs access the querystring value as
if (!String.IsNullOrEmpty(Request.QueryString["CategoryID"]))
{
    int m = Int32.Parse(Request.QueryString["CategoryID"]);

    ....
}


text:
Q: Element–wise summation for custom function I use a custom function/head Operator[low, high] which encodes a generic polynomial expression split into "low" and "high" summands following considerations which are irrelevant to this question.
Two Operator objects should sum in the following way:
Operator[a,b] + Operator[c,d] -> Operator[a+c,b+d]

which is just standard element–wise summation that List does automatically. How can I tell Mathematica that this kind of automatic simplification or rearrangement is not only allowed, but desirable?

A: One of the standard ways for such things is using TagSetDelayed
Operator /: Operator[a_, b_] + Operator[c_, d_] := Operator[a + c, b + d]


text:
Q: How to unclear UITextField secure text entry in Swift? When I use default Security text Entry in UITextField in Swift Language after type type text once UITextField.

Once loss focus from UITextField after try to edit Secure text then UITextField is first reset and after it start put new text in UITextField.

How to edit old Secure Text without Storing data into Any Kind of String object

A: I'd suggest to create a custom UITextField class and override becomeFirstResponder() method do add your desired functionality:

You can override this method in your custom responders to update your
  object's state or perform some action such as highlighting the
  selection. If you override this method, you must call super at some
  point in your implementation.

The custom Class should be similar to:
class CustomSecureTextField: UITextField {
    override func becomeFirstResponder() -> Bool {
        super.becomeFirstResponder()

        if !isSecureTextEntry { return true  }

        if let currentText = text { insertText(currentText) }

        return true
    }
}

The logic of the implementation of becomeFirstResponder as follows:
By default, the secured-entry text field clears the inserted text when it is become first responder text, so what's happening in CustomSecureTextField that if the text field is secured-entry, it will re-insert the current inserted text -after clearing it-, but you have to make sure that the text field input is secured (that's the purpose of adding if !isSecureTextEntry { return true  }) or the text will be duplicated (re-inserted) each time the text field becomes first responder.
Output:
Note that both of text fields are types of CustomSecureTextField:

A: This answer helped me to figure out this problem.
   textField.isSecureTextEntry = true

following property not gonna work if you make testField isSecureTextEntrysecure property makes true .
   textField.clearsOnBeginEditing = false

A: There is an issue with the @Ahmd F solution when you simply tap on the field it will automatically add the text to the field I have resolved that in the below code thanks
override open func becomeFirstResponder() -> Bool {
    super.becomeFirstResponder()
    if !isSecureTextEntry { return true}
    if let currrentText = text {
        self.text = ""
        insertText(currrentText)
    }
    return true
}


text:
Q: Kestrel / IIS Express requires restart before edited .cshtml view changes are shown in browser I'm in the process of setting up my first ASP.NET vNext web application project.
I've got as far as getting the default project to build and run fine in both Windows and OSX. I've tested with kestrel on the mac, and in Windows IIS Express along with kestrel.
The problem I have encountered is that in Windows, editing a cshtml View file while the web server is running isn't reflected when I next refresh the browser.

*

*In OSX, I can run 'dnx web' and navigate to localhost:5000 and browse the site. I can then edit the .cshtml View files, switch back to the browser, hit refresh, and I can see all the changes. This is what I expect to happen and happened in previous versions.*

*In Windows, I can either run dnx web or IIS Express on the same site as I was using on OSX, navigate to localhost:5000 (or for IIS Express its own port number) and browse the site. I then switch to edit the cshtml View files, but when I switch back to the browser to reset, the changes aren't shown. It's not until I restart kestrel or IIS express that the changes are shown.
Curiously, however, I can edit a .cs Controller file and the site then recompiles by itself and I don't need to re-start it - in Windows at least. (In OSX, editing a controller file doesn't cause an auto-recompile, but that's an aside, I believe dnx-watch will fix that).
Is there something that I've missed in the project.json, or another setup file, which is causing the issue in Windows?
I have tried:

*

*creating a second completely clean web application project

*reinstalling ASP.NET

*desperately, lastly, creating a clean install of Windows 10 with Visual Studio 2015 Community Edition, to no avail

What's the way to get Kestrel or IIS Express in Windows to serve the updated cshtml View file after it's been edited, without restarting the server?
*side note, ASP.NET MVC in OSX is awesome!

A: Following on from @SRQ Coder's response, in particular the reassurance that it's supposed to work as I hoped, I found the reason but as yet no decent solution.
My project directory is located on a network share and I load the projects directly from there (I run Parallels Desktop on a mac). This works great with ASP.NET 4.x / MVC 5 (and earlier). However it looks like ASP.NET 5 doesn't support this setup.
The moment I copied the project folder to the local C: drive it all worked fine
When opening the project from a \\network-share, the project loads and I can run/debug the website, but CSHTML edits aren't shown in browser until IIS Express/Kestrel is restarted
Opening the project from a X:\ mapped network drive doesn't make any difference

A: I'm not able to recreate your problem on my machine: VS2015; Win10 etc. in either the IIS mode or Web: localhost/5000 mode and on multiple browsers.
I can edit both 'shared' cshtml files like '_Layout' and also the default 'home/index cshtml file with no problem.
Since you've re-installed so much of your system, I'm wondering if you have not re-installed web-essentials and enabled 'browser link'.
I feel your pain...


text:
Q: chain two remote tasks in celery by send_task In celery I want to chain two tasks from remote worker together. Can somebody tell me how to specify it in send_task? Or is there any other way of calling remote tasks?
BR

A: I was attempting to do the same thing.  I couldn't find any built-in functionality to generate a task purely by its name, however it wasn't difficult to add such tooling:
from celery import Task as BaseTask

class Task(BaseTask):
    def __init__(self, name, *args, **kwargs):
        super(BaseTask, self).__init__(*args, **kwargs)
        self.name = name

With this class, you can then do things like:
(
    Task('worker.hello').s('world') |
    Task('messaging.email-results').s(email_address='user@company.com')
)()

Or, alternatively:
app.send_task(
    'worker.hello', ['world'],
    chain=[
        Task('messaging.email-results').s(email_address='user@company.com')
    ]
)

EDIT:
Disregard above, I've since realized that the correct way to do this is by using the Signature class (as mentioned by @Chrismit below):
from celery import Signature

(
    Signature('worker.hello', args=['world']) |
    Signature('messaging.email-results', kwargs={'email_address':'user@company.org'})
)()

Or, alternatively:
from celery import Signature

app.send_task(
    'worker.hello', ['world'],
    chain=[
        Signature('messaging.email-results', kwargs={'email_address': 'user@company.com'})
    ]
)

An important note: Any tasks after the first task in a chain are not actually scheduled until a worker processes the task before it (this makes sense, as we don't know the input for later tasks until the previous task is run). The subsequent tasks are scheduled on the codebase of the worker. For this reason, you need to ensure that one of the following are true:

*

*each of your workers have knowledge of the task_routes so that it can place the followup tasks in the appropriate queue (e.g. in my example, it should know that tasks starting with messaging.* should go in the 'messaging' queue)

*you have encoded the correct queue into each Signature class when you create the chain. Celery already has tooling to derive a queue name from the task name which can be leaned on:
def get_queue_name(task_name):
    return app.amqp.router.route({}, task_name)['queue'].name

(
    Signature('worker.hello', args=['world']) |
    Signature(
        'messaging.email-results',
        kwargs={'email_address':'user@company.org'},
        queue=get_queue_name('messaging.email-results')  # If typing the task name twice annoys you, you could subclass Signature to do this automatically
    )
)()

(I think this is the cleanest solution, as it allows workers to not know about each other)

*all tasks are executed in the default queue. If you don't have any task_routes declared on the worker and there is no queue specified in the task's signature, then Celery will schedule that task in the worker's default_queue. Unless customized, that is 'celery'. I strongly recommend against doing this as it isn't very explicit and doesn't allow for much queue management, but nonetheless it is an option.

A: The easiest way is with the 'signature' function:
from celery import signature
chain = signature(
  'app_name.task_1',
  kwargs={..},
  queue='this_queue'
)
chain |= signature(
  'app_name2.task2',
  kwargs={..},
  queue='another_queue'
)
chain.apply_async()

A: I did it like this:
The trick is that you have to create new signature out of you task name.
app.send_task("{0}.{1}".format(app_name,task),args, link = [app.signature("{0}.{1}".format(app_name,task),next_args)])

A: For some reason, this signature approach didn't work for me. It created the signature object successfully though:
signature("some_remote_task", ...)

My celery version is 4.4, "some_remote_task" is defined as following:
    celery_app.conf.CELERY_ROUTES = {
        "some_remote_task": {
            "queue": "remote_queue",
            "routing_key": "key",
        }
    }

Then, I realized that the _app=None in the signature for some reason. After passing it like this, it worked:
signature("some_remote_task", app=celery_app, ...)

A: you can use celery canvas objects.
from celery import chain
my_chain = chain(task1.s((arg1, arg2)), task2.s((arg3, arg4))
result = my_chain.apply_async()


text:
Q: Do I need to use iframes or is there a different method? I've been working on this project for a few days and I really haven't found any solid information, other than a co-worker saying I should use a iframe. Hopefully others could chime in and help me out.
Problem:
I have a index page with various links that once clicked will perform a slidedown and reveal content from another page (subpage). However, the subpage has a image rotator which works fine when you view it on it's own, but doesn't work when you view in the index page. The jQuery is not being called, so the image rotator dies. What would be the best method of allowing the content from the subpages to be viewed with it's rotator on the index page?
Sorry if this is confusing, I've worded it the best I could, but if anyone can help, I'd really appreciate it. I have no experience with jQuery and am a total novice. Thank you guys in advance!

A: Look into jquery plugins like thickbox or fancy box.  They can do exactly what you want.

A: It sounds like you just need to load the proper JavaScript after the HTML for the "image rotator" is loaded into the DOM.
While you make the AJAX call for the "image rotator" use $.getScript() to get the include file for the "image rotator":
var XHRs = [];
XHRs.push($.get('<URL TO HTML>', function () {...}));
XHRs.push($.getScript('<URL TO JAVASCRIPT>', function () {...}));
$.when(XHRs).then(function () {
    //here is where you initialize the "image rotator" because the HTML and the JS will be loaded into the DOM
});

If you want to keep your "image rotator" initialization script external you can make another $.getScript() call inside the anonymous function in the .then function call.


text:
Q: Uncaught TypeError: Cannot read property 'top' of undefined Sorry for my bad English but i've a question with a problem.
Here is the message I've :
Uncaught TypeError: Cannot read property 'top' of undefined

Here is my function :
    function onScroll(event){
        var scrollPos = $(document).scrollTop();
        $('#menu-center a').each(function () {
            var currLink = $(this);
            var refElement = $(currLink.attr("href"));
            if (refElement.position().top<= scrollPos && refElement.position().top + refElement.heig
ht() > scrollPos) {
                $('#menu-center ul li a').removeClass("active");
                currLink.addClass("active");
            }
            else{
                currLink.removeClass("active");
            }
        });
    }

I don't understand because I've an other page in local with this function and it's works fine.
I've search on the web but nothing correspond to my problem.
Thanks for your help

A: change this line: var refElement = $(currLink.attr("href"));
in this line: var refElement = $(currLink).attr("href");

A: I found out the solution for the above issue. See the following code snippet
jQuery(document).ready(function($) {
  $(document).on("scroll", onScroll);
});

function onScroll(event){
  var scrollPos = $(document).scrollTop();
  $('#menu-center a').each(function () {
        var currLink = $(this);
        var refElement = currLink.attr("href");
        var splitEle = refElement.split('#');

        if ($("#"+splitEle[1]).offset().top <= scrollPos && $("#"+splitEle[1]).offset().top + $("#"+splitEle[1]).height() > scrollPos) {
            $('#menu-center ul li').removeClass("active");
            currLink.parent().addClass("active");
        }else{
            currLink.parent().removeClass("active");
        }
    });
}