text:
Q: How to combine the across () function with mutate () and case_when () to mutate values in multiple columns according to a condition? I have demographic data set, which includes the age of people in a household. This is collected via a survey and participants are allowed to refuse providing their age.
The result is a data set with one household per row (each with a household ID code), and various household characteristics such as age in the columns. Refused responses as coded as "R", and you could re-create a sample using the code below:
df <- list(Household_ID = c("1A", "1B", "1C", "1D", "1E"),
           AGE1 = c("25", "47", "39", "50", "R"),
           AGE2 = c("66", "23", "71", "R", "16"),
           AGE3 = c("28", "17", "R", "R", "80"),
           AGE4 = c("81", "22", "48", "59", "R"))

df <- as_tibble(df)

> df
# A tibble: 5 x 5
  Household_ID AGE1  AGE2  AGE3  AGE4
  <chr>        <chr> <chr> <chr> <chr>
1 1A           25    66    28    81
2 1B           47    23    17    22
3 1C           39    71    R     48
4 1D           50    R     R     59
5 1E           R     16    80    R

For our intents and purposes we re-code the "R" to "-9" so that we can subsequently convert the format of the AGE columns to integer, and carry out analysis. We usually do this in another software and my objective is to replicate this process in R.
I have managed to do this with the following code:
df <- df %>% mutate(AGE1 = case_when(AGE1 == "R" ~ "-9", TRUE ~ as.character(AGE1)))
df <- df %>% mutate(AGE2 = case_when(AGE2 == "R" ~ "-9", TRUE ~ as.character(AGE2)))
df <- df %>% mutate(AGE3 = case_when(AGE3 == "R" ~ "-9", TRUE ~ as.character(AGE3)))
df <- df %>% mutate(AGE4 = case_when(AGE4 == "R" ~ "-9", TRUE ~ as.character(AGE4)))

Given that this feels clumsy, I tried to find a solution using mutate_if etc. but read that these have been superseded by across(). Hence, I tried to replicate this operation using across():
df <- df %>%
  mutate(across(AGE1:AEG4),
          ~ (case_when(. == "R" ~ "-9")))

But I get the following error:
Error: Problem with `mutate()` input `..2`.
x Input `..2` must be a vector, not a `formula` object.
i Input `..2` is `~(case_when(. == "R" ~ "-9"))`.

Been wrestling with this and googling for a while now but can't figure out what I am missing. Would really appreciate some input on how to get this working, please and thank you.
EDIT: Solved!
df <- df %>%
  mutate(across(AGE1:AGE4, ~ (case_when(.x == "R" ~ "-9", TRUE ~ as.character(.x)))))

A: Or maybe this one which is not much difference from dear @TarJae's interpretation:
library(dplyr)
library(stringr)

df %>%
  mutate(across(AGE1:AGE4, ~ str_replace(., "R", "-9")),
         across(AGE1:AGE4, as.integer))

# A tibble: 5 x 5
  Household_ID  AGE1  AGE2  AGE3  AGE4
  <chr>        <int> <int> <int> <int>
1 1A              25    66    28    81
2 1B              47    23    17    22
3 1C              39    71    -9    48
4 1D              50    -9    -9    59
5 1E              -9    16    80    -9

Data:
df <- list(Household_ID = c("1A", "1B", "1C", "1D", "1E"),
           AGE1 = c("25", "47", "39", "50", "R"),
           AGE2 = c("66", "23", "71", "R", "16"),
           AGE3 = c("28", "17", "R", "R", "80"),
           AGE4 = c("81", "22", "48", "59", "R"))

df <- as_tibble(df)

A: Why not simply?
df[,2:5][df[, 2:5] == 'R'] <- '-9'

# A tibble: 5 x 5
  Household_ID AGE1  AGE2  AGE3  AGE4
  <chr>        <chr> <chr> <chr> <chr>
1 1A           25    66    28    81
2 1B           47    23    17    22
3 1C           39    71    -9    48
4 1D           50    -9    -9    59
5 1E           -9    16    80    -9

A: You could use across with replace.

*

*List to tibble with as_tibble()

*replace R with -9

*integer class for AGE

df %>%
  as_tibble() %>%
  mutate(across(everything(), ~replace(., . ==  "R" , "-9"))) %>%
  type.convert(as.is=TRUE)

Output:
  Household_ID  AGE1  AGE2  AGE3  AGE4
  <chr>        <int> <int> <int> <int>
1 1A              25    66    28    81
2 1B              47    23    17    22
3 1C              39    71    -9    48
4 1D              50    -9    -9    59
5 1E              -9    16    80    -9

redpajama_set_name: RedPajamaStackExchange


text:
Q: spark submit to minikube error related to krb5.conf I'm following this file to spark-submit to minikube : https://gist.github.com/jjstill/8099669931cdfbb90ce6f4c307971514
This is my modified version called spark-minikube.sh:
minikube --memory 8192 --cpus 3 start

kubectl create namespace spark

kubectl create serviceaccount spark-serviceaccount --namespace spark
kubectl create clusterrolebinding spark-rolebinding --clusterrole=edit --serviceaccount=spark:spark-serviceaccount --namespace=spark

cd $SPARK_HOME

# Asking local environment to use Docker daemon inside the Minikube
eval $(minikube docker-env)

# docker build -t spark:latest -f /path/to/Dockerfile .
IMG_NAME=asia.gcr.io/project-id/my-image:latest

# Submitting SparkPi example job
# $KUBERNETES_MASTER can be taken from output of kubectl cluster-info
KUBERNETES_MASTER=https://127.0.0.1:<port_number>

spark-submit --master k8s://$KUBERNETES_MASTER \
                 --deploy-mode cluster \
                 --name spark-pi \
                 --jars jars/gcs-connector-hadoop2-2.0.1-shaded.jar,jars/spark-bigquery-latest_2.12.jar \
                 --conf spark.executor.instances=2 \
                 --conf spark.kubernetes.namespace=spark \
                 --conf spark.kubernetes.container.image=${IMG_NAME} \
                 --conf spark.kubernetes.authenticate.driver.serviceAccountName=spark-serviceaccount \
                 local:///app/main.py

I'm getting this error:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.spark.unsafe.Platform (file:/usr/local/Cellar/apache-spark/3.1.1/libexec/jars/spark-unsafe_2.12-3.1.1.jar) to constructor java.nio.DirectByteBuffer(long,int)
WARNING: Please consider reporting this to the maintainers of org.apache.spark.unsafe.Platform
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
21/05/23 17:33:44 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
21/05/23 17:33:45 INFO SparkKubernetesClientFactory: Auto-configuring K8S client using current context from users K8S config file
21/05/23 17:33:45 INFO KerberosConfDriverFeatureStep: You have not specified a krb5.conf file locally or via a ConfigMap. Make sure that you have the krb5.conf locally on the driver image.
Exception in thread "main" org.apache.spark.SparkException: Please specify spark.kubernetes.file.upload.path property.
        at org.apache.spark.deploy.k8s.KubernetesUtils$.uploadFileUri(KubernetesUtils.scala:299)
        at org.apache.spark.deploy.k8s.KubernetesUtils$.$anonfun$uploadAndTransformFileUris$1(KubernetesUtils.scala:248)
        at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:238)
        at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:62)
        at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:55)
        at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:49)
        at scala.collection.TraversableLike.map(TraversableLike.scala:238)
        at scala.collection.TraversableLike.map$(TraversableLike.scala:231)
        at scala.collection.AbstractTraversable.map(Traversable.scala:108)
        at org.apache.spark.deploy.k8s.KubernetesUtils$.uploadAndTransformFileUris(KubernetesUtils.scala:247)
        at org.apache.spark.deploy.k8s.features.BasicDriverFeatureStep.$anonfun$getAdditionalPodSystemProperties$1(BasicDriverFeatureStep.scala:173)
        at scala.collection.immutable.List.foreach(List.scala:392)
        at org.apache.spark.deploy.k8s.features.BasicDriverFeatureStep.getAdditionalPodSystemProperties(BasicDriverFeatureStep.scala:164)
        at org.apache.spark.deploy.k8s.submit.KubernetesDriverBuilder.$anonfun$buildFromFeatures$3(KubernetesDriverBuilder.scala:60)
        at scala.collection.LinearSeqOptimized.foldLeft(LinearSeqOptimized.scala:126)
        at scala.collection.LinearSeqOptimized.foldLeft$(LinearSeqOptimized.scala:122)
        at scala.collection.immutable.List.foldLeft(List.scala:89)
        at org.apache.spark.deploy.k8s.submit.KubernetesDriverBuilder.buildFromFeatures(KubernetesDriverBuilder.scala:58)
        at org.apache.spark.deploy.k8s.submit.Client.run(KubernetesClientApplication.scala:106)
        at org.apache.spark.deploy.k8s.submit.KubernetesClientApplication.$anonfun$run$3(KubernetesClientApplication.scala:213)
        at org.apache.spark.deploy.k8s.submit.KubernetesClientApplication.$anonfun$run$3$adapted(KubernetesClientApplication.scala:207)
        at org.apache.spark.util.Utils$.tryWithResource(Utils.scala:2611)
        at org.apache.spark.deploy.k8s.submit.KubernetesClientApplication.run(KubernetesClientApplication.scala:207)
        at org.apache.spark.deploy.k8s.submit.KubernetesClientApplication.start(KubernetesClientApplication.scala:179)
        at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:951)
        at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:180)
        at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:203)
        at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:90)
        at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:1030)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:1039)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
21/05/23 17:33:45 INFO ShutdownHookManager: Shutdown hook called
21/05/23 17:33:45 INFO ShutdownHookManager: Deleting directory /private/var/folders/t2/psknqk615q7chtsr41qymznm0000gp/T/spark-100c4448-32bb-4fac-b5b5-d7a1b20d8525

Maybe it has something to do with this error message :

INFO KerberosConfDriverFeatureStep: You have not specified a krb5.conf
file locally or via a ConfigMap. Make sure that you have the krb5.conf
locally on the driver image.

How can I fix this? I'm not able to locate the krb5.conf anyway...

A: despite the cryptic message, what it actually wants to say is that you have not specified where to get your dependency jars from.
From official documentation:

If your application's dependencies are all hosted in remote locations
like HDFS or HTTP servers, they may be referred to by their
appropriate remote URIs. Also, application dependencies can be
pre-mounted into custom-built Docker images. Those dependencies can be
added to the classpath by referencing them with local:// URIs and/or
setting the SPARK_EXTRA_CLASSPATH environment variable in your
Dockerfiles. The local:// scheme is also required when referring to
dependencies in custom-built Docker images in spark-submit. We support
dependencies from the submission client's local file system using the
file:// scheme or without a scheme (using a full path), where the
destination should be a Hadoop compatible filesystem.

So to resolve your issue you just need to prepend your jars argument with local://
--jars local:///full/path/to/jars/gcs-connector-hadoop2-2.0.1-shaded.jar,local:///full/path/to/jars/spark-bigquery-latest_2.12.jar


text:
Q: Express 4.x routing and capturing URL parameters I'm currently refactoring my Node.js application's routing code, and was thinking of using the Router object introduced in Express 4.x. The router needs to capture some parameters in the URL, some of which happen at the very beginning.
At the moment it looks somewhat like this:
var views = require(...); // callback methods for generating each view.
var regexp = ':paramName(...)'; // Regular expression capturing a parameter.

app.get('/' + regexp + '/view_name', views.viewName);

This implementation works as expected, and in the views.viewName method I can retrieve the captured parameter through request.params.paramName.
Now, let's imagine that every valid URL needs to have that form (capturing that parameter). I was thinking of using the Router object like this:
var views = require(...);
var regexp = ':paramName(...)';
var router = express.Router();

router.get('/view_name', views.viewName);

app.use('/' + regexp, router);

This solution (as written) successfully routes the requests towards the views.viewName method, but it seems it fails to capture paramName in the request.
Is there something I'm missing in any of those calls so parameters captured in app.use(...) can be passed on to the request?


text:
Q: Core Data is very slow on the old device such as iPhone4 In my app, I have used simple core data structure.
I call my server api and then store like 30 objects per request into NSManagedObject.  So that 30 managed objects during per cycle and then my tableView reloaded.
My code looks like this
//we have 30 entities here in "post_items"
for(NSDictionary *post in [d objectForKeyNotNull:@"post_items"])
    {
        NSNumber *itemId= [post objectForKeyNotNull:@"id"];
    if(itemId){

        Item *i = [[ChannelStore sharedStore] fetchItem:itemId];

        if(!i) i = [[ChannelStore sharedStore] createItem];

        [i readFromJSONDictionary:post];

        [_items addObject:i];

    }

}

-(Item*)createItem
{
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:self.managedObjectContext];

Item *item = [[Item alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];

return item;

}

   -(Item*)fetchItem:(NSNumber *)itemId;
{

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Item"];

// Create Predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@", @"itemID", itemId];
[fetchRequest setPredicate:predicate];

[fetchRequest setFetchBatchSize:1];

// Execute Fetch Request
NSError *fetchError = nil;

NSArray *result = [self.managedObjectContext executeFetchRequest:fetchRequest error:&fetchError];
Item* item = nil;

if (!fetchError) {
    item = [result firstObject];

} else {
    NSLog(@"Error fetching data.");
    NSLog(@"%@, %@", fetchError, fetchError.localizedDescription);
}

return item;
}

What make the process slow is because I have to fetch so check for existing Item first and then create new one if there is none.
I know that I use only one MOC here. This result in UI blocking. But if we concern about speed here. I doubt implementing parent-child MOC would help. Because in parent-child . I will just have another MOC running on background but it is one MOC for 30 objects it should more or less take the same amount of times.
Any help would be appreciated. I tried searching all over but could not find a proper solution for this. Or maybe, I should not use Core Data for "Items" object at all ?
PS. I do not have performance problem in newer devices but just the old device that make my app looks very laggy and slow

A: The main reason for your slowness here is do to the number of fetch's that you are executing.  Each fetch request forces the core data stack to make a roundtrip all the way to disk, since you are doing this for each item you are importing, this results in a bottleneck for your importing implementation.  This bottleneck then results in a UI slowdown because it is happening on a main queue context.
The solution is to perform a single fetch to see which of the incoming objects you already have locally and which are new.
Once you have your local objects in memory, it is much faster to check that array than to use an NSFetchRequest each time.
Here is a WWDC video that addresses your exact problem: https://developer.apple.com/videos/play/wwdc2013-211/
Specifically they talk about implementing "Update or Insert" at around 14m into the video.

A: You can optimize your NSFetchRequests by asking CodeData to fetch only the properties of interest (instead of fetching all the properties).
So, if you are interested only in itemID, then ask CoreData to check only itemIDs
theFetchRequest.predicate = ...;
// you MUST set the predicate BEFORE using the next lines, otherwise your app will crash

theFetchRequest.includesSubentities = NO;
theFetchRequest.propertiesToFetch = @[@"itemID"];

This helps a lot when your entities have

*

*attributes of NSData type

*relationships to other entities

A few days ago these two lines made my code 400 times faster...

A: You must use privatequeueContext for fetching data from server & mainQueuCOntext for handling UI part. For more information please go through following links
CoreDataConcurrency_Swift
CoreDataCConcurrency_ObjC


text:
Q: Inverse Laplace transform of a Gaussian Bell curve Is it possible to find a continuous bounded real function $f$ such that $\mathcal Lf(z)=\exp(-z^2)$ where $\mathcal Lf(z)=\int_0^{+\infty} e^{-tz}f(t)dt$ ?
I don't find anything in the tables...


text:
Q: Multiple joins error in group by when I use SUM function I'm getting this error:
Column 'MDR.dbo.nav_BG$Location.Name' is invalid in the select list because
it is not contained in either an aggregate function or the GROUP BY clause.

He wants from me to add all my fields in group by but this is incorrect.
DECLARE @date datetime2 = CURRENT_TIMESTAMP;
SELECT
[Source Document ID]        AS Source
,Location.Name              AS Address
,[Item No_]                 AS No
,[Document No_]             AS Document
,Item.[No_ 2]               AS No2
,MN.Name                    AS Brand
,SUM([Quantity Requested])  AS Qty,
CASE WHEN qty > 20 THEN  'No' ELSE 'Yes'  END AS Priority
,[Created On]               AS Date

FROM [MDR].[dbo].[nav_BG$AWHM_Document_Line] AS DocLine
JOIN [MDR].[dbo].[nav_BG$Item] AS Item ON DocLine.[Item No_] = Item.[No_]
JOIN [MDR].[dbo].[nav_BG$Location] AS Location ON DocLine.[Source Document ID] = Location.Code
JOIN [MDR].[dbo].[nav_BG$Manufacturer] AS MN ON Item.[Manufacturer Code] = MN.Code

WHERE [Location Code] = 'XXX'
AND   [Document Type] = 'XXX'
AND   [From Zone Code] = 'XXX'
AND   (DATEPART(yy, [Created On]) = YEAR(@date)
AND    DATEPART(mm, [Created On]) = MONTH(@date)
AND    DATEPART(dd, [Created On]) = DAY(@date))
GROUP BY [Source Document ID]
ORDER BY [Created On]

Expected result would be the SUM([Quantity Requested]) group by [Source Document ID].
How to use only one group by [Source Document ID]?

A: If you're going to use an aggregate function, you normally need to specify all your non-aggregated columns (like Location.Name) in the GROUP BY clause.  Otherwise, you can't return them in your query.
If you want to return non-aggregated fields and also include an aggregate, you need to use a window function:
SUM([Quantity Requested]) OVER(PARTITION BY [Source Document ID])
If your DBMS supports it, it would look like:
SELECT
[Source Document ID]        AS Source
,Location.Name              AS Address
,[Item No_]                 AS No
,[Document No_]             AS Document
,Item.[No_ 2]               AS No2
,MN.Name                    AS Brand
,SUM([Quantity Requested]) OVER(PARTITION BY [Source Document ID])  AS Qty,
CASE WHEN qty > 20 THEN  'No' ELSE 'Yes'  END AS Priority
,[Created On]               AS Date

FROM [MDR].[dbo].[nav_BG$AWHM_Document_Line] AS DocLine
JOIN [MDR].[dbo].[nav_BG$Item] AS Item ON DocLine.[Item No_] = Item.[No_]
JOIN [MDR].[dbo].[nav_BG$Location] AS Location ON DocLine.[Source Document ID] = Location.Code
JOIN [MDR].[dbo].[nav_BG$Manufacturer] AS MN ON Item.[Manufacturer Code] = MN.Code

WHERE [Location Code] = 'XXX'
AND   [Document Type] = 'XXX'
AND   [From Zone Code] = 'XXX'
AND   (DATEPART(yy, [Created On]) = YEAR(@date)
AND    DATEPART(mm, [Created On]) = MONTH(@date)
AND    DATEPART(dd, [Created On]) = DAY(@date))
-- GROUP BY [Source Document ID]
ORDER BY [Created On]

This will let you return the detail rows along with the SUM() calculated over each [Source Document ID] group.


text:
Q: Finding maximum number of concurrent users by login time I have a table that holds login times for users:
 | Login time       | Logout time      | System | Username
 | 01/01/2015 09:00 | 01/01/2015 10:00 | A      | Joe
 | 01/01/2015 10:00 | 01/01/2015 11:00 | A      | Fred
 | 01/01/2015 12:00 | 01/01/2015 14:00 | B      | Tom
 | 01/01/2015 15:30 | 01/01/2015 16:00 | B      | Dick
 | 01/01/2015 09:00 | 01/01/2015 17:00 | A      | Harry

... and I'd like to report on the maximum number of concurrent users each system for a particular day: in the above example, it'd be
 | System | Concurrency
 |   A    |   2
 |   B    |   1

... because Fred and Harry were logged in to system A at the same time, and B only had one concurrent user.
I've tried:
SELECT t1.system,count(t1.system)
FROM logins t1,logins t2
WHERE t1.system=t2.system
and t2.logintime <= t1.logouttime
AND  t2.logouttime>t1.logintime
group by t1.system

... but that doesn't seem to give me what I want. Can anyone suggest a simplest solution?

A: For any given time, you can get the number of concurrent users by adding up the number of logins on or before the time and subtracting the number of logouts.
There are several ways to approach this.  In SQL Server 2008, one relatively simple way is to use correlated subqueries.  So the following gets the cumulative values at any given time:
      select l.system, l.logintime,
             (select count(*)
              from logins l2
              where l2.system = l.system and l2.logintime <= l.logintime
             ) as cumeins,
             (select count(*)
              from logins l2
              where l2.system = l.system and l2.logouttime <= l.logintime
             ) as cumeouts
      from logins l
     ) l
group by l.system, cast(logintime as date);

To get the maximum number per day, simply do an aggregation on the above and pull out the maximum difference:
  select system, cast(logintime as date) as thedate,
         max(coalesce(cumeins, 0) - coalesce(cumeouts, 0)) as concurrent
  from (select l.logintime,
               (select count(*)
                from logins l2
                where l2.system = l.system and l2.logintime <= l.logintime
               ) as cumeins,
               (select count(*)
                from logins l2
                where l2.system = l.system and l2.logouttime <= l.logintime
               ) as cumeouts
        from logins l
       ) l
  group by system, cast(logintime as date);

A: Atilla is correct about how you define concurrence. Let's say you define concurrence as being logged in with the same minute. In that case, you'd want the following (my column names may not be identical to yours as by habit I don't include spaces). If you run this against your data, it will get what you want. You need to adjust what's inside the with statement accordingly if you want to the nearest 5 minutes or the nearest millisecond (that might run pretty slowly), etc. If you really want true concurrency, you'll need a combination of correlated subqueries similar to but more complex than what Gordon Linoff suggested.
declare @minlogintime smalldatetime,@maxlogouttime smalldatetime
select @minlogintime=min(logintime),@maxlogouttime=max(logouttime) from logins;
with minuterange as
(
    select dt=dateadd(mi,1,@minlogintime)
    where dateadd(mi,1,@minlogintime) < @maxlogouttime
    union all
    select dateadd(mi,1,dt)
    from minuterange
    where dateadd(mi,1,dt) < @maxlogouttime
)
select * into #tmpminutes from minuterange
option (maxrecursion 0)

--get concurrency count
select b.system,convert(varchar,b.dt,112),max(b.users)
from
(select a.system,a.dt,count(distinct a.username) as users
from
(SELECT
    t1.Username,t1.System,m.dt
FROM
    Logins t1
INNER JOIN #tmpminutes m on m.dt between t1.logintime and t1.logouttime) as a
GROUP BY
    a.System,a.dt) as b
GROUP BY
    b.System,convert(varchar,b.dt,112)

drop table #tmpminutes

A: Use following for day group, see following fiddle
SELECT System,convert(varchar(10),LoginTime,112),COUNT(*) AS CONCURRENT FROM logins
GROUP BY SYSTEM,convert(varchar(10),LoginTime,112)

If you want tighter window than days, you should use different group by.
This does not answer what you want fully, but you need to define your problem better. What is your window for concurrency? One hour or One day?
Following SQL gives concurrent users as you defined but without more information about concurrency window, how to to group and count this concurrent users?
SELECT
l1.System,convert(varchar(10),l1.LoginTime,120) AS l1LoginDay
, l1.Username as l1Username
, l2.Username as l2Username

FROM logins l1
INNER JOIN logins l2
ON
l1.System = l2.System
AND convert(varchar(10),l1.LoginTime,120) = convert(varchar(10),l2.LoginTime,120)
AND l1.Username != l2.Username
WHERE
1 = 1
and l2.LoginTime <= l1.LogoutTime
AND  l2.LogoutTime>l1.LoginTime


text:
Q: Codeigniter Pagination Not working Properly I've been trying to learn using the CI framework, and I'm a beginner at PHP too. Can anybody tell me what am i doing wrong here. The contents on the page seems to be different but it doesn't show the page no. properly. When I'm at some other page, the page number is still showing the same as the initial one. It doesn't change. Here is my code for pagination. Any help will be appreciated.
    $this->load->library('pagination');
    $config = array();
    $config['base_url'] = site_url("infos/display/$query_id/$sort_by/$sort_order");
    $config['total_rows'] = $data['num_results'];
    $config['per_page'] = $limit;
    $config['uri_segment'] = 3;
    $config['num_links'] = 9;
    $this->pagination->initialize($config);
    $data['pagination'] = $this->pagination->create_links();

A: for the $config['base_url'] = base_url()."infos/display/$query_id/$sort_by/$sort_order";

*

*use base_url for your url config, CI's pagination needs the url without the index.php in it, which site_url automatically adds.

*and what is on $data['num_results'] you might want to check if it gives of the proper number of total rows

A: try this
  $config['base_url'] = base_url("index.php/infos/display/$page/$query_id/$sort_by/$sort_order");
    $config['uri_segment'] = 3;

You mus pass the $page to the controller or vieuw in which you have the pagination.
I mostly do this in controller
function openpage() {
$data['page'] = $this->uri->segment(3, 0);
...
...
}

make sure you always set the $page.


text:
Q: COD BO3 campaign 4 players, 2 consoles offline I gather you can setup campaign a max of 2 players for couch coop and 4 players for online, but is it possible to do 4 players offline just by connecting 2 consoles ( 2 player split screen on each console)?

A: According to this website you can play four player co-op through LAN. The response to the question: "How many players are supported in combo co-op?" is the following:

Two players per system are supported in combo co-op with four players total being able to play the campaign and/or zombies mode.


text:
Q: Automatically Add a default category to a Custom Post Type before save_post action I am using the Enhanced Image Library plugin to automatically add a taxonomy to images uploaded to a custom post type. The plugin has a feature that will allow the post's categories to be automatically added to associated images when the image is uploaded.
However, if the post category is not assigned to the post before the images are added, then the images will not be categorized correctly. The easiest solution would be if there was a way to assign a default category directly after the "New Post" button was clicked, before the user has a chance to input any data into the post fields, and well before the save_post action.
All of the answers to this question that I found seem to reference the save_post or publish_post actions. Is there any action that can be utilized when "new post" is initially clicked?
If there is not, do you have any other suggestions? Should I attempt to add javascript somewhere to pre-check this field in a post admin template? If so, where should I find that?

A: the hooks "save_post..." are called too when a new post is created
then you can set default values with that
$customPostType = "customTypeCode";

add_action("save_post_$customPostType", function ($post_ID, $post, $update) {

    if (!$update) {

        // new item
        // place to set default values

        return;

    }

    // updating a existing item
    // ...

}, 10, 3);

A: As far as I can tell, there is no way to hook into the post when the 'new post' screen is initially generated. Instead, I loaded some javascript in the admin template and had the javascript check the category box for me.


text:
Q: Как правильно хранить JSON в БД при работе с Laravel? Приложение получает пользовательский ввод в формате JSON и сохраняет его в БД, выводит на страницах.
Как правильно работать с JSON в Laravel, в каком виде он должен храниться в БД?
Нужно ли устанавливать тип поля в БД как JSON, экранировать или кодировать его для безопасной работы?


text:
Q: Angular router, calling controller many times This code is functional, but it could work better. My question:
How i can insert navDetalle or other views in many states without call controller  again.

(function() {
  'use strict';

  angular
    .module('miApp')
    .config(routerConfig);

  var nav = {
    templateUrl: 'app/nav/nav.html',
    controller: 'NavController',
    controllerAs: 'nav'
  };
    var navInter = {
    templateUrl: 'app/nav/navInter.html',
    controller: 'NavController',
    controllerAs: 'nav'
  };
  var navDetalle = {
      templateUrl: 'app/navDetalle/navDetalle.html',
      controller: 'NavDetalleController',
      controllerAs: 'navDetalle'
  };
  /** @ngInject */
  function routerConfig($stateProvider, $urlRouterProvider) {

    $stateProvider
      .state('home', {
        url: '/',
        views: {
            // the main template will be placed here (relatively named)
            'nav': nav,
            'carousel': {
              templateUrl: 'app/carousel/carousel.html',
              controller: 'CarouselController',
              controllerAs: 'carousel'
            },
            'footer':{
              templateUrl: 'app/footer/footer.html'
            }
        }
      })
      .state('detalle', {
        url: '/detalle/:idDetalle',
        views:{
            'nav': navInter,
            'detalle': {
              templateUrl: 'app/detalle/detalle.html',
              controller: 'DetalleController',
              controllerAs: 'detalle'
            },
            'navdetalle': navDetalle,
            'footer':{
              templateUrl: 'app/footer/footer.html'
            }
        }

      })
      .state('resumen', {
        url: '/resumen',
        views:{
            'nav': navInter,
            'navdetalle': navDetalle,
            'footer':{
              templateUrl: 'app/footer/footer.html'
            }
        }

      })
      .state('success', {
        url: '/success',
        views:{
            'nav': navInter,
            'success': {
              templateUrl: 'app/success/success.html',
              controller: 'SuccessController',
              controllerAs: 'success'
            },
            'navdetalle': navDetalle,
            'footer':{
              templateUrl: 'app/footer/footer.html'
            }
        }

      })
      .state('cancel', {
        url: '/cancel',
        views:{
            'nav': navInter,
            'navdetalle': navDetalle,
            'cancel': {
              templateUrl: 'app/cancel/cancel.html',
              controller: 'CancelController',
              controllerAs: 'cancel'
            },
            'footer':{
              templateUrl: 'app/footer/footer.html'
            }
        }

      });

    $urlRouterProvider.otherwise('/');
  }

})();

and if you have suggestion on another improvements please comment

A: I don't know if what you want is possible. Because ui-router always creates a new instance to the view's controller, and that makes sense cause every single view has your own scope.

A: I'm not sure if this is possible to prevent executing controller every time. But, I do have another solution. That might work. The Ionic Framework do this internally by preserving controller state.
Create a global controller and add it to <body> or <html> tag so that its scope can be available every time.
app.controller('GlobalController', function($scope) {

    var navDetalleCtrlInstantiated = false;

    $scope.$on('$stateChangeStart', function(e, toState, toParams) {
        if (!navDetalleCtrlInstantiated && toState.views && toState.views.navdetalle) {
            // Do the common logic on controller instantiation

           // Mark so that we don't have to do the same logic again
            navDetalleCtrlInstantiated = true;
        }
    });
});

In your view:
<body ng-controller="GlobalController">
</body>

And remove logic from your NavDetalleController.


text:
Q: How to order 3 columns in series? python pandas I have the following dataframe:
df = {names:["CARL","HERMES","LEO"], srv:[234,123,44], mx_l1:[10,12,8], mx_l2:[20,8,10], mx_l3:[12,23,11], label:["street","city","apto"]}

but the length columns(mx_l1,mx_l2,mx_l3) must go vertically, so I guarantee their order with the current columns.
How could I sort those columns in series consecutively but in a single column
something like this
name  |srv|max_lenght|label
CARL  |234|10        |street
CARL  |234|20        |city
CARL  |234|12        |apto
HERMES|123|12        |street
HERMES|234|8         |city
HERMES|234|23        |apto

My code
df2 = df.melt(id_vars=["srv", "name"],
              value_vars=["max_l1", "max_l2", "max_l3"],
              value_name="max_lenght")\
    .sort_values(by="srv")\
    .drop("variable", axis=1)\
    .reset_index(drop=True)

A: IIUC, this is what you want:
df = (
    df.melt(
        id_vars=["names", "srv", "label"],
        value_vars=["mx_l1", "mx_l2", "mx_l3"],
        value_name="max_length",
    )
    .sort_values(["names", "srv", "max_length"])
    .drop(columns="variable")
    .reset_index(drop=True)
)

print(df)
names  srv   label  max_length
    0    CARL  234  street          10
    1    CARL  234  street          12
    2    CARL  234  street          20
    3  HERMES  123    city           8
    4  HERMES  123    city          12
    5  HERMES  123    city          23
    6     LEO   44    apto           8
    7     LEO   44    apto          10
    8     LEO   44    apto          11

A: Use set_index and stack
df_final = (df.set_index(['names','srv','label']).stack().droplevel(-1)
              .rename_axis(index={'label':'max_length'})
              .reset_index(name='label'))

Out[31]:
    names  srv max_length  label
0    CARL  234     street     10
1    CARL  234     street     20
2    CARL  234     street     12
3  HERMES  123       city     12
4  HERMES  123       city      8
5  HERMES  123       city     23
6     LEO   44       apto      8
7     LEO   44       apto     10
8     LEO   44       apto     11


text:
Q: How to structure MQ consumer loop in Erlang/OTP? I need to create simple application that consumes message queue and asynchronously handles messages using Erlang/OTP. Consider this pseudo-example in Golang:
var queue chan
func main() {
    for req := range queue {
        go handleRequest(req)  //handle asynchronously
    }
}

How to correclty structure this following OTP principles?
I've been looking for gen_server, but in this case where do I define my loop resursive?
Also, how can I start asynchronous handle? Should I create another supervisor and use supervisor:start_child on every new message?

A: The gen_server module in the standard library defines the recursive loop for you.  The only thing you need to do is to implement callback functions to handle messages.  If the message queue is sending Erlang messages to your gen_server process, you'd do something like:
handle_info({incoming_request, Request}, _From, State) ->
    async_handle_request(Request),
    {noreply, State}.

To handle the requests asynchronously, async_handle_request would start a process for each incoming request.  There are two ways of doing that: either just spawn a process, or start each process under a simple_one_for_one supervisor.  The differences come down to error handling and shutdown behaviour.  What do you do if handling a request fails?  Do you ignore the error, or let it propagate to the gen_server process, or do you have the supervisor restart the process and retry the request?
This question explains when you might use a simple_one_for_one supervisor.  If you just want to spawn a process, that would look like this:
async_handle_request(Request) ->
    spawn_link(fun() -> handle_request(Request) end).

And then the actual request handling logic is implemented in handle_request.


text:
Q: Finding the altitude of the cone with minimum volume circumscribed about a hemisphere of radius R
I have tried considering a plane parallel to that of the base of the hemisphere at a distance $R$  to work with some similar triangles, but all I could find is that the radius of the base of the smaller cone is $r = \frac{R(h-R)}{h}$ where $h$ is the altitude of the big cone. I'm having trouble finding a relation between $R$ and $h$. Any help would be appreciated.
For those wondering, this is Problem 50 from Chapter V by Differential and Integral Calculus by N. Piskunov.

A: Hints:

*

*Your diagram slightly obscures the fact there are two radii.  Try this one instead:

*

*Find $r$ in terms of $h$ and $R$, using similar triangles and Pythagoras: I think you get $\dfrac{hR}{\sqrt{h^2-R^2}}$ rather than $\dfrac{R(h-R)}{h}$

*Find the volume of the cone in terms of $h$ and $r$, and then by substitution in terms of $h$ and $R$

*Find the $h$ which minimises this volume while keeping $R$ constant, for example by differentiation - you should get $R \sqrt 3$

A:
See the diagram. Now can you find $OH$ and $OA$ in terms of radius of the sphere $R$ and angle $x$ where $OH$ is the height of the cone, $OA$ is radius of the base of the cone and $OT = R$ is the radius of the sphere. $OT$ is perpendicular to $AH$.
Then you need to find angle $x$ for which the volume is minimum and that boils down to maximizing $\sin^2x \cos x$.
Can you take it from here?

A:
Minimize
$$ volume \; V = \frac{\pi r^2 h}{3} \tag1$$
subject to constraint of right triangle sides ( not directly given) connecting the constant $R$
$$\frac{1}{R^2}=\frac{1}{h^2}+\frac{1}{r^2}  \tag 2$$
By plugging in (2) and setting derivative to zero as usual and simplifying we get
$$ \frac{h}{r}= \sqrt 2\;;  \frac{h}{R} =\sqrt 3 .\tag 3$$


text:
Q: Can not Add Rows datatable.js - sAjaxSource Ajax call
Html Code: I'm using plain table with few column headers

             ModemName
             AssignedTo
             AssignDate
             ReturnedDate
             CreatedName

Js Code:
  Here is js method which im using,

var oTable = $('#gvAssgin').dataTable
           ({
               "bProcessing": true,
               "bServerSide": true,
               "sAjaxSource": "AssignHistory.aspx/getAllModemAssign",
               "fnServerData": function(sSource, aoData, fnCallback) {
                   $.ajax({
                       type: "POST",
                       url: "AssignHistory.aspx/getAllModemAssign",
                       contentType: "application/json; charset=utf-8",
                       dataType: "json",
                       data: "{}",
                       success: function (json) {
                           fnCallback(json)
                       },
                       error: function (xhr, textStatus, errorThrown) {
                           alert(xhr.responseText);
                       }
                   });
               },
               "columns": [
                   { data: "ModemName" },
                   { data: "AssignedTo" },
                   { data: "AssignDate" },
                   { data: "ReturnedDate" },
                   { data: "CreatedName" }
               ]
           });

In browser debugging i can see result in json.d, But, No data visible on page. I don't know what is the issue in this code.
Here is the screen shot on browser console screen,


text:
Q: Is Finn's sword able to interact with him?
Finn's sword first appears in the Breezy episode, being held by the image of princess Bubblegum during the last song (before Finn gets his arm back). Finn literally gets his arm back in the is that you episode after resurrecting Prismo Finn interacts with the other Finn from another dimension and turns him into his sword. In the dentist episode he says something to his sword.

Did he really talk to the Finn from the sword, or just imagined him answering?


text:
Q: How to get parent node in Firebase I'm using Firebase to display content into RecyclerView. In adapter class I use this code to pass selected node's key:
holder.view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, NewsDetails.class);
            intent.putExtra("NewsKey",getRef(position).getKey());
            context.startActivity(intent);
        }
    });

This code passed key(blue arrow in screenshot), i also want to pass parent node(red arrow) as String. How can i get parent node and pass it in putExtra ?

Here is how i call my database:
private void setUpFirebase() {
    newsRecycler = findViewById(R.id.newsRecycler);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setReverseLayout(true);
    linearLayoutManager.setStackFromEnd(true);
    newsRecycler.setLayoutManager(linearLayoutManager);

    FirebaseRecyclerOptions<NewsItem> options =
            new FirebaseRecyclerOptions.Builder<NewsItem>().setQuery(FirebaseDatabase.getInstance().getReference().child("news"), NewsItem.class).build();

    newsAdapter = new NewsAdapter(options, this);
    newsRecycler.setAdapter(newsAdapter);
}

A: You can use getParent() on the database reference "getRef(position)" in your case, and then put its key into the intent using putExtra()
Intent intent = new Intent(context, NewsDetails.class);
intent.putExtra("NewsKey", getRef(position).getKey());
DatabaseReference parent = getRef(position).getParent();
if (parent != null)
    intent.putExtra("ParentKey", parent.getKey());
context.startActivity(intent);

A: You can try
if(ref.parent() != null) {
  val news = ref.parent().key()
}

For more information read DatabaseReference#getParent()


text:
Q: Node.js - Access Google Secret Manager locally I can't seem to figure it out. All I want to do is access a test secret that's been created for me, when locally running my appliction. I was given a service-account.json that looks as follows, which I was told to use for local access, but I can't find any documentation or any other resources that show what to do with the file.
{
  "type": "service_account",
  "project_id": "test-dev-project",
  "private_key_id": "12cea3c45d67d0d89f0ccfca1bede23d4d56c7b8",
  "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBg1234\n-----END PRIVATE KEY-----\n",
  "client_email": "my-secrets-email@test-dev-project.iam.gserviceaccount.com",
  "client_id": "123456789012345678901",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/my-secrets-email%40test-dev-project.iam.gserviceaccount.com"
}

What little I could glean from the docs was that I should "set" its path via Powershell, but even when I do, and then run node index.js again, I still get the exact same error:
Error: 7 PERMISSION_DENIED: Secret Manager API has not been used in project 123456789012 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/secretmanager.googleapis.com/overview?project=123456789012 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.

My only other experience with these kinds of service-account files is with Firebase Functions, and there you set the file path as an argument to the app initialization function, so I thought I'd have to do something similar here, but I can't find anything that indicates such.
Here's what my Node project looks like, in its entirety:
// ./index.js
(async() => {
  const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');
  const client = new SecretManagerServiceClient();
  const SOME_APIKEY = await client.accessSecretVersion({ name: 'latest' });
  console.log('key:', SOME_APIKEY);
})();

// ./package.json
{
  "name": "google-secret-attempt-17",
  "main": "index.js",
  "scripts": {},
  "dependencies": {
    "@google-cloud/secret-manager": "^3.10.1"
  }
}

// ./service-account.json (already posted its content above)

The steps that I've been trying is:

*

*Run $env:GOOGLE_APPLICATION_CREDENTIALS="./service-account.json" in Powershell

*Run node index.js in Powershell

I've also tried explicitly setting process.env.GOOGLE_APPLICATION_CREDENTIALS = './service-account.json' at the start of my index.js and then running step 2, but that resulted in exactly the same outcome, so I don't know what to do anymore.
Any insight into where I'm going wrong or anything else would be highly appreciated.

A: Looks like Secrets Manager api is not enabled in the concerned project. Please ask the person who provided the the service-account.json file to visit https://console.developers.google.com/apis/api/secretmanager.googleapis.com/overview?project=123456789012 and enable the API. Once complete you should be able to access the api.


text:
Q: OutOfMemory Exception - for adapter.notifiyDataSetChanged() while loading images with picasso I am facing the outOfMemory exception while loading images with Picasso.
I am creating picasso builder with OkHttp and created Picasso Singleton class to cache images.
Scenario:
I have 100+ image feeds which are to be loaded. I am getting images in sets and each set has 25 image url which i am setting with Picasso. I am using recyclerview and whenever new set of images come in i am calling adapter.notifyDataSetChanged(). I am loading first set - no issues, for 2nd and 3rd set when making retrofit to get next set and adding to existing list and calling - adapter.notifyDataSetChanged(). For 3rd set when I call adapter.NotifyDataSetChanged() app crashes with outOfMemoryException
BUT
When i load all 3 sets of 75 images, I don't face any issues.
Code:
Application Class - where I am building Picasso.
 Picasso.Builder builder = new Picasso.Builder(this)
            .memoryCache(new LruCache(24000));
    builder.downloader(new OkHttpDownloader(this,Integer.MAX_VALUE));
    Picasso built = builder.build();
    built.setLoggingEnabled(true);

Picasso Singleton Class:
public class PicassoCache {

/**
 * Static Picasso Instance
 */
private static Picasso picassoInstance = null;

/**
 * PicassoCache Constructor
 *
 * @param context application Context
 */
private PicassoCache (Context context) {

    Downloader downloader   = new OkHttpDownloader(context, Integer.MAX_VALUE);
    Picasso.Builder builder = new Picasso.Builder(context);
    builder.downloader(downloader);

    picassoInstance = builder.build();
}

/**
 * Get Singleton Picasso Instance
 *
 * @param context application Context
 * @return Picasso instance
 */
public static Picasso getPicassoInstance (Context context) {

    if (picassoInstance == null) {

        new PicassoCache(context);
        return picassoInstance;
    }

    return picassoInstance;
}

}

Code where I am setting/loading images with Picasso.
  PicassoCache.getPicassoInstance(context).load(url).placeholder(R.mipmap.banner_placeholder).into(mView);

Code where I am updating the existing list to load when there is data set changed.
Inside Retorfit OnSuccess message:
    if (response.code() == 200) {

List<CampaignCard> newCampaigns = response.body().getCampaigns();

for (int i = 0; i < newCampaigns.size(); i++) {
    if (!campaignCards.contains(newCampaigns.get(i))) {
        campaignCards.add(newCampaigns.get(i));
    }
}

dashBoardAdapter.notifyDataSetChanged();

} else if (response.code() == Params.CODE_422) {
    Utils.ShowServiceErrorMessages(getActivity(), response);
} else if (response.code() == Params.CODE_401) {
    Utils.Logout(getActivity());
}

Adapter Class:
public class DashboardAdapter extends RecyclerView.Adapter<DashboardAdapter.DashboardViewHolder> implements View.OnClickListener {

    private static final int VIEW_TYPE_CAMPAIGN = 1;
    private static final int VIEW_TYPE_FEED = 2;

    DashboardViewHolder holder;

    protected List list;
    protected int viewTypeLayout;
    Context context;
    int position;

    Dashboard.DashboardActionList actionList;
    Map<String, SourceContent> mPreviewLinkMapper;
    ViewGroup parent;

    //Picasso p;
    public DashboardAdapter(List list, int viewTypeLayout) {
        this.list = list;
        this.viewTypeLayout = viewTypeLayout;
    }

    public DashboardAdapter(List list, int viewTypeLayout, Context context, Map<String, SourceContent> mPreviewLinkMapper) {
        this.list = list;
        this.viewTypeLayout = viewTypeLayout;
        this.mPreviewLinkMapper = mPreviewLinkMapper;
    }

    @Override
    public DashboardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        context = parent.getContext();
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_feed, parent, false);
        return new DashboardViewHolder(view, 2);

    }

    @Override
    public void onBindViewHolder(DashboardViewHolder holder, final int position) {
        BindFeedData(holder, position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @SuppressWarnings("unchecked")
    private void BindFeedData(DashboardViewHolder holder, int position) {
        List<Feed> feeds = (List<Feed>) list;
        if (holder.mBannerImage != null) {
            if (feeds.get(position).getCampaign().getParticipation().getType().toLowerCase().contains("video")) {

                holder.mPlayIcon.setVisibility(View.VISIBLE);
                String url = feeds.get(position).getCampaign().getParticipation().getThumbnail_url();
                Utils.LoadImages(context, url, holder.mBannerImage, false);

            } else if (feeds.get(position).getCampaign().getParticipation().getType().toLowerCase().contains("gif")) {

                holder.mPlayIcon.setVisibility(View.GONE);
                String url = feeds.get(position).getCampaign().getParticipation().getPost_file();
                Utils.loadGif(context, url, holder.mBannerImage);

            } else if (feeds.get(position).getCampaign().getParticipation().getType().toLowerCase().contains("link") ||
                    feeds.get(position).getCampaign().getParticipation().getType().toLowerCase().contains("youtube")) {

                holder.mPlayIcon.setVisibility(View.GONE);
                String slug = feeds.get(position).getCampaign().getSlug();
                List<String> images = mPreviewLinkMapper.get(slug).getImages();
                Utils.LoadImages(context, images.get(0), holder.mBannerImage, false);

            } else {
                holder.mPlayIcon.setVisibility(View.GONE);
                holder.mBannerImage.setVisibility(View.VISIBLE);
                String url = feeds.get(position).getCampaign().getParticipation().getPost_file();
                Utils.LoadImages(context, url, holder.mBannerImage, false);
            }
        }

        if (holder.mBrandLogo != null) {
            Utils.LoadImages(context, feeds.get(position).getInfluencer().getProfile_picture_url(), holder.mBrandLogo, true);
        }

        holder.mTitle.setText(feeds.get(position).getInfluencer().getName());
        holder.mSubTitle.setText(feeds.get(position).getCampaign().getName());
        holder.mTime.setText(feeds.get(position).getCampaign().getTimestamp());
        holder.mDescription.setText(feeds.get(position).getCampaign().getParticipation().getPost_content());
        holder.mEngagement.setText(feeds.get(position).getCampaign().getParticipation().getMetrics().getEngagements());
        holder.mImpresion.setText(feeds.get(position).getCampaign().getParticipation().getMetrics().getImpressions());
    }

    }

    public static class DashboardViewHolder extends RecyclerView.ViewHolder {

        ImageView mBannerImage, mFacebook, mTwitter, mInstagram, mPlayIcon, mHotIcon, mLocationIcon;
        CircularImageView mBrandLogo;
        CustomTextViewRegular mDescription, mTime, mOption1, mOption2, mOption3;
        CustomTextViewDemi mTitle, mSubTitle, mImpresion, mEngagement;
        LinearLayout mDetailsLayout;

        LinearLayout mOptionLayout1, mOptionLayout2, mOptionLayout3;
        public ViewGroup dropPreview;

        TableRow mTableOptions;

        public DashboardViewHolder(View v, int viewtype) {
            super(v);
            InitFeedViews(v);
          }

        private void InitFeedViews(View v) {
            mTitle = (CustomTextViewDemi) v.findViewById(R.id.adapterHeaderLayoutTitle);
            mSubTitle = (CustomTextViewDemi) v.findViewById(R.id.adapterHeaderLayoutSubTitle);
            mBrandLogo = (CircularImageView) v.findViewById(R.id.adapterHeaderLayoutLogo);
            mTime = (CustomTextViewRegular) v.findViewById(R.id.adapterHeaderLayoutTime);

            mBannerImage = (ImageView) v.findViewById(R.id.adapterFeedBannerImage);
            mPlayIcon = (ImageView) v.findViewById(R.id.adapterFeedPlayIocn);

            mImpresion = (CustomTextViewDemi) v.findViewById(R.id.adapterFeedImpressions);
            mEngagement = (CustomTextViewDemi) v.findViewById(R.id.adapterFeedEngagements);
            mDescription = (CustomTextViewRegular) v.findViewById(R.id.adapterFeedDescription);

            dropPreview = (LinearLayout) v.findViewById(R.id.drop_preview);
        }

    }

}

A: You would face "out of memory" issues lot in case of picasso library I would suggest you to use Glide library.
I had lot "out of memory" exception tried all but at last when i used glide it worked well.

A: Try to resize the image with Picasso library. OutOfMemoryException will be resolved.
For better understanding, refer below link:
https://futurestud.io/tutorials/picasso-image-resizing-scaling-and-fit


text:
Q: Discord.py ctx.guild.edit works but not self.bot.guild.edit? Like the title says,
I'm trying to do guild edits but on an events.
Here's part of my code:
    @commands.guild_only()
    async def on_ready(self):
    server = self.bot.get_guild("serverid")
        while True:
            await self.bot.guild.edit(guild=server, name="foo")
            await asyncio.sleep(1)
            await self.bot.guild.edit(guild=server, name="bar")
            await asyncio.sleep(1)

I've already tested it with a standalone command, so I know that ctx.guild.edit works but I'm not sure how to get it to work in an event.

A: You should call edit directly from the Guild object server
async def on_ready(self):
server = self.bot.get_guild(SERVER_ID)
while server is not None:
    await server.edit(name="foo")
    await asyncio.sleep(1)
    await server.edit(name="bar")
    await asyncio.sleep(1)

Also, make sure that you're passing the id of the guild as an int and not a string, and the guild_only decorator should only be used on commands.


text:
Q: Java - Return two dimensional array value I want to return all values of 2D array. How I can return it if I use get method with String type?
public class Data {
private final String[][] table;
public Data(){
    table = new String[][] {{"ID", "NAME"},
                         {"101", "A"},
                         {"102", "B"},
                         {"103", "C"},
                         {"104", "D"},
                         {"105", "E"}};
}

public String[][] get(){
    for (int i = 0; i < table.length; i++) {
        for (int j = 0; j < table[i].length; j++) {
            table[i][j] = table[i][j];
        }
    }
    return table;
}

public void displayMessage(){
    System.out.println(get());
}

}


text:
Q: strange dataclass decorator behaviour with fields I recently ran into strange behavior related to dataclasses in python. When using fields with default_factory, repeated call of the decorator results in an error.
As for me, this looks like a bug, because the field does not work out as a full-fledged default value. Accordingly, I would like to ask a question. what is the reason for this behavior of dataclasses?
source:
@dataclass
class A:
    a: int = 5
    b: int = 6

B = dataclass(A)
print(B == A)

output:
True

on the other hand
@dataclass
class A:
    a: int = 5
    b: List = field(default_factory=lambda: [1, 2, 3])

B = dataclass(A)
print(B == A)

output:
TypeError: non-default argument 'b' follows default argument

and finally if you change order of a and b in last snippet you'll obtain True in the output.

A: The error message:
TypeError: non-default argument 'b' follows default argument

is pretty clear, you can't put a fields without defaults following fields with them. Specifying a default_factory for a field is not the same as giving it a default value.
Luckily in this particular case there's an easy workaround, just define a default_factory for the a field too, so b no longer follows one with a default argument. I certainly don't understand all the details of the current dataclass implementation, so can't really say whether it's a bug or not — the comments in the code basically just echo what the error says.
That said, generally speaking default argument values shouldn't be mutable objects, and that's the primary use-case for using default_factory functions, so it's fairly obvious that initializing mutable fields types would need to be handled in a different manner than those with immutable ones, don't you think?
from dataclasses import dataclass, field
from typing import List

@dataclass
class A:
    a: int = field(default_factory=lambda: 5)
    b: List = field(default_factory=lambda: [1, 2, 3])

B = dataclass(A)
print(B == A)  # -> True

A: I was fooling around with this for a while, and came up with a pretty striaghtforward solution that looks like can work. As mentioned, this is no bug with dataclasses, because there's nothing that says it needs to support decorating the same class twice. Therefore I'm not entirely sure about what the issue is, however if for whatever reason we need to ensure a dataclass can support being decorated with the @dataclass decorator again, we need to ensure we unset all other values for a field that has a default_factory - other than the default_factory itself.
The below example demonstrates this pretty clearly:
from dataclasses import dataclass, field, fields, MISSING
from typing import List

@dataclass
class A:
    a: int = 5
    b: List = field(default_factory=lambda: [1, 2, 3])

print('== A Fields')
for f in fields(A):
    print(f)
    if f.default_factory is not MISSING:
        setattr(A, f.name, field(default_factory=f.default_factory))

B = dataclass(A)
print(B == A)
print()

print('== B Fields')
for f in fields(B):
    print(f)

Of course in your code, you can encapsulate the logic under print('== A Fields') into a helper function, and change A instead to a generic cls argument that gets passed in to a function. This would allow you to modify any dataclass fields that are set with a default_factory, so that no error is raised when the data class is re-decorated again.


text:
Q: Single Signin With AAD and B2C We're trying to implement a single sign in using both AAD and B2C. The web app needs to allow internal and external people to login in. I'm able to implement each method individually, but is it possible to determine the login method based upon email addr. If they're an external person, I would authenticate with B2C. If internal, AAD.
Any suggestions or is this even possible,

A: For OIDC, "domain_hint" would work.
"The domain hint can be used to skip directly to the sign-in page of the specified identity provider, instead of having the user make a selection among the list of available identity providers".
Update
The usual way to do this would be to authenticate with B2C and then add a login button to AAD i.e. federation.


text:
Q: How to locate UI Button for AppleScript using Accessibility Inspector There are several articles here that address this question, but none offer the help to connect-the-dots.
The attached screen shot shot shows Accessibility Inspector for the button in question, which answers to 'process java'. It also shows the properties of the window (bottom) and 2 code strings to have AppleScript press the continue button. These are:
if exists (button "Continue" of window 1) then
    click button "Continue" of window
else if exists (button "continue" of window 1) then
    click button "continue" of window 1

I am almost certain 'tab' and 'space bar' might work for this. But, can it be done through the window? If so, how?
EDIT: Tried to get info about the buttons with:
 get every button of window 1 of process "java"
    --> {button 1 of window "Security Warning" of application process "java",
         button 2 of window "Security Warning" of application process "java",
         button 3 of window "Security Warning" of application process "java"}

It appears the buttons are 'close, zoom & minimize'. (upper left 3 dots)

A: To get information about UI elements in Accessibility Inspector, you just need to hover the mouse over whichever UI element you want to know more about. For the purposes of closing this security warning, you need to be able to identify which button and which window. So if you hover the mouse over the title bar of the window you can see the AXValue is "Security Warning". And if you hover over the Continue button you can see the AXTitle value is "Continue".
From this you can create the following AppleScript which will close this dialog...
tell application "System Events" to tell process "java"
    click button "Continue" of window "Security Warning"
end tell

Also you can get AppleScript to tell you the actual names of the buttons in the window with. Please note that it will list the three standard Close, Minimise, Maximise traffic light buttons in the top left corner as well.
tell application "System Events" to tell process "java"
    get name of every button of window "Security Warning"
end tell

Hope that helps.


text:
Q: "Strip Debug Symbols During Copy" and "Strip Linked Product" I read a lot of thing and discovery this configs have 2 side effect:

*

*Make the binary size smaller

*The program show a better debug crash

I am building program for iOS, so I want my binary to be the smallest possible. This mean:

*

*If I set YES to both config, my binary will be the smaller

*If I set NO, I will get better debug crash

So I have to set YES for AppStore version and NO for Debug?

A: A dSYM file is nothing a "debug symbols file". It is generated when the "Strip Debug Symbols" setting is enabled in the build settings of your project.
The default debug info format for the Debug configuration for new iOS projects is "DWARF with dSYM file", but for new OS X projects is just "DWARF".
If you're running under the debugger, of course, it will just stop at the point of the crash, so you don't need to symbolicate a crash report.So set 'DWARF' when application is in development and set 'DWARF with dSYM' at the time of release.
You should apply this settings as well:

A: You are correct, set it to YES for AppStore build and NO for debugging builds. Even when you build you AppStore version, there is dsym file containing all symbols you need to symbolicate your crash logs.


text:
Q: If else in Jquery i am a noob to jquery and i want to know how to make use of if else for the following:
on the server side there is a  if for number of rows is equal to 0 and else some JSON part.
$age= mysql_query("SELECT title FROM parent WHERE id ='$name'");
$age_num_rows = mysql_num_rows($age);
  if ($age_num_rows==0)
  {
   echo "true";
  }
  else
  {
$sql ="SELECT * FROM parentid WHERE id = '$name'"; //$name is value from html
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
     {
$abc_output = array('title' => $row['title'],'age' => $row['age']);
     }
echo json_encode($abc_output);
  }

Now coming to Jquery part :
If the above PHP code go to if part then i want to display an alert box or if it goes to else part it needs to insert some values into the forms.
Here is something i tried but it did not work.
   $(document).ready(function(){
      $("#button1").click(function(){
        $.getJSON('script_1.php',function(data){
            if (data=='true') {
                 alert ('hello')
            }
            else {
                $.post('script_1.php',
                    { id: $('input[name="id"]', '#myForm').val() },
                    function(json) {
                        $("input[name='title']").val(json.title);
                        $("input[name='age']").val(json.age);
                    },
                    "json");
            }
      });
  });

Edited:
  $(document).ready(function(){
$("#button1").click(function(){
    $.post(
        'script.php',
        { id: $('input[name="id"]', '#myForm').val() },
        function(json) {
            var data = JSON.parse(json);
            if (data.length === 0){
             alert('no data');
            }
            else{
            $("input[name='title']").val(json.title);
                    $("input[name='age']").val(json.age);

            }},
        "json"
    );
});
});

PHP side
$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if ($row) {
$row=  array('title' => $row['title'],'age' => $row['age']);
echo json_encode($row);
} else {
echo json_encode(array());
}

A: You need to parse the JSON before you can use it like that. Modern browsers will have built in support for JSON.parse(yourJSON), but to account for those that don't, you should use Douglas Crockford's JavaScript JSON library. Including it will provide JSON.parse() if the browser doesn't have it already.
For the if-else stuff you're doing in the PHP, the common practice is to echo out an empty JSON object or array, so you don't have to test for things like no rows on the server side. You could do something as simple as this, later accounting for your database column names:
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row) {
  echo json_encode($row);
} else {
  echo json_encode(array());
}

Back in the JavaScript, you could then do something like this:
var data = JSON.parse(json);
if (data.length === 0) {
  alert('no data');
} else {
  $("input[name='title']").val(data.title);
  $("input[name='age']").val(data.age);
}

jeroen is right though, you only need to use one AJAX call.

A: There seem to be a few problems:

*

*You are treating the data returned from getJSON as if it is plain
text

*The php that you are calling from javascript does not always
return json

*You are doing 2 ajax requests; getJSON and post where you only need one: The first call to getJSON without any data will never reach the else condition

By the way, where does $name come from in your php script? For your second ajax call to work, it needs to be something like mysql_real_escape_string($_POST['id']) or (int) $_POST['id'] if it is an integer.
Edit: I think it would be easiest to get rid of the .post and just use the first ajax call. So you will need to change:
$.getJSON('script_1.php',function(data){

to something like:
$.getJSON('script_1.php?id=' + $('input[name="id"]').val(), function(data) {

and in your php you need to use something like:
$name = mysql_real_escape_string($_GET['id']);


text:
Q: Uninstalling django-tinymce. Import error when makemigrations Thanks for taking the time to read this.
I was not happy with TinyMCE extension in django and decided to switch to django-summernote. I first ran
pip uninstall django-tinymce

Removed all mentions of tinymce in the actual project.
Followed the instruction to install django-summernote. Upon completion I decided to run
python manage.py makemigrations
python manage.py migrate

to apply new extension, but get an error:
File "/Users/rasulkireev/Sites/dj-pw/now/migrations/0006_auto_20190703_0134.py", line 4, in <module>
    import tinymce.models
ModuleNotFoundError: No module named 'tinymce'

I'm not sure why would Django care about what I did previously since I am simply asking to replace the editor. I can't run python manage.py runserver either.
I can't do anything before fixing this. I beg you guys, please help.
Note: I would ideally want to keep the contents of my current database.
Thanks for taking the time to read this.

A: Once you have removed all the mentions of tinymce from the models, admins and other files, you need to migrate using a special "flag":
python manage.py makemigrations
python manage.py migrate --fake-initial

I am not to clear on the backend of this method, but it works. You can read more about it the official Django website:
https://docs.djangoproject.com/en/2.2/topics/migrations/

This will make a new initial migration for your app. Now, run python
  manage.py migrate --fake-initial, and Django will detect that you have
  an initial migration and that the tables it wants to create already
  exist, and will mark the migration as already applied. (Without the
  migrate --fake-initial flag, the command would error out because the
  tables it wants to create already exist.)
Note that this only works given two things:

*

*You have not changed your models since you made their tables. For
  migrations to work, you must make the initial migration first and
  then make changes, as Django compares changes against migration files, not the database.

*You have not manually edited your database - Django won't be able to detect that your database doesn't match your models, you'll just get errors when migrations try to modify those tables.


text:
Q: Notification on the bottom of the screen After upgrading to the newest version of ios-app I see strange notification on the bottom of the "select active application" screen.

What is this?
Text "Доброе утро!" means "Good morning!" in Russian.

*

*App Version: 1.6.0.10

*Device: iPad Air 2 (Wi-Fi)

*OS Version: Version 10.0.2 (Build 14A456)

A: Apple shows that notification when you use an app in a specific location often. For example, when I arrive at work, suddenly the Stack Exchange app pops up on the bottom of the screen. When I come home, it shows WhatsApp. That's a feature.
I guess the SE developer who wrote this (Brian Nickel I guess), thought it was funny to greet you while you see this notification.


text:
Q: How do I get a user's facebook username (and other user info) when logged Firebase? I am building an iOS app in Xcode. I log users in with Facebook via Firebase and each new user is created within the firebase realtime database accordingly. When signing in, users give me access to their public profile information. How can I access this information and add it to the list of properties stored within each user in the database?
Eg, when a user logs in, a new user is created in the database (already working) with their facebook username (eg facebook.com/xxxx), full name, email etc all stored as separate values within the user (no idea how to do this even after reading the docs).
Any help would be greatly appreciated!

A: You should be able to get basic profile info including profile URL from AdditionalUserInfo on sign-in success.

A: You should look at Facebook developer help on the subject.
This is how you can connect multiple apps together:
https://developers.facebook.com/docs/facebook-login/connecting-accounts


text:
Q: SQL 2000 (MSDE) Hangs When It Receives an Erroneous Query from a Classic ASP Web Application I have a SQL interface page in my classic ASP web app that allows admin users to run queries against the app's database (MSDE 2000) - it simply consists of a textarea that the user submits and the app returns the resulting list of records as below
Dim oRS
Set oRS = Server.CreateObject("ADODB.Recordset")
oRS.ActiveConnection = sConnectionString

// run the query - this is for the admin only so doesnt check for sql safe commands etc.
oRS.Open Request.Form("txtSQL")

If Not oRS.EOF Then
    // list the field names from the recordset
    For i = 0 to oRS.Fields.Count - 1
        Response.Write oRS.Fields(i).name & " "
    Next
    // show the data for each record in the recordset
    While Not oRS.EOF
        For i = 0 to oRS.Fields.Count - 1
       Response.Write oRS.Fields(i).value & " "
        Next
        Response.Write "<br />"
        oRS.Movenext()
    Wend
End If

The problem with this is that if you send it an invalid query (with a spelling mistake, invalid join etc.) instead of throwing back an error immediately, it hangs IIS (you can see this by trying to browse the app from another computer, it fails) for a number of minutes and THEN returns the error. I have NO idea why! Can anyone help?

A: Well, working at MS support I had a similar request once. Not saying it is you doing the same, but sou ask for stories like that, and this may shed some light.
I got a call promoted from an external support center running in india that did ASP support (and he made enough pressure it got promoted to processional support services SQL Server level 3 - the "last line of defence"). On a website, SQL Server would stop responding hitting a specific SQL Query. The Server would just stop doing anything, actually even IIS was not properly usable anymore. I got a full case documented from a very entusiastic fellow that even managed to proove it was something wrong with SQL Server because the (C++ level) stack traces showed the OleDB driver hanging in the call to SQL Server. First time in my life someone showed me that level of stack trace for prooving SQL Server crashed.
Anyhow, some research turned out - the programmer that originally wrote the site and had still been fired by the customer trying to fix the mess should not have been using ASP but serving burgers instead. Customer had that one particular page making a lot of compelx SQL calls - and the database had NO INDEX AT ALL. Basically it would go into "tying to make a dozen table scans" on a very cheap disc system. After adding even SOME indices, the system became usable - and the customer went to along quest of checking the whole complex database. The support person was obvsiouly a litle ashamed for not having checked what SQL Server was actually DOING (which would have resulted in awkward execution pland an stalled IO immediately).
And here the story comes back to you ;)
You say with a bad query, IIS stalls for minutes.
Can you validate that:
* This happens on IIS? Being making an example, and chcking in IIS and in Enterprise Manager? If it also hangs in Enterprise Manager - it it not IIS.
* It hangs IIS as in the app. Does the rest of IIS / other apps / static pages still work?
* The code does happen in a page, and not in a central element / event handler / synchronized connection so taht one hanging access hangs the whole app?
* What is IIS processor load and SQL Server load doing during that event?
* SQL Server does not happen to be on the same computer? (so it overloads the computer and thus also hits IIS)?
I can not really imagine this behavior without some issues in the IIS side.
Basicalle, give us a little more context and we should find it ;) Meanwhile, enjoy my story.


text:
Q: I want to upload form data with images from Angular to Node.js using http post request? html: in these template, I am asking for product information and image and store it.

      <input type="hidden" formControlName="_id">

      <input type="file" formControlName="ProductImage" #ProductImage>

      <mat-form-field>
        <input formControlName="productName" matInput placeholder="Product Name" #productName>
        <mat-hint align="end">{{ productName.value.length }}/50</mat-hint>

        <mat-error *ngIf="productForm.get('productName').hasError('required') && productForm.get('productName').touched; else patternproductName;">This is required</mat-error>
        <ng-template #patternproductName>
          <mat-error *ngIf="productForm.get('productName').hasError('pattern'); else lengthproductName;">Invalid characters</mat-error>
        </ng-template>
        <ng-template #lengthproductName>
          <mat-error *ngIf="productForm.get('productName').hasError('minlength') || productForm.get('productName').hasError('maxlength');">Must be 1-50 characters</mat-error>
        </ng-template>
      </mat-form-field>

      <mat-form-field>
        <mat-select formControlName="supplierId" matInput placeholder="Supplier" #supplierId>
          <mat-option *ngFor="let a of supplierArray" value="{{ a._id }}">{{ a.supplierName }}</mat-option>
        </mat-select>

        <mat-error *ngIf="productForm.get('supplierId').hasError('required') && productForm.get('supplierId').touched; else patternsupplierId;">This is required</mat-error>
        <ng-template #patternsupplierId>
          <mat-error *ngIf="productForm.get('supplierId').hasError('pattern'); else lengthsupplierId;">Invalid characters</mat-error>
        </ng-template>
        <ng-template #lengthsupplierId>
          <mat-error *ngIf="productForm.get('supplierId').hasError('minlength') || productForm.get('supplierId').hasError('maxlength');">Must be 1-24 characters</mat-error>
        </ng-template>
      </mat-form-field>

      <mat-form-field>
        <mat-select formControlName="brandId" matInput placeholder="Brand" #brandId>
          <mat-option *ngFor="let a of brandArray" value="{{ a._id }}">{{ a.brandName }}</mat-option>
        </mat-select>
        <mat-error *ngIf="productForm.get('brandId').hasError('required') && productForm.get('brandId').touched; else patternbrandId;">This is required</mat-error>
        <ng-template #patternbrandId>
          <mat-error *ngIf="productForm.get('brandId').hasError('pattern'); else lengthbrandId;">Invalid characters</mat-error>
        </ng-template>
        <ng-template #lengthbrandId>
          <mat-error *ngIf="productForm.get('brandId').hasError('minlength') || productForm.get('brandId').hasError('maxlength');">Must be 1-24 characters</mat-error>
        </ng-template>
      </mat-form-field>

      <mat-form-field>
        <mat-select formControlName="categoryId" matInput placeholder="Category" #categoryId>
          <mat-option *ngFor="let a of categoryArray" value="{{ a._id }}">{{ a.categoryName }}</mat-option>
        </mat-select>
        <mat-error *ngIf="productForm.get('categoryId').hasError('required') && productForm.get('categoryId').touched; else patterncategoryId;">This is required</mat-error>
        <ng-template #patterncategoryId>
          <mat-error *ngIf="productForm.get('categoryId').hasError('pattern'); else lengthcategoryId;">Invalid characters</mat-error>
        </ng-template>
        <ng-template #lengthcategoryId>
          <mat-error *ngIf="productForm.get('categoryId').hasError('minlength') || productForm.get('categoryId').hasError('maxlength');">Must be 1-20 characters</mat-error>
        </ng-template>
      </mat-form-field>

      <mat-form-field>
        <input formControlName="productPrice" matInput placeholder="Price" #productPrice>
        <mat-hint align="end">{{ productPrice.value.length }}/5</mat-hint>

        <mat-error *ngIf="productForm.get('productPrice').hasError('required') && productForm.get('productPrice').touched; else patternproductPrice;">This is required</mat-error>
        <ng-template #patternproductPrice>
          <mat-error *ngIf="productForm.get('productPrice').hasError('pattern'); else lengthproductPrice;">Invalid characters</mat-error>
        </ng-template>
        <ng-template #lengthproductPrice>
          <mat-error *ngIf="productForm.get('productPrice').hasError('min') || productForm.get('productPrice').hasError('max');">Must be between 1-99999</mat-error>
        </ng-template>
      </mat-form-field>

      <mat-form-field>
        <input formControlName="productQuantity" matInput placeholder="Quantity" #productQuantity>
        <mat-hint align="end">{{ productQuantity.value.length }}/5</mat-hint>

        <mat-error *ngIf="productForm.get('productQuantity').hasError('required') && productForm.get('productQuantity').touched; else patternproductQuantity;">This is required</mat-error>
        <ng-template #patternproductQuantity>
          <mat-error *ngIf="productForm.get('productQuantity').hasError('pattern'); else lengthproductQuantity;">Invalid characters</mat-error>
        </ng-template>
        <ng-template #lengthproductQuantity>
          <mat-error *ngIf="productForm.get('productQuantity').hasError('min') || productForm.get('productQuantity').hasError('max');">Must be between 1-99999</mat-error>
        </ng-template>
      </mat-form-field>

      <mat-form-field>
        <input formControlName="productMin" matInput placeholder="Minimum" #productMin>
        <mat-hint align="end">{{ productMin.value.length }}/5</mat-hint>

        <mat-error *ngIf="productForm.get('productMin').hasError('required') && productForm.get('productMin').touched; else patternproductMin;">This is required</mat-error>
        <ng-template #patternproductMin>
          <mat-error *ngIf="productForm.get('productMin').hasError('pattern'); else lengthproductMin;">Invalid characters</mat-error>
        </ng-template>
        <ng-template #lengthproductMin>
          <mat-error *ngIf="productForm.get('productMin').hasError('min') || productForm.get('productMin').hasError('max');">Must be between 0-99999</mat-error>
        </ng-template>
      </mat-form-field>

      <button mat-raised-button class="pull-right" [mat-dialog-close]="true">Cancel</button>
      <button type="submit" mat-raised-button color="primary" class="pull-right" *ngIf="!formSelector" [disabled]="!productForm.valid" (click)="openSnackBar(productNotification)">Create</button>
      <button type="submit" mat-raised-button color="primary" class="pull-right" *ngIf="formSelector" [disabled]="!productForm.valid" (click)="openSnackBar(productNotification)">Update</button>

    </form>
  </ng-template>

this is the typescript file that executes when the user completes the form and click the submit button. I want to get the image as wend and join it to the the productSchema and send it to node server by the use of the service
.ts:
productSubmit(form){
        const Image = this.Product_Image.nativeElement;
        if(Image.files && Image.files[0]){
          this.ProductImageFile = Image.files[0];
        }
        const ImageFile: File = this.ProductImageFile;

        let productSchema: productSchema = {
          '_id': form.value._id,
          'productImage': ImageFile,
          'productName': form.value.productName,
          'supplierId': form.value.supplierId,
          'brandId': form.value.brandId,
          'categoryId': form.value.categoryId,
          'productPrice': form.value.productPrice,
          'productQuantity': form.value.productQuantity,
          'productMin': form.value.productMin
        };
        console.log(productSchema);
        if(!this.formSelector){ //create method
          this.productService.productCreate(productSchema).subscribe(result =>{
            this.notif = "created";
            this.productForm.reset();
            this.productSelect();
          });
        }
      }

schema: This is the schema that I want to implement in all of the fields
const mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
const productSchema = mongoose.Schema({
    ProductImage: {
        type: String,
        required: true
    },
    productName: {
        type: String,
        required: true,
        minlength: 1,
        maxlength: 50
    },
    supplierId: {
        type: ObjectId,
        required: true,
        minlength: 24,
        maxlength: 24
    },
    brandId: {
        type: ObjectId,
        required: true,
        minlength: 24,
        maxlength: 24
    },
    categoryId: {
        type: ObjectId,
        required: true,
        minlength: 24,
        maxlength: 24
    },
    productPrice: {
        type: Number,
        required: true,
        minlength: 1,
        maxlength: 5
    },
    productQuantity: {
        type: Number,
        required: true,
        minlength: 1,
        maxlength: 5
    },
    productMin: {
        type: Number,
        required: true,
        minlength: 1,
        maxlength: 5
    },
    productExist: {
        type: Boolean,
        required: true,
        default: true
    },
    productTimeStamp: {
        type: Date,
        required: true,
        default: Date.now
    }

});

module.exports = mongoose.model('productSchema', productSchema);

this is the service that send the formdata to nodejs
service:
  productCreate(val){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/api/productCreate', val, { headers: headers }).pipe(map(res => res.json()));
  }

node.js
    var store = multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, './uploads');
        },
        filename: (re, file, cb) => {
            cb(null, Date.now() + '.' + file.originalname);
            console.log(file);
        }
    });

    //start saving picture
    var upload = multer({storage: store}).single('file');
    router.post('/upload', (req, res, next) => {
        upload(req, res, (err) => {
            if(err) return res.status(501).json({ error: err });
            return res.json({ originalname: req.file.originalname, uploadname: req.file.filename });
        });
    });
    //end saving picture

    router.post('/productCreate', upload, (req, res, next) =>{
        console.log(req);
        let newproductSchema = new productSchema({
            productImage: req.file,
            productName: req.body.productName,
            supplierId: req.body.supplierId,
            brandId: req.body.brandId,
            categoryId: req.body.categoryId,
            productPrice: req.body.productPrice,
            productQuantity: req.body.productQuantity,
            productMax: req.body.productMax,
            productMin: req.body.productMin
        });
        console.log(newproductSchema);
        newproductSchema.save((err, newproductSchema) =>{
            if(err) res.json(err);
            else res.json({msg: 'Item added successful'});
        });
    });

I want to create a system that save product information and image as well to mongodb. i want to store the path of the image in database. I am confused on how to send file from angular to node. Can you help me fix these? Thank you.
    I want to upload form data with one image. but i cant do it. How can I fix these?

A: You could get the image into a canvas and then retrieve the blob or dataUrl from the canvas, attach that as a property to your get/post request to the server whatever you are using and store the image directly in MongoDB as a blob of bytes or a base64 encoded string. To retrieve it all you have to do is set the src of the image to the dataUrl stored in MonoDB.
Example:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL


text:
Q: Concept for a button that should be able to press longer then 30 sec Is there an opportunity to implement an element that is able to get pressed longer then 30 sec until the MotionEvent Action_up timeout gets automatically fired?
Maybe an other concept of doing that job?
At the moment i have changed the image of an ImageButton by using the onTouchListener and the action_up and action_down define. But this concept is getting ruined by the auto action_up from android.
Edit:
The problem could be caused by samsungs android mod. It occurs on the Galaxy Tab2 7.0 Wifionly edition but not on the HTC Sensation XE. Does anyone got an Galaxy Tab2 to cross check this behavior?

A: Try this code for your solution i suppose this will help you.
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_CALL) {
        // a long press of the call key.
        // do our work, returning true to consume it.  by
        // returning true, the framework knows an action has
        // been performed on the long press, so will set the
        // canceled flag for the following up event.
        return true;
    }
    return super.onKeyLongPress(keyCode, event);
}

The following Link will lead you to the correct result with other uses of Hard Keys.The link is as follows:-Imp Link

A: I tested this issue on other samsung tablets. The result is that there is no problem at all. Just the Tablet i am using Samsung Galaxy Tab 2 WiFi 7.0 (P3110) got that issue.


text:
Q: Combine column values into a list of unique values without nan in a new column I want to combine multiple columns of a Pandas DataFrame into a single column of lists, such that each list does not contain duplicate values and does not contain null values.
So, for example, in the data frame below, columns A, B and C are combined into column D:
                  A              B                 C                                 D
0             "KFC"            NaN             "KFC"                           ["KFC"]
1               NaN   "Mandai Zoo"   "Singapore Zoo"   ["Mandai Zoo", "Singapore Zoo"]
2   "Tampines Mall"            NaN               NaN                 ["Tampines Mall"]

The best I could come up of this was a combination of this and this:
df['D'] = df[['A', 'B', 'C']].values.tolist()
df['D'] = df['D'].map(set).tolist()

which would give me this:
                  A              B                 C                                      D
0             "KFC"            NaN             "KFC"                           ["KFC", NaN]
1               NaN   "Mandai Zoo"   "Singapore Zoo"   [NaN, "Mandai Zoo", "Singapore Zoo"]
2   "Tampines Mall"            NaN               NaN                 ["Tampines Mall", NaN]

But that still leaves the NaN values in the list.

A: You could use pd.dropna before using pd.Series.unique along axis=1
df['D'] = df.apply(lambda row: row.dropna().unique(), axis=1)
print(df)

               A           B              C                            D
0            KFC         NaN            KFC                        [KFC]
1            NaN  Mandai Zoo  Singapore Zoo  [Mandai Zoo, Singapore Zoo]
2  Tampines Mall         NaN            NaN              [Tampines Mall]

A: Because two NaN values are not equal you can use [x for x in my_list if x==x] to remove NaN values:
df = pd.DataFrame({'A': ["KFC", np.nan, "Tampines Mall"], 'B': [np.nan, "Mandai Zoo", np.nan], 'C': ["KFC", "Singapore Zoo", np.nan]}).

df.assign(D = lambda df: [[z for z in x if z==z] for x in  [set(l) for l in df.values.tolist()]])

Result:
               A           B              C                           D

0            KFC         NaN            KFC                        [KFC]
1            NaN  Mandai Zoo  Singapore Zoo  [Mandai Zoo, Singapore Zoo]
2  Tampines Mall         NaN            NaN              [Tampines Mall]

A: Use:
df[['Name', 'Year', 'Date']].apply(lambda x: [y for y in set(x) if pd.notna(y)], axis=1)

This just holds values if they are not nans.


text:
Q: Python - Parsing Nested Json I have json file i am trying to parse out and get just two values out. 'timestamps' and 'values'.
Here is the sample of my json file:
    {'totalCount': 1,
 'nextPageKey': None,
 'result': [{'metricId': 'builtin:synthetic.browser.event.visuallyComplete.load',
   'data': [{'dimensions': ['SYNTHETIC_TEST_STEP-123456'],
     'dimensionMap': {'dt.entity.synthetic_test_step': 'SYNTHETIC_TEST_STEP-123456'},
     'timestamps': [
      1596326400000,
      1616976000000,
      1617062400000,
      1617148800000,
      1617235200000],
     'values': [
      3880.834490740741,
      3879.6458333333335,
      3826.3645833333335,
      3890.871527777778,
      3876.8199643493763]}]}]}

I tried using approach with pandas:
    import pandas as pd
    pdp = pd.json_normalize(PDPjson['result'],['data'])

so I can get it into data frame but I am getting column with list of dates and column with list of values.

What I am trying to get is just a dataframe with two columns, Timestamp and Values.
How do I do this from here?

A: You can apply Series.explode on the timestamps and values:
pdp = pdp[['timestamps', 'values']].apply(pd.Series.explode).reset_index(drop=True)

#       timestamps       values
# 0  1596326400000  3880.834491
# 1  1616976000000  3879.645833
# 2  1617062400000  3826.364583
# 3  1617148800000  3890.871528
# 4  1617235200000  3876.819964

A: I created your JSON object as follows:
txt = '''\
{ "totalCount": 1,
  "nextPageKey": "None",
  "result": [{"metricId": "builtin:synthetic.browser.event.visuallyComplete.load",
    "data": [{"dimensions": ["SYNTHETIC_TEST_STEP-123456"],
      "dimensionMap": {"dt.entity.synthetic_test_step": "SYNTHETIC_TEST_STEP-123456"},
      "timestamps": [ 1596326400000, 1616976000000, 1617062400000,
        1617148800000, 1617235200000],
      "values": [ 3880.834490740741, 3879.6458333333335, 3826.3645833333335,
        3890.871527777778, 3876.8199643493763]}]}]}'''
PDPjson = json.loads(txt)

Then I started from json_normalize just as you did:
pdp = pd.json_normalize(PDPjson['result'], 'data')

The missing step is:
result = pdp[['timestamps', 'values']].apply(lambda col: col.explode())\
    .reset_index(drop=True)

The result is:
      timestamps   values
0  1596326400000  3880.83
1  1616976000000  3879.65
2  1617062400000  3826.36
3  1617148800000  3890.87
4  1617235200000  3876.82

Don't worry about smaller precision of values column, it is only
the way how Jupyter Notebook presents the data.
When you run e.g. result.iloc[0,1] you will get:
3880.834490740741

with full precision.


text:
Q: Why performance and speed of my tensorflow matrix factorization code is slower than numpy code? I am unfamiliar tensorflow.
I am trying to replace matrix factorization numpy code with tensorflow. But not only the model performance but also the speed is worse than numpy. What's wrong with my code?
Tensorflow code : https://github.com/choco9966/Research/blob/master/Matrix%20Factorization/%5BTensorflow%5D%20MatrixFactorization.ipynb
Based numpy code : https://github.com/choco9966/Research/blob/master/Matrix%20Factorization/%5BNumpy%5D%20MatrixFactorization.ipynb


text:
Q: How Can I Get Files And Folders Of A Special Website Like IDM Grabber In C# If you have worked with IDM(Internet Download Manager) this has a item named Grabber that searches in a special web site and get the files and folders of that website and you can download them using IDM.
I would like to do something similar in C#. I would like to download html web pages and extract links from those pages. I would also like to detect directories and attempt to search their contents - possibly parsing "Index Of" directory listing pages.
How would I go about doing this?

A: Use regex or use the HtmlAgilityPack (http://htmlagilitypack.codeplex.com/) to parse the website and find links to files. You may need to check the extension of the file. Ie. Only parse links that end in .zip|.exe|.msi|.rar|.png|.pdf|.gif|.jpg|.jpeg.

A: I once wrote a "Web Spider" to do this and published the source code over at Code Project.
If you want to do it as an end-user, I found out the the free Httrack Website Copier works pretty well.


text:
Q: Entity FrameWork System.ArgumentOutOfRangeException my project use ef and reposiroty for communication with database
when i find a record with the id
 var applicant = applicantProvider.Get(1020);

 Context.Set<TEntity>().Find(id);

then i got exception
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Year, Month, and Day parameters describe an un-representable DateTime.
the data record is :
id        DOB                 SubmitDate CreateDate UpdateDate
1020    01/06/1949  2010-05-12 16:01:39 2010-05-14 16:59:10 2011-05-28 10:22:00
i don't know how i got that error pls help me
My entity Applicant
public class ABGApplicant

public int ABGApplicantID { get; set; }
public DateTime? DOB { get; set; }
public DateTime? SubmitDate { get; set; }
public DateTime? CreateDate { get; set; }
public DateTime? UpdateDate{ get; set; }

this is my main function
IABGApplicantProvider applicantProvider = new ABGApplicantProvider(new GenesisContext());

            var applicant = applicantProvider.Get(1020);

this is my ABGApplicantProvider  extend repository
public class ABGApplicantProvider : Repository<ABGApplicant>, IABGApplicantProvider
    {
        public ABGApplicantProvider(DbContext context) : base(context)
        {
        }
    }

This is class Repository
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class

public TEntity Get(int id)
        {
            // Here we are working with a DbContext, not PlutoContext. So we don't have DbSets
            // such as Courses or Authors, and we need to use the generic Set() method to access them.
            return Context.Set<TEntity>().Find(id);
        }

A: I think your problem is not in your repository but in the data inside your DB...
Check the record with id=1020 and then check the column DOB


text:
Q: MPMusicPlayerController pause while in background and resume when app enters foreground I have implemented MPMusicPlayerController to play music from library. When app enters background, i pause it and when it comes back to foreground, i want it to resume. It pauses fine but begins from the start. Heres the code...
AppDelegate.m
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [self.appMusicPlayer pause];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [self.appMusicPlayer play];
}

MainViewController.m
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection
{
    [self dismissModalViewControllerAnimated: YES];
   appdelegate.selectedSongCollection=mediaItemCollection;
    appdelegate.appMusicPlayer = [MPMusicPlayerController applicationMusicPlayer];

    [appdelegate.appMusicPlayer setQueueWithItemCollection:appdelegate.selectedSongCollection];
    [appdelegate.appMusicPlayer play];
    [btnStop setHidden:NO];
    [btnMusic setHidden:YES];
}

- (void) mediaPickerDidCancel: (MPMediaPickerController *) mediaPicker
{
    [self dismissModalViewControllerAnimated: YES];
}

Any ideas on how to resume it when app enters foreground?

A: I would look into the track's currentPlaybackTime. MPMusicPlayerController has a currentPlaybackTime property. When the app is going to enter the background, simply save this value (as a property should work just fine), and in WillEnterForeground, use the same property's value to set the currentPlaybackTime when you resume.