text:
Q: is.character() does not correctly identify a data frame Has the behavior of is.character() changed in R 4.x ?
Here I read a simple tab-delimited text file into a data frame, and then confirm all columns are correctly marked as character data:
> raw <- read.table( creditDataPath, header = TRUE, colClasses="character", sep = "\t")
> str(raw)
'data.frame':   407 obs. of  18 variables:
 $ NAME          : chr  "Hope Gorman" "Sarah Coriano" "Ernest Farmer" "John Coleman" ...
 $ ADDRESS       : chr  "179 Del Mar Blvd." "640 Prospect Lane" "474 Green Street" "452 Green Street" ...
 $ ZIP           : chr  "99975" "99904" "99900" "99924" ...
 $ SSN           : chr  "470-17-7670" "355-91-5677" "129-21-0468" "121-57-2753" ...
 $ SEX           : chr  "F" "F" "M" "M" ...
 $ MARITALSTATUS : chr  "M" "M" "M" "M" ...
 $ CHILDREN      : chr  "2" "1" "0" "0" ...
 $ OCCUPATION    : chr  "Professional" "Unknown" "Unknown" "Unknown" ...
 $ HOMEOWNERSHIP : chr  "O" "O" "O" "O" ...
 $ INCOME        : chr  "3212" "3145" "3165" "3248" ...
 $ EXPENSES      : chr  "1124" "1100" "1266" "974" ...
 $ CHECKING      : chr  "N" "N" "N" "N" ...
 $ SAVINGS       : chr  "Y" "Y" "Y" "Y" ...
 $ MSTRCARD      : chr  "1" "1" "1" "1" ...
 $ VISA          : chr  "5" "5" "5" "5" ...
 $ AMEX          : chr  "0" "0" "0" "0" ...
 $ MERCHANT      : chr  "9" "9" "9" "9" ...
 $ PAYMENTHISTORY: chr  "2" "0" "2" "3" ...

However, is.character(raw) for the data frame and is.character(raw[3,1:17]) for a portion of a row in the data frame both return FALSE:
> is.character(raw)
[1] FALSE
> is.character(raw[3,1:17])
[1] FALSE
>

With R version 3.5.2 (the original development environment was 64-bit R 3.5.2 on 64-bit Win 7), simply reading the file into a data frame (WITHOUT needing to add colClasses = "character" simply worked. The use case is that basically an R wrapper uses is.character() to determine whether a row in the data frame contains all string values (in effect: is.character(raw[n,1:17])); that then determines which version of a C function in a legacy DLL to call - one that expects either ALL strings, or one that expects ALL doubles).
I have been away from R since 2019, so today on a computer running Win10 Pro I installed 64-bit R 4.2.1, loaded the original workspace, and expected everything to work. And, if I manually craft a record (vector) that explicitly has every value in double quotes (e.g., "Hope Gorman", ""99975", etc.) everything does work - the R wrapper calls the correct C function.
The problem is, loading the data frame from the simple flat ASCII text file and then accessing it row by row does not work, even though after loading R seems to think the data consists of values that are quoted strings. The error is the dreaded NAs introduced by coercion error - in the wrapper R appears to NOT recognize the character strings.
What am I missing? Is this a bug in 4.x ?
EDIT:
Here are the first 4 lines of the file (first line contains column labels; 18 total tab delimited fields - some of the string fields contain spaces, e.g. Hope Gorman is the value for the first Name field/column). This is a toy (ENTIRELY FAKED) data file for consumer credit analysis.
NAME    ADDRESS ZIP SSN SEX MARITALSTATUS   CHILDREN    OCCUPATION  HOMEOWNERSHIP   INCOME  EXPENSES    CHECKING    SAVINGS MSTRCARD    VISA    AMEX    MERCHANT    PAYMENTHISTORY
Hope Gorman 179 Del Mar Blvd.   99975   470-17-7670 F   M   2   Professional    O   3212    1124    N   Y   1   5   0   9   2
Sarah Coriano   640 Prospect Lane   99904   355-91-5677 F   M   1   Unknown O   3145    1100    N   Y   1   5   0   9   0
Ernest Farmer   474 Green Street    99900   129-21-0468 M   M   0   Unknown O   3165    1266    N   Y   1   5   0   9   2

Also FWIW, I have checked everything on the original development machine (same file, same R workspace but R 3.5.2 running on Win7), and the R wrapper calls the correct C code as expected.
This leads me to think there is something different in R 4.2 running on Win 10 - I have noted that R now apparently uses UTF-8 characters, but since the file consists solely of US-ASCII characters and no BOM, I am hard-pressed to think character handling on Win10 is the problem, but the fact remains the original code/ R Workspace doesn't work.
Thanks,
Jack

A: First, thanks to all the R Gurus who responded.
Second, and somewhat embarrassing, after re-learning how to use debugging tools in R, I discovered that the reason the code "ran" on R 3.5.2 was that there was a bug in the legacy C DLL.
When I looked at the problematic R code statically, it appeared that the only way the R function could possibly call the correct DLL function was if is.character(data) returned true.
However, when I stepped through the code in the debugger (in the original Win7/R 3.5.2 environment), I found that is.character(data) was actually returning false - as everyone here expected (and Casper V. further demonstrated), BUT the C function in the Win7 DLL was still treating data as an array of character strings (which it should not have done, given the logic path in the R function).
I then discovered that the legacy DLL used on Win 10, which I thought was the same as that used in the Win 7 environment, was actually a later version, in which the bug was fixed (which of course caused the R error I was seeing in Win 10).
In the end, checking the data type in R as suggested by r2evans ultimately solved the problem.

A: The behaviour of is.character() that you describe doesn't seem to have changed. What you describe as the behavior for version 3.5.2 doesn't seem to be correct, as can be seen in my attempt to replicate it below.
As mentioned by @guasi, the class of your data frame raw is just data.frame. The class of a column, eg raw$NAME, can be character.
It is possible that you had/have a custom handler for is.character() to handle data frames on the 3.5.2 setup, and you didn't copy it to the new version:
https://www.rdocumentation.org/packages/base/versions/3.5.2/topics/character

as.character and is.character are generic: you can write methods to handle specific classes of objects, see InternalMethods

You mention that the same code on the old 3.5.2 install, still calls the correct C code. Have you checked yourself what the output of is.character(raw) is on that machine?
Reproduction attempt
I have installed R 3.5.2 64 bit on Win 7, and couldn't reproduce what you remember from the past:
File: test.csv, created from example data, but tab delimited:

Here are the first 4 lines of the file (first line contains column labels; 18 total tab delimited fields - some of the string fields contain spaces, e.g. Hope Gorman is the value for the first Name field/column).

Environment:

the original development environment was 64-bit R 3.5.2 on 64-bit Win 7

> sessionInfo()
R version 3.5.2 (2018-12-20)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_3.5.2

Command:

simply reading the file into a table (WITHOUT needing to add colClasses = "character" simply worked.

> raw <- read.table('C:\\Users\\caspar\\Desktop\\test.csv', header=T, sep='\t')
> str(raw)
'data.frame':   3 obs. of  18 variables:
 $ NAME          : Factor w/ 3 levels "Ernest Farmer",..: 2 3 1
 $ ADDRESS       : Factor w/ 3 levels "179 Del Mar Blvd.",..: 1 3 2
 $ ZIP           : int  99975 99904 99900
 $ SSN           : Factor w/ 3 levels "129-21-0468",..: 3 2 1
 $ SEX           : Factor w/ 2 levels "F","M": 1 1 2
 $ MARITALSTATUS : Factor w/ 1 level "M": 1 1 1
 $ CHILDREN      : int  2 1 0
 $ OCCUPATION    : Factor w/ 2 levels "Professional",..: 1 2 2
 $ HOMEOWNERSHIP : Factor w/ 1 level "O": 1 1 1
 $ INCOME        : int  3212 3145 3165
 $ EXPENSES      : int  1124 1100 1266
 $ CHECKING      : Factor w/ 1 level "N": 1 1 1
 $ SAVINGS       : Factor w/ 1 level "Y": 1 1 1
 $ MSTRCARD      : int  1 1 1
 $ VISA          : int  5 5 5
 $ AMEX          : int  0 0 0
 $ MERCHANT      : int  9 9 9
 $ PAYMENTHISTORY: int  2 0 2

> is.character(raw)
[1] FALSE

> is.character(raw[3,1:17])
[1] FALSE

spacing between commands mine
Here I assumed you mean the same command you used before, but without the colClasses parameter. is.character() is still FALSE with colClasses = "character". It's more common to use read.csv(), but that yielded the same results as well.


text:
Q: How to go back from one to another Navigation activity on back button pressed? i am making an android application in which i am using two activities one is navigation activity and other is blank activity. i have applied intent class from navigation activity to blank activity as
Intent intent = new Intent(NavigationActivity.this,SecondActivity.class);
startActivity(intent);

that is working fine. Now i have to go back to the navigation activity on back button pressed in secondActivity. How I can do this.
@Override
public void onBackPressed() {
    super.onBackPressed();
}

i have used this approach but nothing done. sencond activity not go to a previous one and i have also used fragments in secondActivity

A: public void onBackPressed() {
    super.onBackPressed();
    finish();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: PowerShell: Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument" I am following along the example on how to parse XML with Powershell. I copied the contents of the example XML text and tried to parse with given commands. Everything worked OK.
Then I tried to parse my own XML file but immediately after I had issued  [xml]$bar = Get-Content test2.xml command, I got the following error:
Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "The '=' character, hexadecimal value 0
x3D, cannot be included in a name. Line 5, position 19."
At line:1 char:1
+ [xml]$bar = Get-Content test2.xml
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException

So I suppose the mere fact that the contents of the XML file differ affects Powershell's ability to parse XML data?
My XML file contents:
<?xml version="1.0" encoding="UTF-8"?>

<metamarket id="lowvol">
    <market id="asx" marketDir="creditcentraligaapaclve_asx_m" mandatoryNews="False">
        <houseCode="CREDITBAAPACLVE" metahouseCode="CREDITBAAPACLVE"/>
    </market>

    <market id="bru" marketDir="creditcentraligaapaclve_bru_m" mandatoryNews="False">
        <houseCode="CREDITBAAPACLVE" metahouseCode="CREDITBAAPACLVE"/>
    </market>

    <market id="sto" marketDir="creditcentraligaapaclve_sto_m" mandatoryNews="False">
        <houseCode="CREDITBAAPACLVE" metahouseCode="CREDITBAAPACLVE"/>
    </market>
</metamarket>

A: The error message indicates the source of the problem, though it doesn't specifically indicate that an element name is the problem (emphasis added):

Error: "The '=' character, hexadecimal value 0
  x3D, cannot be included in a name. Line 5, position 19."

Element names (node names in general) in XML cannot themselves contain = characters.
By contrast, the = in tokens such as id="lowvol" is a separator between an attribute name and its value.
Your XML mistakenly uses such a token - houseCode="CREDITBAAPACLVE" - directly after an opening tag's <, so that houseCode="CREDITBAAPACLVE" was interpreted as the element name.
The solution is to give your element a proper name, such as house:
<house houseCode="CREDITBAAPACLVE" metahouseCode="CREDITBAAPACLVE"/>


text:
Q: Why is my memory consumption going up every time I query mnesia? Every time I issue a query, some of my memory gets eaten, and is never recovered. If I issue the same query, more memory is used up.
For example, if I issue this query (and later convert records to maps):
CatchAll = [{'_', [], ['$_']}],
mnesia:dirty_select(read_store, CatchAll)

Edit: sorry the image was completely wrong - it was showing processes not queries

A: The problem was that I was storing strings instead of binaries in mnesia tables.
The result of http request is a string:
httpc:request(get, {Url,[]}, [{timeout, ?TIMEOUT}], [])
However, it is possible to change it to a binary instead:
httpc:request(get, {Url,[]}, [{timeout, ?TIMEOUT}], [{body_format, binary}])
This reduced the memory footprint by at least a factor of 20.


text:
Q: kubernetes (kubectl) port forwarding not working on mac for IBM MQ/Docker deployment I am trying to deploy IBM MQ to my local MAC machine using an image hosted on docker hub repository. I am using docker edge version with Kubernetes support on it.
I am able to deploy the image successfully using kubernetes and also have the Queue Manager running fine inside the container. I am also able to ssh into the container and make sure all the MQ processes are running as expected.
But when I use port forwarding using the following kubectl command, it opens the port, but does not let me telnet to it using "IP or hostname" (even from the local machine). But when I use "localhost" to telnet it works fine.
While troubleshooting, I deployed the same image using docker commands instead of kubernetes and with docker deployment, the port forwarding works as expected. It lets me telnet using IP, hostname and localhost.
So, definitely its some issue with Kubernetes port forwarding. Can some one please let me know if I am missing anything here? Let me know if there is some additional information needed from my end.
I am new to kubernetes and docker, but pretty familiar with IBM MQ.
Commands being used:
To create port forwarding rule using kubectl, checking netstat and connecting with telnet:

HOSTNAME:Test2 an0s5v4$ sudo kubectl port-forward private-reg 1414:1414 &

[1] 3001

HOSTNAME:Test2 an0s5v4$ Forwarding from 127.0.0.1:1414 -> 1414
Forwarding from [::1]:1414 -> 1414

HOSTNAME:Test2 an0s5v4$ netstat -an |grep 1414
tcp6       0      0  ::1.1414               *.*                    LISTEN
tcp4       0      0  127.0.0.1.1414         *.*                    LISTEN

HOSTNAME:Test2 an0s5v4$ ps -ef|grep 1414
    0  3001   920   0 10:27AM ttys006    0:00.03 sudo kubectl port-forward private-reg 1414:1414

    0  3002  3001   0 10:27AM ttys006    0:00.18 kubectl port-forward private-reg 1414:1414
  502  3007   920   0 10:28AM ttys006    0:00.00 grep 1414

HOSTNAME:Test2 an0s5v4$ telnet IP 1414

Trying IP...

telnet: Unable to connect to remote host: Connection refused

HOSTNAME:Test2 an0s5v4$ telnet localhost 1414

Trying ::1...

Connected to localhost.

Escape character is '^]'.

Handling connection for 1414

L-RCC9048942:Test2 an0s5v4$ telnet HOSTNAME 1414

Trying IP ...

telnet: Unable to connect to remote host: Connection refused

HOSTNAME:Test2 an0s5v4$ nslookup HOSTNAME

;; Truncated, retrying in TCP mode.

Name:   HOSTNAME
Address: IP

Kubernetes pod YAML file contents
apiVersion: v1

kind: Pod

metadata:

  name: private-reg

  labels:

     app: ibmmq

spec:

  containers:

    -

      env:

        -

          name: LICENSE

          value: accept

        -

          name: MQ_QMGR_NAME

          value: QM4

      image: "image path in docker hub"

      name: private-reg-container

      ports:

        -

          containerPort: 1414

          hostPort: 1414

EDIT: ADDED K8S Service to the post
Kubernetes service YAML file contents
apiVersion: v1
kind: Service
metadata:
  name: myservice-nodeport
  labels:
    app: ibmmq
spec:
  ports:
  - port: 3000
    targetPort: 1414
    nodePort: 31414
  selector:
    app: ibmmq
  type: NodePort

A: If you need port forwarding to bind to all the network interfaces, you can give this option. This will be useful when working with servers in OpenShift etc where there are different local and floating IPs

--address 0.0.0.0

Example
kubectl port-forward minio-64b7c649f9-9xf5x --address 0.0.0.0 7000:9000 --namespace minio

A: This is an known issue with the kubectl port-forward command. It only connects to the localhost interface. See this PR: https://github.com/kubernetes/kubernetes/pull/46517. I still am looking onto this same issue too. I see two work-arounds:

*

*socat option: (need to install with brew install socat) https://github.com/kubernetes/kubernetes/issues/43962#issuecomment-418305960, which I don't really like as I need another port to listen to than to forward

*pf solution: https://superuser.com/questions/473039/pfctl-port-forwarding-in-mac-osx#521803, which I still can't get working.

I added to the /etc/pf.conf file rules like:
rdr pass on en0 inet proto tcp from any to any port 10001 -> 127.0.0.1 port 10001, where en0 is my wifi interface:
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    ether 6c:96:cf:dd:98:e9
    inet6 fe80::b0:4b17:388d:8a1b%en0 prefixlen 64 secured scopeid 0x6
    inet 192.168.12.82 netmask 0xfffffc00 broadcast 192.168.15.255
    nd6 options=201<PERFORMNUD,DAD>
    media: autoselect
    status: active

I have a terminal with the kubectl port-forward: kubectl port-forward mypod 10001:10001, but there is not listener on the *:10001 port (you can check with the command: sudo lsof -PiTCP -sTCP:LISTEN)
If I fix it I will edit this answer.

A: As mentioned in the earlier comment Docker will bind forwarded port to 127.0.0.1 despite being explicitly asked otherwise with --address 0.0.0.0.
This issue can be solved with socat. Given a following setup:

*

*WebServer running on port 8080 in kubernetes cluster

*Docker image, where kubectl port-forward is run and exposes it to the outside at port 9876

*HostOS where a Web Browser is accessing the WebServer at localhost:9876
The code to tunnel the connection would consist of following pieces:

*

*Dockerfile
RUN yum -y install socat

*Docker run command
docker run --publish 9876:9876 ...

*port forwarding and exposing
kubectl --namespace YOUR_NAMESPACE port-forward pod/YOUR_POD_NAME --address 0.0.0.0 9877:8000 & socat TCP-LISTEN:9876,fork TCP:localhost:9877
Here, port 9877 is used as a "jump port" to bypass Docker limitations.


text:
Q: JavaScript Unsafe Access? When trying to use JavaScript in my app I am getting these following errors from Chrome:

Uncaught SyntaxError: Unexpected token )
_I-bZ2aLo8f.js:48
Unsafe JavaScript attempt to access frame with URL
http://apps.facebook.com/ubo-elementalfury/ from frame with URL
https://s-static.ak.facebook.com/connect/xd_arbiter.php?version=17#channel=f2f2ee12fc&origin=http%3A%2F%2Fultimate-battle-online.com&channel_path=%2Fchannel.php%3Ffb_xd_fragment%23xd_sig%3Df3312304ec%26.
The frame requesting access has a protocol of 'https', the frame being
accessed has a protocol of 'http'. Protocols must match.
xd_arbiter.php:20

I am not sure what is going on, I don't get this issue when browsing it from a secure Facebook connection.

A: The unsafe access error isn't causing your problem. Its the extra parenthesis you have. Go through your code and find where that is and remove it, then see what happens.
It would be helpful to know what section of your FB app that is causing this.
Edit:
I see other issues in your app that aren't related to this. In your app, http://ultimate-battle.com, on the Choose your Clan page you have this line:
document.getElementById("clock").innerHTML=movingtime;

#clock doesn't exist on this page. The error is in jquery.mycode.js on line 419.


text:
Q: What seals would suit my Torterra? I want to get seals for my Torterra but i have been unable to find some that suit him. I am looking for brown or green colour effects to suit his type and colour. I would like to know if there are any seals to suit my Torterra and how to get them.

A: Unfortunately green is not a common colour among seals. According to Bulbapedia's list of seals:

*

*Ele-Seals B and D fire green lightning bolts.

*Party Seal C creates green confetti.

*Song Seal A makes a green treble clef.

*The D, L, and T letter seals are green.

There are no brown seals whatsoever.


text:
Q: Iterating over rows in a database and removing them I'd just like to check, is this a good way of iterating over rows in a database and deleting them when processed? I first had

*

*Grab all

*Process all

*Delete all

But figured that might leave to problems if new rows were added (from outside) while the "Process all" step is running.
// the limited for loop is to prevent an infinite loop
// assume the limit to be much higher than the expected
// number of rows to process
for ($i = 0; $i < $limit; $i++)
{

    // get next mail in queue
    $st = $db->prepare('
        SELECT id, to, subject, message, attachment
        FROM shop_mailqueue
        LIMIT 0,1
    ');
    $st->execute();
    $mail = $st->fetch(PDO::FETCH_ASSOC);

    // if no more mails in queue, stop
    if ($mail === false) {
        break;
    }

    // send queued mail
    $mailer = new PHPMailer();
    $mailer->AddAddress($mail['to']);
    $mailer->SetFrom('info@xxx.nl', 'xxx.nl');
    $mailer->Subject = $mail['subject'];
    $mailer->Body = $mail['message'];
    $mailer->AddAttachment($mail['attachment']);
    $mailer->Send();

    // remove mail from queue
    $st = $db->prepare('
        DELETE FROM shop_mailqueue WHERE id = :id
    ');
    $st->bindValue('id', $mail['id']);
    $st->execute();

}

A: I think your grab all, process all, delete all approach is fine with a simple change:

*

*Instead of doing a simple delete from table, do a
delete from table where key in (<all keys retrieved>).

You can easily build the <all keys retrieved> because you first grab everything.
This will perform (a lot) better than doing many queries as you plan to do now.

A: First and foremost, any time you say, "Iterating Over Rows From a Database," you better be talking about some seriously complex operation happening for each row. Otherwise, you can and should think in sets!
It looks like you're taking everything in the mail queue and dumping the table after sending all of the emails. Now, I should note that your limit 0,1 here is a bit disconcerting, since you have no order by. No database stores things in a reliable order (and for good reason--it has to constantly move things to optimize them). So, a better code would be:
// get next mail in queue
$st = $db->prepare('
    SELECT id, to, subject, message, attachment
    FROM shop_mailqueue
    ORDER BY id ASC
    LIMIT 0, ' . $limit);
        $st->execute();

$lastid = 0;

while ($mail = $st->fetch(PDO::FETCH_ASSOC))
{
    // send queued mail
    $mailer = new PHPMailer();
    $mailer->AddAddress($mail['to']);
    $mailer->SetFrom('info@xxx.nl', 'xxx.nl');
    $mailer->Subject = $mail['subject'];
    $mailer->Body = $mail['message'];
    $mailer->AddAttachment($mail['attachment']);
    $mailer->Send();

    $lastid = $mail['id'];
}

// remove mail from queue
$st = $db->prepare('DELETE FROM shop_mailqueue WHERE id <= ' . $lastid);
$st->execute();

This way, you're only making two (count 'em!) queries to the database, which is much more optimal than pulling one row back each time.
Now, if the whole $limit deal is unnecessary, and you really want to pull back all of the rows in the queue and then just dump the queue out, change your delete statement to:
TRUNCATE TABLE shop_mailqueue

See, truncate isn't bound by transaction logic, and just wipes the table clean, no questions asked. Therefore, it's immensely fast (as in milliseconds, regardless of table size). delete just doesn't have that kind of speed. Just remember that truncate is a nuclear option--once you truncate, it's gone gone.

A: You can lock table during process
http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html

A: What you are doing is fine, I think. You fetch all that you had, you process them and delete only those that you processed. I also would not lock the table in your process, because you will block those who create the records.
If the only problem you have is to process those e-mails that may have been created while you were sending out existing ones, then you could just create a while loop on top of all your procedure to run always when there are new records.
In addition, why getting LIMIT 0,1 ($limit) times, if you can just modify the query to get max $limit items in one query LIMIT 0,$limit.


text:
Q: Is there a VBA function that could create boolean entries for the days employees have worked? I am trying to create boolean entries for the days employees have worked. Here is my sample code:
Sub BooleabAtt2()
'Create boolean entries for days worked
'Sign-on Worksheet
Dim ws1 As Worksheets
    Set ws = Worksheets("Sign-ons")
Dim rng1 As Range
    Set rng1 = ws1.Range("SignOns")
Dim EmployeeName1 As Long
    EmployeeName1 = rng1.Columns("", 2)
Dim DateIn1 As Date
    DateIn1 = rng1.Columns("", 6)
Dim Company1 As Long
    Company1 = rng1.Colums("", 3)
Dim RowCount As Long
Dim LastRow As Long
Dim i As Long

'Employee ID Worksheet
Dim ws2 As Worksheets
    Set ws2 = Worksheets("EmployeeID")

'ConsecutiveDays worksheet
Dim ws3 As Worksheets
    Set ws3 = Worksheets("Consecutive-Days")
Dim rng3 As Range
    Set rng3 = ws3.Range("ConsecutiveDays")
Dim EmployeeName

'conditional statement
With rng1
    LastRow = .Colums(2).Rows.Count
    For i = LastRow
        If ws3.rng3.Cells(1, i) = DateIn1 Then
            If ws3.rng3.Cells(i, 2) = EmployeeName1 Then Enter 1
            Otherwise "0"
            End If
        End If
    Next i
End With

End Sub

Below is some sample data
Excel sample data
The table below is what I am trying to achieve:
Final worksheet

A: I agree this could easily be done with formulas. First, to create a list of unique employees, either go to data> remove duplicates, or use a formula like this. I think there's also a unique formula if you have the newest version of excel
Then use the formula =COUNTIFS($F$2:$F$11,B$1,$E$2:$E$11,$A2)

A: Here's a shot at it using VBA.
Source table (named "timesheet")

Public Function CreateMyPivotTable()

''' Source, destination, and pivot table name variables. '''
''' We're using Sheet1 and Sheet2 for our worksheets, but you
''' could probably add those as a parameter.
Dim source_worksheet_name As String: source_worksheet_name = "Sheet1"
Dim source_tablename As String: source_tablename = "timesheet"
Dim destination_worksheet_name As String: destination_worksheet_name = "Sheet2"
Dim pivot_table_name As String: pivot_table_name = "PivotTimeSheet"

Dim source_worksheet As Worksheet
Dim destination_worksheet As Worksheet

''' Create source and destination worksheet objects.
Set source_worksheet = ActiveWorkbook.Worksheets(source_worksheet_name)
Set destination_worksheet = ActiveWorkbook.Worksheets(destination_worksheet_name)

''' Create source and pivot table objects
Dim src_tbl As ListObject
Dim pivot_tbl As PivotTable

''' Focus on destinaton worksheet.
source_worksheet.Select

''' Set source table variable.
Set src_tbl = source_worksheet.ListObjects(source_tablename)

''' Clear out pivot table (function is below.
Call RemovePivotTable(pivot_table_name)

''' Generate pivotcache using our table source.
With ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=src_tbl.Range.Address(False, False, xlA1, xlExternal))
    ''' Create pivot table at A1 in the destination worksheet.
    Call .CreatePivotTable(TableDestination:=destination_worksheet.Range("A1"), tablename:=pivot_table_name)
End With

''' Focus on destinaton worksheet.
destination_worksheet.Select

''' Set EmployeeName and Date in as Row and Column fields
''' Use count of Date in per EmployeeName as value.
With destination_worksheet.PivotTables(pivot_table_name)
    ''' Miss me with that Grand Total stuff
    .RowGrand = False
    .ColumnGrand = False

    ''' Fill any missing values with Zero.
    .NullString = "0"

    ''' General pivot action. Pretty self explanatory.
    With .PivotFields("EmployeeName")
        .Orientation = xlRowField
        .Position = 1
    End With

    With .PivotFields("Date in")
        .Orientation = xlColumnField
        .Position = 1
    End With

    ''' Data field section
    With .PivotFields("Date in")
        .Orientation = xlDataField
        .Function = xlCount ' Count dates per employee
        .NumberFormat = "0" ' General number format.
    End With
End With

''' Clear objects before leaving.
Set source_worksheet = Nothing
Set destination_worksheet = Nothing
Set src_tbl = Nothing
Set pivot_tbl = Nothing

End Function

Public Function RemovePivotTable(pivot_table_name As String)
''' Delete a pivot table by name.
''' Ex. usage -
'''     RemovePivotTable("PivotTimeSheet")

If Len(pivot_table_name) > 0 Then
    ''' In general, iterate over each worksheet,
    ''' look for a name match
    ''' then clear out that pivot table.
    Dim pvttbl As PivotTable
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        For Each pvttbl In ws.PivotTables
            If pvttbl.Name = pivot_table_name Then
                pvttbl.TableRange2.Clear
            End If
        Next pvttbl
    Next ws
    Set pvttbl = Nothing
    Set ws = Nothing
End If

End Function

Output (on Sheet2):

EDIT: The best way to get a count of 1 in each pivot cell is by removing duplicate values in the table.  That could be done manually, but I recorded a macro that produced the following:
ActiveSheet.Range("timesheet[#All]").RemoveDuplicates Columns:=Array(2, 3), Header:=xlYes

(Remember skip the No. column or else no rows will be removed since all of those values are unique.)
Once that's done, this will be your output:


text:
Q: Stop Button inside a For loop I have been looking around for a stop button but I can't find anything that applies to my code.
if (O1.isSelected()) {
    for (int nu = Num; nu > 0; nu--) {
        try {
            Robot robot = new Robot();
            robot.delay(Num2 * 1000);
            robot.keyPress(KeyEvent.VK_H);
            robot.keyPress(KeyEvent.VK_E);
            robot.keyPress(KeyEvent.VK_L);
            robot.keyPress(KeyEvent.VK_L);
            robot.keyPress(KeyEvent.VK_O);
            robot.keyPress(KeyEvent.VK_SPACE);
            robot.keyPress(KeyEvent.VK_W);
            robot.keyPress(KeyEvent.VK_O);
            robot.keyPress(KeyEvent.VK_R);
            robot.keyPress(KeyEvent.VK_L);
            robot.keyPress(KeyEvent.VK_D);
            robot.keyPress(KeyEvent.VK_ENTER);
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
}

I was thinking of making the jbutton initiate a break; but I can't seem to use jButtonActionPerformed inside a for loop. Any help is greatly apriciated.
Thanks.

A: Make the button's click handler set a private field to indicate that the action has been "stopped", then make your for loop check for that field when it is at a safe place to cancel:
for (int nu = Num; nu > 0; nu--) {
    try {
        Robot robot = new Robot();
        robot.delay(Num2 * 1000);
        if (this.stopRequested) {
            this.stopRequested = !this.stopRequested;
            break;
        }
        robot.keyPress(KeyEvent.VK_H);
        robot.keyPress(KeyEvent.VK_E);
        robot.keyPress(KeyEvent.VK_L);
        robot.keyPress(KeyEvent.VK_L);
        robot.keyPress(KeyEvent.VK_O);
        robot.keyPress(KeyEvent.VK_SPACE);
        robot.keyPress(KeyEvent.VK_W);
        robot.keyPress(KeyEvent.VK_O);
        robot.keyPress(KeyEvent.VK_R);
        robot.keyPress(KeyEvent.VK_L);
        robot.keyPress(KeyEvent.VK_D);
        robot.keyPress(KeyEvent.VK_ENTER);
    } catch (AWTException e) {
        e.printStackTrace();
    }
}


text:
Q: Creating polygon in turf surrounding route generated by OSRM? I am generating a route using the osrm rendering it by leaflet, and I was trying to create a  buffer automatically surrounding this route

As you can see in the previous image, there are parts of the route that are not inside the buffer generated by turf.
Does anyone know some router that can generate me more points of the route so the buffer can be more precise?


text:
Q: Question about Multiplication of Series of Analytic Functions Can you help with this problem?
Thank you so much!
I want to multiply this two series:

This is the result:

I want to do exactly like this example that is at the end, but I do not understand how to combine them. I do not understand also how in the example they found (k-1)/2 and all the other details in the result.
As they are power series of analytic functions, the result is also analytic in the intersection of the intervals (-1,1)


text:
Q: create editing modal in laravel 7 i'm trying to make a timesheet table that takes inputs from attendance machine, and it can be edited later on, my table look like this:
![timesheet table][1]: https://i.stack.imgur.com/5D1ap.png
this is the popup to edit time and reason of editing the half day :
[edit time and reason][2]: https://i.stack.imgur.com/tPa37.png
however, when i pick time and reason, i can't update them in the table, this is the code of modal:

Changer l'heure

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                <form action="">

                        <input type="time" class="form-control">

                        <select name="motif" class="form-control">
                            <option value="">MCD</option>
                            <option value="">MTA</option>
                            <option value="">CA</option>
                            <option value="">AIR</option>
                            <option value="">MLD</option>
                            <option value="">CS</option>
                        </select>

                </form>

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
                    <button type="button" class="btn btn-primary">Enregistrer</button>

is there any solution to make it working?

A: Okay, you need a couple of things for your modal form to work.

*

*You need to add route in your form open tag (see my example below)

*Your form submit button at the modal-footer div needs to be inside the form open and close tags (see my exaple below)

*Your submit button must have a type of submit for it to send to form parameters. (see my example below)

*You need a method in your controller to process your form request and save into the database (Hope you know that.).

         {{ Form::open(['action' => 'YourController@update_method','method' =>'PATCH']) }}

Changer l'heure

             <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                 ×
             </button>

             {{-- <form action=""> remove --}}

                     <input type="time" class="form-control">

                     <select name="motif" class="form-control">
                         <option value="">MCD</option>
                         <option value="">MTA</option>
                         <option value="">CA</option>
                         <option value="">AIR</option>
                         <option value="">MLD</option>
                         <option value="">CS</option>
                     </select>

             {{-- </form> remove --}}

                 <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
                 {{-- Your submit button should look like this --}}
                 <button type="submit" class="btn btn-primary">Enregistrer</button>

             {{ Form::close() }}

Also make sure the function you put on your form's action attribute is defined on your routes file like this below
Route::patch('url', 'YourController@update_method')->name('model.update_method');.


text:
Q: How to save/load to/from file in virtualtree component using Delphi? I have downloaded the virtualtree component and the manual"Virtual TreeView tutorial". I follow the tutorial and coding  step  by step. Most of the function in tutorial is fine except the savetofile and loadfromfile do not work.
My node data is
type
  PMytreedata = ^TMYTreeData;
  TMYTreeData = record
    Column0: String;
    Column1: String;
    Column2: String;
  end;

The question is something string lose in column0,column1/2 when load from file.
The code is below
Create new node and data:
procedure TForm3.Button1Click(Sender: TObject); //CRETAE NEW NODE AND DATA
begin
  Randomize;
  Rand := Random(99);
  XNode := VST.AddChild(nil);

  if VST.AbsoluteIndex(XNode) > -1 then
  begin
    Data := VST.GetNodeData(Xnode);
    Data^.Column0 := IntToStr(Rand)+EDIT1.Text + 'One' ;
    Data^.Column1 := EDIT1.Text+'Two' + IntToStr(Rand + 10);
    Data^.Column2 := EDIT1.Text+'Three' + IntToStr(Rand - 10);
  end;
end;

procedure TForm3.Button2Click(Sender: TObject);//ADDCHILD
var
  XNode: PVirtualNode;
  Data: PMytreedata;
begin
  if not Assigned(VST.FocusedNode) then
     Exit;

   XNode := VST.AddChild(VST.FocusedNode);
   Data := VST.GetNodeData(Xnode);

   Data^.Column0 := EDIT1.Text ;
   Data^.Column1 := EDIT2.Text ;
   Data^.Column2 := EDIT3.Text ;

   VST.Expanded[VST.FocusedNode] := True;
end;

Save to file  and load from file
procedure TForm3.Button4Click(Sender: TObject);
begin
    VST.SaveToFile('C:\vst.at1');
end;

procedure TForm3.Button5Click(Sender: TObject);
begin
    VST.LoadFromFile('C:\vst.at1');
end;

Get the node size without the code error
procedure TForm3.VSTGetNodeDataSize(Sender: TBaseVirtualTree;
  var NodeDataSize: Integer);
begin
    NodeDataSize := SizeOf(TMYTreeData);//WITHOUT THE CODE,ERROR COMING .
end;

Show text
procedure TForm3.VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
  Column: TColumnIndex; TextType: TVSTTextType; var CellText: string);
var
  Data: PMytreedata;
begin
  Data := VST.GetNodeData(Node);
  case Column of
    0: CellText := Data^.Column0;
    1: CellText := Data^.Column1;
    2: CellText := Data^.Column2;
  end;
end;

LOAD FORM FILE
procedure TForm3.VSTLoadNode(Sender: TBaseVirtualTree; Node: PVirtualNode;
  Stream: TStream);//LOAD FORM FILE
var
  Data: PMytreedata;
  Len: Integer;
begin
      Data := VST.GetNodeData(Node);

      Stream.read(Len, SizeOf(Len));
      SetLength(Data^.Column0, Len);
      Stream.read(PChar(Data^.Column0)^, Len);

      Stream.read(Len, SizeOf(Len));
      SetLength(Data^.Column1, Len);
      Stream.read(PChar(Data^.Column1)^, Len);

      Stream.read(Len, SizeOf(Len));
      SetLength(Data^.Column2, Len);
      Stream.read(PChar(Data^.Column2)^, Len);
end;

SAVE TO FILE
procedure TForm3.VSTSaveNode(Sender: TBaseVirtualTree; Node: PVirtualNode;
  Stream: TStream); //SAVE TO FILE
var
  Data: PMytreedata;
  Len: Integer;
begin
  Data := VST.GetNodeData(Node);

  Len := Length(Data^.Column0);
  Stream.write(Len, SizeOf(Len));
  Stream.write(PChar(Data^.Column0)^, Len);

  Len := Length(Data^.Column1);
  Stream.write(Len, SizeOf(Len));
  Stream.write(PChar(Data^.Column1)^, Len);

  Len := Length(Data^.Column2);
  Stream.write(Len, SizeOf(Len));
  Stream.write(PChar(Data^.Column2)^, Len);
end;

A: In Unicode Delphi, 2009 and later, Char is a 16 bit type, WideChar. You are only writing half of the string because you don't account for this. In each call to Write and Read for the content of the string, you must write twice as many bytes.
For instance, each line like this
Stream.read(PChar(Data^.Column0)^, Len);

should be
Stream.read(PChar(Data^.Column0)^, Len*SizeOf(Char));

Some other comments:

*

*You replicate code to read and write each string. It would be better practise to extract those repeated sections of code into methods for re-use.

*You should use WriteBuffer rather than Write. WriteBuffer calls Write to do the work, but also checks the return value and performs error checking. Likewise call ReadBuffer rather than Read.


text:
Q: Java - closing socket gives different results I'm getting different results while trying to read from a socket while the other socket is closed.
I have two sockets A and B.
1)B sent some data to A --> A has read the data --> A closes -->  When B tries to read some data from A, it is getting -1(or EOF).
2)B sent some data to A --> A closes even before reading the data --> Now B tries to read from A, an exception is thrown(java.net.SocketException "Software caused connection abort.")
please excuse me, if you can't understand my question. Please see the code
Server.java
import java.io.*;
import java.net.*;

class SocketCloser extends Thread
{
    private Socket c;
    public SocketCloser(Socket c) {
        this.c = c;
    }

    public void run()  {

        try{
            this.c.close();
        } catch (Exception e) {}
    }
}

public class Server
{
    public static void main(String argv[]) throws Exception {
        ServerSocket listen = new ServerSocket(6789);

        Socket socket = listen.accept();
        SocketCloser sc = new SocketCloser(socket);
        InputStream is = socket.getInputStream();
        // uncomment below line to get "Software caused connection abort" on client
        //sc.start();
        try {
            Thread.sleep(1000);
            int i = is.read();
            System.out.println("read returned: " + i);
            socket.close();
        } catch (Exception e) {
            System.out.println(e.toString() + " thrown");
        }
    }
}

Client.java
import java.io.*;
import java.net.*;

public class Client
{
    public static void main(String argv[])
    {
        Socket cSocket;
        try {
            cSocket = new Socket("localhost", 6789);
            InputStream is = cSocket.getInputStream();
            OutputStream os = cSocket.getOutputStream();
            Thread.sleep(1000);
            os.write(200);
            Thread.sleep(1000);
            int i = is.read();
            System.out.println("read returned: " + i);
            cSocket.close();
        } catch (Exception e) {
            System.out.println(e.toString() + " thrown");
        }
    }
}

Can someone please help me figure out why there is an exception in one case and -1 in another. Interestingly on linux both the cases resulted in -1.

A: 1) Because B established a connection, A goes to CLOSE_WAIT. It will be in that state until B closes the connection. There is nothing to read, so the read() call on B's InputStream returns -1.
2) A is blocked in the accept call. The other thread is trying to close the socket, but it can't because accept is blocking it. When B connects, accept unblocks and the socket closes outright. When B tries to read, the socket is not there anymore so you get the exception.
I'm simplifying a bit, but that's the gist of it.

A:
1)B sent some data to A --> A has read the data --> A closes --> When B tries to read some data from A, it is getting -1(or EOF).

I agree. What did you expect? This is the expected behaviour.

2)B sent some data to A --> A closes even before reading the data --> Now B tries to read from A, an exception is thrown(java.net.SocketException "Software caused connection abort.")

I agree. This is one of the expected behaviours in this incorrect situation. What did you expect?

please excuse me, if you can't understand my question.

There is no question here to understand. You haven't asked a question. You close a socket without sending any data and the peer gets EOS without receiving any data. You close a socket while the peer is sending and the peer gets an exception. System is working as designed.


text:
Q: Hugo – How to add different class names based on counter Using Hugo, I need add unique class names to the first few posts. How can this be done?
My code that's obviously not working…
// if the first post
{{ if eq .Site.GetPage 1 }}
    {{ $classname := "class-one" }}
// else the second post
{{ elseif eq .Site.GetPage 2 }}
    {{ $classname := "class-two" }}
// else the third post
{{ elseif eq .Site.GetPage 3 }}
    {{ $classname := "class-three" }}
{{ else }}
{{ end }}

    …

A: Maybe there's some more efficient way, but this works:
{{ $paginator := .Paginate (where .Data.Pages.ByDate.Reverse "Type" "post") }}

{{ range $index, $element := $paginator.Pages }}

{{ if (eq $index 0) }}
{{ $.Scratch.Set "classname" "class-one" }}
{{ else if (eq $index 1) }}
{{ $.Scratch.Set "classname" "class-two" }}
{{ else }}
{{ $.Scratch.Set "classname" "" }}
{{ end }}

    …

{{ end }}


text:
Q: iCloud storage photos I have an iphone 4, with ios 7.1.2, and my phone tells me my software is up to date. When I log into iCloud photos, I can't view any of my photos. There is small print saying "iCloud photos requires ios 8.1 or later..." Does this mean I cannot use iCloud? I am paying for extra storage but where are my pictures?

A: You can use iCloud photos from a PC, Mac, iOS and web application. So it's conceivable you could use that service even though one of your devices is ineligible to participate due to it not running a supported iOS version.
From a supported web browser, your photos in iCloud are at:

*

*https://www.icloud.com/#photos
You can review storage at - https://www.icloud.com/#settings


text:
Q: Getting ajax based data in laravel I try to make a finder (kind of advanced search), I came half way and i'm facing issue by getting third part of my search query.
Logic

*

*Select category

*Select Subcategory

*Select Specifications of products in Subcategory

*Select Brands in Subcategory

Basically user will select category, then select subcategory of that category till here I've done then all specifications and brands of that subcategory products will be presented to select.
issue

My problem is to get specifications and brands from selected
  subcategory.

Reason that I want to get these info base on chosen subcategory is because each subcategory products have different brand and specifications for example i don't want to show cpu specification while user chooses mouse subcategory! there is no cpu for any kind of mouses, that's the whole reason.
codes
blade
<form action="" class="mt-20">

                    category
                    <select name="category_id" class="form-control">
                        <option value="">Select Category</option>
                        @foreach($findercategories as $category)
                            <option value="{{$category->id}}">{{$category->title}}</option>
                        @endforeach
                    </select>

                    subcategory
                    <select name="subcategory_id" class="form-control">
                        <option value="">Select Subcategory</option>
                    </select>

                    specifications
                    <select name="specification_id" class="form-control">
                        <option value="">Select Specification</option>
                    </select>

                    brands
                    <select name="brand_id" class="form-control">
                        <option value="">Select Brand</option>
                    </select>

                        <button style="margin: 20px;" class="pull-right btn btn-info" type="submit">Find</button>

              </form>

Javascript

controller
//get categories list
$findercategories = Category::ofStatus('Active')->get();

//finder (subcategories)
    public function getSubCategories($id){
        $subcategory = Subcategory::where('category_id', $id)->get();
        return response()->json($subcategory);
    }

//finder (specifications + brands)
    public function getspecifications($id){
        $product = Product::where('subcategory_id', $id)->get();
        $productsubsp = DB::table('product_subspecification')->where('product_id', $product)->get();
        $specifications = $productsubsp;
        return response()->json($specifications);
    }

routes
Route::get('/getSubCategories/{id}', 'frontend\SearchController@getSubCategories');
Route::get('/getspecifications/{id}', 'frontend\SearchController@getspecifications');

Extra (just to be clear about data i try to get)

*

*My product brands are saving with id in products table in column
named brand_id

*My product specifications are saving in third table named
product_subspecification which will get id product_id and
subspecification_id
This is how i get those info in front-end:
for brands

{{$product->brand->title}}

and for specifications
in controller
$specifications = $product->subspecifications->mapToGroups(function ($item, $key) {
        return [$item->specification->title => $item];
    });

in blade
@foreach($specifications as $specificationtitle => $specificationcollection)

{{ $specificationtitle }}

@foreach($specificationcollection as $subspecification)
{{$subspecification->title}}
@endforeach

@endforeach

This returns like:

CPU  CORE I5 CORE I3 CORE I7
RAM  2 GIG 4 GIG

UPDATE
I managed to get my result in specifications dropdown, however i have problem with getting all my products under chosen subcategory I only can get last product and not all of them.
codes
here is how i get my results currently
public function getspecifications($id){
            //find products under subcategory
             $product = DB::table('products')
                            ->where('subcategory_id', $id)
                            ->get();
                            foreach($product as $pp) {
                            }
            $specificationsw = $pp->id; //get products id (currently has issue, only gets 1)

            // find products specification with same product id
            $specificationss = DB::table('product_subspecification')
                            ->where('product_id', $specificationsw)->get();
                            foreach($specificationss as $dd) {
                            }
            $specificationsss = $dd->subspecification_id; //get specifications id from product_subspecification table

            // get specifications title base on table above
           $specifications = DB::table('subspecifications')
                            ->where('id', $specificationsss)->get();
        return response()->json($specifications);
    }

any idea how to get all my products id instead of only last one which i'm getting currently?
UPDATE2
I changed my controller to code below and now i'm able to get all my products from subcategory:
public function getspecifications($id){
            //find products under subcategory
            $product = DB::table('products')
                            ->where('subcategory_id', $id)
                            ->get();
            $date = array();
            foreach ($product as $stan) {
                $date[] = $stan->id;
            }
            $specificationsw = $date; //get products id (currently has issue, only gets 1)

            // find products specification with same product id
            $specificationss = DB::table('product_subspecification')
                            ->where('product_id', $specificationsw)->get();
            $date2 = array();
            foreach ($specificationss as $stan2) {
                $date2[] = $stan2->subspecification_id;
            }
            $specificationsss = $date2; //get specifications id from product_subspecification table

            // get specifications title base on table above
            $specifications = DB::table('subspecifications')
                            ->where('id', $specificationsss)->get();
            $date3 = array();
            foreach ($specifications as $stan3) {
                $date3[] = $stan3;
            }
            $specifications = $date3;
        return response()->json($specifications);
    }

now here is my dd results:
dd($specificationsw); products dd which is id of products 2 products
array:2 [▼
  0 => 27
  1 => 38
]

dd($specificationsss); product_subspecification table result only return values of product id 27. nothing for product id 38!
array:2 [▼
  0 => 5
  1 => 8
]

dd($specifications); result of last part of my function i get this title in my ajax code in front-end but as you see info about subspesification id 8 and product id 38 is lost.
array:1 [▼
  0 => {#722 ▼
    +"id": 5
    +"title": "4 GIG"
    +"specification_id": 2
    +"created_at": "2017-12-04 00:00:00"
    +"updated_at": "2017-12-04 00:00:00"
  }
]

A: SOLVED
I solved my issue here is for those in need:
Explanation:

*

*first method of controller will get subcategories base on chosen
category id.

*second method will show specifications base on selected subcategory, note in my case specifications where stored in their table and related to my products with sync method in third table. (will show specifications that used in products under that subcategory only)

*third method will show brands base on selected subcategory (will show brands that used in products under that subcategory only)

Controller methods
//finder (find subcategories base on selected category)
    public function getSubCategories($id){
        $subcategory = Subcategory::where('category_id', $id)->get();
        return response()->json($subcategory);
    }

    //finder (show specifications base on selected subcategory)
    public function getspecifications($id){
            $specifications = DB::table('products')
                        ->where('subcategory_id', $id)
                        ->join('product_subspecification', 'product_subspecification.product_id', '=', 'products.id')
                        ->join('subspecifications', 'subspecifications.id', '=', 'product_subspecification.subspecification_id')
                        ->groupBy('subspecifications.id')
                        ->get();
            return response()->json($specifications);
    }

    //finder (show brands base on selected subcategory)
    public function getbrands($id){
        $specifications = DB::table('products')
                    ->where('subcategory_id', $id)
                    ->join('brands', 'brands.id', '=', 'products.brand_id')
                    ->groupBy('brand_id')
                    ->get();
                    return response()->json($specifications);
    }

Important: In order to avoid duplicated results in specifications and brands I used groupBy.

Routes
Route::get('/getSubCategories/{id}', 'frontend\SearchController@getSubCategories');
Route::get('/getspecifications/{id}', 'frontend\SearchController@getspecifications');
Route::get('/getbrands/{id}', 'frontend\SearchController@getbrands');

Scripts


text:
Q: iOS: Is it possible to detect if a track exists in music library? I'm working on an app for a band and they'd like certain features to unlock if their album or singles are in the user's music library.
Is it possible to scan the library for a specific title?(and possibly check duration as well?)

A: It should be possible to do both, have a look at the iPod Library Access Programming Guide, specifically the seconds on programmatically querying the media store and the item metadata (for the duration).

A: Here is a working search. This checks for a track that matches both the title and the artist name.
MPMediaPropertyPredicate *titlePredicate = [MPMediaPropertyPredicate predicateWithValue:@"Sleep The Clock Around" forProperty:MPMediaItemPropertyTitle comparisonType:MPMediaPredicateComparisonEqualTo];

MPMediaPropertyPredicate *artistPredicate = [MPMediaPropertyPredicate predicateWithValue:@"Belle & Sebastian" forProperty:MPMediaItemPropertyArtist comparisonType:MPMediaPredicateComparisonEqualTo];

MPMediaQuery *trackSearch = [[MPMediaQuery alloc] initWithFilterPredicates:[NSSet setWithObjects:titlePredicate,artistPredicate, nil]];

if(trackSearch.items.count > 0) NSLog(@"we found the track!");


text:
Q: Color Intensity of Pixel(X,Y) on Image [OpenCV / Python] I'm using Template Matching to detect for smaller images in a large image.
After detecting it , i would grab the center point(x y) of main picture of the detected image.
Could anyone advice how I could grab the shade/color of that particular center point?
I understand the Template Matching ignores color , based this example, is there anyway to grab the color intensity of the particular pixel? of that center point
# Python program to illustrate
# template matching
import cv2
import numpy as np
import time
import sys

# Read the main image
img_rgb = cv2.imread('test.png')

# Convert it to grayscale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)

# Read the template
template = cv2.imread('template.png',0)

# Store width and heigth of template in w and h
w, h = template.shape[::-1]

# Perform match operations.
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)

# Specify a threshold
threshold = 0.90

# Store the coordinates of matched area in a numpy array
loc = np.where( res >= threshold)

xyMiddle = ""
for pt in zip(*loc[::-1]):
    xyMiddle = str(pt[0] + w/2) +"," +str(pt[1] + h/5)
if(xyMiddle != ""):
    print(xyMiddle)

A: The grayscale image has just a single channel and the colour image has 3 or 4 channels (BGR or BGRA).
Once you have the pixel coordinates, the pixel value in the grayscale image will be an intensity value or you can get the BGR values from that pixel in the original image. That is, img_gray[y][x] will return an intensity value in the range 0-255, and img_rgb[y][x] will return a list of [B, G, R (, A)] values, each of which will have intensity values in the range 0-255.
Thus the value returned when you call e.g. img_gray[10][50] or print(img_gray[10][50]) is the pixel value at x=50, y=10. Similarly the value returned when you call e.g. img_rgb[10][50] is the pixel value at x=50, y=10, but calling it in this way will return the list of pixel values for that location e.g. [93 238 27] for RGB or [93 238 27 255] for RGBA. To get just the B, G or R value you would call img_rgb[10][50][chan] where for chan, B=0, G=1, R=2.


text:
Q: Writing a plugin: inserting image I'm trying to write a plugin to for quotations.
A quotation will have an author and a text.
The shortcode will be like this:
[portrait-quotation author="George W. Bush" text="I think we agree, the past is over." link="https://en.wikipedia.org/wiki/Bushism" portrait="..."]
I've managed to do everything but the portrait. Could you help me understand how to do that. I suppose, the image should be inserted into the media library. And then a ready made wordpress function should prepare img tag with srcset according to what sizes the current theme is able to operate on.
I thought that an image will have an ID or something. But I failed to find any accessible in the admin.
Could you help me with the problem? In other words:
1. How to organize uploading portraits?
2. How to prepare img tags?
3. Which ready made functions will be helpful?
4. General comment on how to cope with the task most elegantly.


text:
Q: PHP - join elements with the same attribute within a loop I'm trying to "group" the elements from the XML, where some of them share the same date and then print certain values from those element "groups".
The XML structure:
<parent>

    <element date="2017-04-18D12:00:00">
        <node value="30" />
        <node value="82" />
        <node value="25" />
        <foo name="noon" />
    </element>
    <element date="2017-04-18D18:00:00">
        <node value="12" />
        <node value="52" />
        <node value="11" />
        <foo name="evening" />
    </element>

    <element date="2017-04-19D00:00:00">
        <node value="21" />
        <node value="78" />
        <node value="33" />
        <foo name="night" />
    </element>
    <element date="2017-04-19D06:00:00">
        <node value="35" />
        <node value="57" />
        <node value="88" />
        <foo name="morning" />
    </element>
    <element date="2017-04-19D12:00:00">
        <node value="22" />
        <node value="92" />
        <node value="81" />
        <node value="19" />
        <foo name="noon" />
    </element>
    <element date="2017-04-19D18:00:00">
        <node value="2" />
        <node value="30" />
        <node value="44" />
        <foo name="evening" />
    </element>

    <element date="2017-04-20D00:00:00">
        <node value="12" />
        <node value="99" />
        <node value="43" />
        <foo name="night" />
    </element>
    <element date="2017-04-20D06:00:00">
        <node value="65" />
        <node value="211" />
        <node value="16" />
        <foo name="morning" />
    </element>
    <element date="2017-04-20D12:00:00">
        <node value="32" />
        <node value="55" />
        <node value="77" />
        <node value="1" />
        <foo name="noon" />
    </element>
    <element date="2017-04-20D18:00:00">
        <node value="68" />
        <node value="74" />
        <node value="21" />
        <foo name="evening" />
    </element>
    ...
</parent>

Each element has a date attribute which i would like to use to group the elements.
The end result should print

Monday

11

82

noon

evening

Thursday

2

92

night

morning

noon

evening

Wednesday

1

211

night

morning

noon

evening

...

Here is what i have so far:
$source = simplexml_load_file('http://example.com');
foreach ($source -> parent -> element as $element) {
    // Format the date value and get the day so the elements could group
    $from      = explode('D', $element['date']);
    $group_day = explode('-', trim($from[0]));

    // problem starts here :)

}

Comments in the XML are just for presentation and not included inside it.

A: Try this hope it will help you out. Here i am using DOMDocument to retrieve tags with name element and get retrieving its attribute date afterwards you can do what you want..
Try this code snippet here
$source = new DOMDocument();
$source->loadXML('<parent>

    <element date="2017-04-18D12:00:00">
        <node value="30" />
        <node value="82" />
        <node value="25" />
        <foo name="noon" />
    </element>
    <element date="2017-04-18D18:00:00">
        <node value="12" />
        <node value="52" />
        <node value="11" />
        <foo name="evening" />
    </element>

    <element date="2017-04-19D00:00:00">
        <node value="21" />
        <node value="78" />
        <node value="33" />
        <foo name="night" />
    </element>
    <element date="2017-04-19D06:00:00">
        <node value="35" />
        <node value="57" />
        <node value="88" />
        <foo name="morning" />
    </element>
    <element date="2017-04-19D12:00:00">
        <node value="22" />
        <node value="92" />
        <node value="81" />
        <node value="19" />
        <foo name="noon" />
    </element>
    <element date="2017-04-19D18:00:00">
        <node value="2" />
        <node value="30" />
        <node value="44" />
        <foo name="evening" />
    </element>

    <element date="2017-04-20D00:00:00">
        <node value="12" />
        <node value="99" />
        <node value="43" />
        <foo name="night" />
    </element>
    <element date="2017-04-20D06:00:00">
        <node value="65" />
        <node value="211" />
        <node value="16" />
        <foo name="morning" />
    </element>
    <element date="2017-04-20D12:00:00">
        <node value="32" />
        <node value="55" />
        <node value="77" />
        <node value="1" />
        <foo name="noon" />
    </element>
    <element date="2017-04-20D18:00:00">
        <node value="68" />
        <node value="74" />
        <node value="21" />
        <foo name="evening" />
    </element>
</parent>');
$result=array();
foreach ($source->getElementsByTagName("element") as $element)
{
    $date=$element->getAttribute("date");
    $from      = explode('D', $date);
    $group_day = explode('-', trim($from[0]));
    $values=array();
    $weekDay=date("l",  strtotime($date));
    foreach($element->childNodes as $node)
    {
        if($node instanceof DOMElement)
        {
            if(!empty($node->getAttribute("value")))
            {
                $result[$group_day[2]]["values"][]=$node->getAttribute("value");
            }
            else
            {
                $result[$group_day[2]]["datetime"][]=$node->getAttribute("name");
            }
        }
    }
    $result[$group_day[2]]["weekDay"][$weekDay]=$weekDay;
}

foreach($result as $key => $value)
{
    $array=$result[$key]["values"];
    asort($array);
    $lowest=$array[key($array)];
    arsort($array);
    $highest=$array[key($array)];
    $result[$key]["values"]=array();
    $result[$key]["values"]["highest"]=$highest;
    $result[$key]["values"]["lowest"]=$lowest;
}
print_r($result);

A: This is a better XML format than last time as it is much easier to relate elements.
Like last time, let's parse the XML and put it in a format we can work with.
We'll create another associative map $groups except this time keyed on the date that comes from the <element/> date attributes. Since we need to store the times of the day, we'll need to adjust the values of our map, so that we can store the <node/> value attributes and <foo/> name attributes. This can easily be done by making an inner map.
$xml = simplexml_load_file('http://example.com');

// group all the value/name attributes

foreach ($xml->element as $element) {
    $datetime = (string) $element->attributes()['date'];
    // let's remove the time
    $date = substr($datetime, 0, 10);
    // check if there is a group for that date; if not create one
    if (!isset($groups[$date])) {
        $groups[$date] = [];
        // this will be used to store all the value attributes for this date
        $groups[$date]['values'] = [];
        // this will be used to store all the name attributes for this date
        $groups[$date]['names'] = [];
    }
    // store the next value attributes in that group
    foreach ($element->node as $node) {
        $groups[$date]['values'][] = (int) $node->attributes()['value'];
    }
    // store the next name attributes in that group
    foreach ($element->foo as $foo) {
        $groups[$date]['names'][] = (string) $foo->attributes()['name'];
    }
}

// now we have everything we need to build the result

foreach ($groups as $date => $group) {
    print '
';
    printf('
%s
', date('l', strtotime($date)));
    printf('
%d
', min($group['values']));
    printf('
%d
', max($group['values']));
    foreach ($group['names'] as $name) {
        printf('
%s
', $name);
    }
    print '
';
}


text:
Q: Find the 3rd degree of polynomial having trigonometry as a root I am struggling to solve the problem that asking to find the 3rd degree of polynomial having all coefficients as integers, which satisfying
$f(\cos \frac{\pi}{7})=0$.
I know that I should use the euler's equation, but I don't know how to apply it to this problem.
In detail, I know I should use the fact that $e^{(\frac{\pi i}{7})}$ is the root for $\frac{(x^7+1)}{x+1}$ = $x^6-x^5+x^4-x^3+x^2-x+1 = 0 $, but it is really hard for me to find how to use that fact to solve the problem.
Thank you.

A: MORE DETAILS
You want a relation involving only $\;c:=\cos\left(\frac{\pi}7\right)\,$ the real part of $\,x=e^{i\pi/7}\,$ such that :
$$x^6-x^5+x^4-x^3+x^2-x+1 = 0$$
Divide by $x^3$ to get :
\begin{align}
\tag{1}&\bigl(x^3+x^{-3}\bigr)-\bigl(x^2+x^{-2}\bigr)+\bigl(x^1+x^{-1}\bigr)=1\\
\end{align}
But
\begin{align}
\tag{2}(2\;c)=\left(x+\frac 1x\right)^1&=\bigl(x^1+x^{-1}\bigr)\\
\tag{3}(2\;c)^2=\left(x+\frac 1x\right)^2&=\bigl(x^2+x^{-2}\bigr)+2\\
\tag{4}(2\;c)^3=\left(x+\frac 1x\right)^3&=\bigl(x^3+x^{-3}\bigr)+3\,\bigl(x^1+x^{-1}\bigr)\\
\end{align}
so that everything may be written in function of $\,c\,$ only :

*

*from $(2)$ and $(4)$ deduce $\,\bigl(x^3+x^{-3}\bigr)=(2\;c)^3-3\,(2\;c)\,$,

*from $(3)$ deduce $\,\bigl(x^2+x^{-2}\bigr)$

*from $(2)\ \cdots$

Conclude !

A: A generic overview for other denominators $n\neq 3$ in $\cos (\pi/n)$ is in https://vixra.org/abs/2210.0026 . This includes $8\cos ^3(\pi/7)-4\cos^2(\pi/7)-4\cos(\pi/7)+1=0$.


text:
Q: based on 4 values calculate price elasticity, QTY, and revenue I'm calculating price elasticity, QTY, and revenue. But I don't understand why price point 2 + 1,8 + 1,6 etc are negative values.
Can anyone explain the logic here?
I can forward the Excel file upon request.enter image description here
QTY
-86.358.654.443.600.200.000.000
-86.358.654.443.600.200.000.000
-86.358.654.443.600.200.000.000
1.562.456.412.924.750.000.000.000
-13.353.255.812.646.700.000.000.000
71.629.731.799.382.200.000.000.000
-270.270.514.977.585.000.000.000.000
761.765.243.873.840.000.000.000.000
-1.662.253.556.922.770.000.000.000.000
2.871.577.274.342.580.000.000.000.000
-3.981.673.143.281.680.000.000.000.000
4.465.067.840.296.370.000.000.000.000
-4.059.927.343.261.740.000.000.000.000
2.986.867.970.705.740.000.000.000.000
-1.765.399.328.645.510.000.000.000.000
827.380.774.773.874.000.000.000.000
-300.968.281.915.882.000.000.000.000
82.117.073.933.395.800.000.000.000
-15.872.431.042.918.400.000.000.000
1.953.844.210.962.580.000.000.000
-118.603.147.016.950.000.000.000
578.310.517.566.495.000.000
26.236.668.613.717.600.000
2.382.983.842.389.350.000
314.917.353.258.725.000
53.499.744.800.765.300
10.939.261.673.645.300
2.584.884.413.091.240
686.719.854.185.475
201.116.229.122.102
63.979.064.267.779
21.857.356.900.984
7.946.865.581.041
3.052.456.630.820
1.231.223.238.734
518.880.593.526
227.504.047.013
103.399.651.713
48.561.519.326
23.502.929.790
11.694.164.596
5.969.228.072
3.120.019.371
1.667.106.690
909.262.048
505.536.076
286.171.975
164.754.648
96.371.998
57.223.141
34.461.869
21.033.946
13.002.073
8.134.545
5.147.814
3.293.373
2.128.943
1.389.904
916.030
609.198
408.660
278.620
249.530
220.440
108.140
53.910
27.292
14.020
7.304
3.857
2.063
1.117
612
339
190
108
62
36
21
12
7
4
3
2
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
Thanks
Thomas


text:
Q: Odata : Get data from Salesforce Using Odata? Is there any way to get Salesforce data (Lead,Contact) using Odata. There are some Application Cloud Drivers, Progress DataDirect Cloud and Skyvia Connect for it. Are they using Normal Rest Api and then converting Data to Odata?

A: Progress DataDirect Cloud exposes the external data sources as standard OData for consumption by Salesforce Connect independent of Salesforce REST APIs. For example, if it's an on-premises hadoop cluster or SQL database, the service will translate database queries into OData and work with, or independently, from your firewall configuration. Beyond the OData standard, it supports specific features optimized for Salesforce Connect to optimize access to external sources.


text:
Q: Matching a range of dates to a single categorical variable I am a beginner using R, and I am wanting to create a dataframe that stores a range of dates to their respective classified time period.
paleo.periods <- c("Paleoindian","Early Paleoindian", "Middle Paleoindian", "Late Paleoindian", "Archaic","Early Archaic", "Middle Archaic","Late Archaic","Woodland","Early Woodland","Middle Woodland","Late Woodland","Late Prehistoric")

paleo.dates <- c(c(13500,8000), c(13500,10050) ,c(10050,9015), c(9015,8000), c(8000,2500), c(8000,5500), c(5500,3500), c(3500,2500), c(2500,1150), c(2500,2000), c(2000,1500), c(1500,1150), c(1150,500))

I would like for the arrangement to come out where I can refer to a given time period, ex: "Late Woodland", and get the associated vector of it's beginning and end timeframes, ex: (1500,1150)
I tried simply doing this by
paleo.seg <- data.frame(paleo.periods,paleo.dates)

however, this creates 3 variables: a list of the periods, a list of the vectors, and paleo.dates. I am not sure why it is creating 3 variables, as I'd like it to be only 2: paleo.periods and paleo.dates. I would also like to refer to them as paleo.seg$paleo.periods which will return the list of periods (and later use this to somehow refer to the periods individually), same with the dates.
Essentially I would like my dataframe to look a bit like this:
paleoperiods           paleodates
"Late Woodland"    1500,1100

Therefore I could look specifically for the string "Late Woodland" and find the vector dates. I tried doing this on my current data.frame, and
"Woodland" %in% paleo.seg returns false. So I feel like I am misunderstanding how to build a proper dataframe, as well as being able to match one categorical variable to two dates.

A: There are a few ways that you could go about this depending on your reasoning about what you want to do with your dataframe. My recommendation would actually be to split the dates column into two separate date columns(start and end I believe, from your description). This way you could calculate or use rules based on the dates. I've found this useful when looking at data, as it gives you the ability to filter based on two different aspects of the date. If you would like them to be in the same column, you could make the dates a character in order to have them in the same column. However, this approach does have drawbacks in terms of using it for exploratory data analysis. An example of this would be:
paleo.dates <- c("13500,8000","13500,10050","10050,9015","9015,8000", ...)

This would allow you to look up Late Woodland and get "1500,1100", but you wouldn't be able to search for periods occurring after 1500 if that type of analysis is something you would be doing at a later point.


text:
Q: Find top 500 oldest files How can I find top 500 oldest files?
What I've tried:
find /storage -name "*.mp4" -o -name "*.flv" -type f | sort | head -n500

A: Find 500 oldest files using GNU find and GNU sort:
#!/bin/bash
typeset -a files
export LC_{TIME,NUMERIC}=C
n=0

while ((n++ < 500)) && IFS=' ' read -rd '' _ x; do
    files+=("$x")
done < <(find /storage -type f \( -name '*.mp4' -o -name '*.flv' \) -printf '%T@ %p\0' | sort -zn)

printf '%q\n' "${files[@]}"

Update - some explanation:
As mentioned by Jonathan in the comments, the proper way to handle this involves a lot of non-standard features which allows producing and consuming null-delimited lists so that arbitrary filenames can be handled safely.
GNU find's -printf produces the mtime (using the undocumented %T@ format. My guess would be that whether or not this works depends upon your C library) followed by a space, followed by the filename with a terminating \0. Two additional non-standard features process the output: GNU sort's -z option, and the read builtin's -d option, which with an empty option argument delimits input on nulls. The overall effect is to have sort order the elements by the mtime produced by find's -printf string, then read the first 500 results into an array, using IFS to split read's input on space and discard the first element into the _ variable, leaving only the filename.
Finally, we print out the array using the %q format just to display the results unambiguously with a guarantee of one file per line.
The process substitution (<(...) syntax) isn't completely necessary but avoids the subshell induced by the pipe in versions that lack the lastpipe option. That can be an advantage should you decide to make the script more complicated than merely printing out the results.
None of these features are unique to GNU. All of this can be done using e.g. AST find(1), openbsd sort(1), and either Bash, mksh, zsh, or ksh93 (v or greater). Unfortunately the find format strings are incompatible.

A: The following finds the oldest 500 files with the oldest file at the top of the list:
find . -regex  '.*.\(mp4\|flv\)' -type f -print0 | xargs -0 ls -drt --quoting-style=shell-always 2>/dev/null | head -n500

The above is a pipeline.  The first step is to find the file names which is done by find.  Any of find's options can be used to select the files of interest to you.  The second step does the sorting.  This is accomplished with xargs passing the file names to ls with sorts on time in reverse order so that the oldest files are at the top.  The last step is head -n500 which takes just the first 500 file names.  The first of those names will be the oldest file.
If there are more than 500 files, then head terminates before ls.  If this happens, ls will issue a message: terminated by signal 13.  I redirected stderr from the xargs command to eliminate this harmless message.
The above solution assumes that all the filenames can fit on one command line in your shell.


text:
Q: Difference between "public relations" and "human relations" The other day I was looking at the various job positions in the newspaper just for my knowledge and found that a few companies had public relations officer post and some had human relations officer post.
What is the difference between the two? Why give a different name when they seem the same?

A: HR stands for human resources, not human relations.
HR deals with staffing issues. PR (public relations) deals with image issues.

A: HR (HRD) - Human Resources Department. It is responsible for the staff (employee) management in an organisation. Example responsibilities: Recruiting, Lay-offs, Pay-Packets etc.
PR (PRM) - Public Relations Management. It comprises of all activities done to keep the public involved in the company. PR used to be the 'point of contact' between the (general) public (esp. Media) and the organisation. However, modern PR has donned a more of marketing role. For example, most celebrities hire PR fellows who in turn (through their contacts) get them published in various media, arrange for entry in privileged parties, sustaining a large public interest in them through various means (including fabricating controversies :P ) etc.

A: Public relations concern dealing with "people" in the ABSTRACT. That is, putting out news (in the most positive possible light) about a company to create a positive impression of the company among a group of people outside the company (who are not necessarily identifiable).
Human relations (or human resources) concern dealing with people IN THE FLESH. That is, with hiring, training, compensation and promotion of particular INDIVIDUALS, specifically those within the company.


text:
Q: Sorting multiple values based on how frequent they appear I am retrieving data from a database using php / sql. The sql code that retrieves data is
SELECT user_id
FROM table
WHERE (field_id = 16 AND value BETWEEN 1 AND 100)
OR (filed_id = 17 AND value BETWEEN 1 AND 100)

(the or's would be multiple or 1, or 0)
And it would return an array of values similar to
$arry = {4,1,5,4,1,5}

something like that. If I change the query to something like
SELECT user_id
FROM table
WHERE (field_id = 16 AND value BETWEEN 1 AND 100)
OR (filed_id = 17 AND value BETWEEN 1 AND 100)
GROUP BY user_id

It would return something like
$arry = {1,4,5}

How can I organize the results so that the most frequent user_id which appears comes first in descending order?
SELECT count(user_id) AS cnt, user_id
FROM table
WHERE (field_id = 16 AND value BETWEEN 1 AND 100)
OR (filed_id = 17 AND value BETWEEN 1 AND 100)
ORDER BY cnt

I tried a query similar to that, but it screws up all the results.

A: SELECT user_id,COUNT(*)
FROM table
WHERE (field_id = 16 AND value BETWEEN 1 AND 100)
OR (filed_id = 17 AND value BETWEEN 1 AND 100)
GROUP BY user_id
ORDER BY COUNT(*) DESC


text:
Q: Android app crashes on startup if I'm signed into a test account under alpha testing? I've created an Android game using the Unity game engine. I utilize leaderboards/achievements and in-app purchases for my app.
To test the IAPs, I had to submit and publish my app to alpha in the Google Play Developer Console. It then asks me to setup close or open alpha testing. I chose close testing and entered my test account details.
In addition to that, I've also set up the same test account under Settings>Account Details>License Testing and GameServices>Testing Access in the Developer Console as well.
Now when I deploy my app to my device, the app crashes on startup everytime. This happens if I'm signed in to my test account on the device. I get a notification saying "Unfortunately (app name) has stopped" after it launches.
Now the weird thing is that if I'm signed in on another Google account on my device, the app DOES NOT crash on startup.
This only started to happen when I added my test account as part of the close alpha testing group.
I have now removed my test account from the close alpha group and I'm currently waiting for the changes to be approved by Google Play and see if my test account would still cause my app to crash.
I don't have the slightest clue on why this is happening. I have published 2 Android apps before and didn't have this problem. But that was before Google implemented the close or open alpha testing feature. I didn't have to deal with that feature back then.
Anyone know what's going on?

A: Thanks for the comments. I think I found the culprit already. When I removed my test account from the closed alpha test group, my app doesn't crash anymore on startup. This leads me to think that there's something wrong with alpha test accounts and their communication with Google Play Services (Play Games and Billing for me) because my app tries to sign in to Google Play (for leaderboard access) and requests the IAPs on startup.
Hope this helps other devs who might face this issue.


text:
Q: Modifying condition for PL/SQL procedure I have a PL/SQL procedure for deleting records corresponding to a field having NULL value. Am able to achieve this by the below query.
set serveroutput on;

begin
    dbms_output.put_line('Execution started');

    for rec in (
        select name from employee where emp_id is null
        and location = 'SITE_A'
    )
    loop
        delete from employeedetails@sitea where name = rec.name;
        dbms_output.put_line('name '|| rec.name ||' deleted');
    end loop;

    dbms_output.put_line('Execution completed');
end;
/

set serveroutput off;

I am running the for loop query from one database and deleting the records  in another database (  sitea  ) using a database link.
I need to add a condition like, if the  name=rec.name  is not returning any records to be deleted,then dbms_output.put_line('No records to be deleted');
Is there a comfortable way to achieve it ?

A: You can use the sql%rowcount implicit cursor attribute to see how many rows were affected by a DML statement; that works across a database link as well as locally:
if sql%rowcount = 0 then
  dbms_output.put_line('No records to be deleted');
else
  dbms_output.put_line('name '|| rec.name ||' deleted');
end if;

You can include it in the messages too:
if sql%rowcount = 0 then
  dbms_output.put_line('name '|| rec.name ||': no records to be deleted');
else
  dbms_output.put_line('name '|| rec.name ||': '|| sql%rowcount ||' record(s) deleted');
end if;

Then you'll see something like:
Execution started
name B: 1 record(s) deleted
name C: no records to be deleted
Execution completed

PL/SQL procedure successfully completed.

As name probably isn't unique you could encounter the same value twice as you go through your loop; in which case the first delete will find multiple rows and the second delete will find none. You could avoid the second one by adding distinct to your cursor query.
And if you didn't want to see which names did and did not have remote data to delete then you could use a much simpler single delete, with no loop or PL/SQL, but it seems like this is an exercise anyway...


text:
Q: How to get data shown on rails console into my views in rails I am new to rails and am having trouble showing what I get in my rails console to my views pages.
In my rails console, I will type c = Course.find(21).
Then when I put c.scores.all in my console I get all of the scores columns that are associated with the Course model, with the id of 21.
However, I cannot do the same thing in the controller or the views. I tried putting the same information but it does not find the scores that are associated with the courses_id in the course/show page. I know this is really simple but cannot seem to get this to work. Thanks

A: Without the code of your controller and your view, I can only guess the cause of your problem.
The code c.scores.all returns an ActiveRecord::Relation, not an array of models.
A relation is lazily loaded, which means it does not query DB until you retrieve data from it (typically by calling to_a or each on it). This may be the cause of your problem.
Rails console and irb work, by default, in inspect mode, which means whenever you enter an expression, Rails console automatically calls inspect on the return value of that expression and prints the result. ActiveRecord::Relation#inspect internally calls to_a thus accesses DB, so you can see your data in Rails console.


text:
Q: What is the best implementation for an application that regards open edits by users? I am currently developing a web application that users can upload movies/books information to a large database. I am trying to create a system where there are no duplicates in titles. I have a coupe of options but I do not think I am experienced enough to make the proper one:
Options:

*

*make it so once a user uploads the book's info and pictures..then other users will be able to edit this openly.

*upload every single possible movie myself or

*allow users to upload multiple of the same ones.

Problems:

*

*this problem will involve users who vandalize

*this seems almost impossible

*duplicate of data

Is there anyone who've encountered this problem before who can think of a better solution for this?
This application is built using PHP/MySQL.

A: You could create a Wiki-style database, where users are free to add and edit details but you appoint moderators that can approve or disapprove of added / edited details.
Score every member that uploads good information and after they have reached a certain score, they can edit information freely without moderators checking it. Give vandals a negative score and prevent anyone with a score below a certain point to add information.

A: Ok so i did some thinking. There is this site I like, they use a kind of voting system or edits. On this particular site there are large lists of 'movies' and the movies are poorly documented. People can submit the names or 'actors' or 'actresses' that star in these films. After a certain number of people make the same suggestions, they are committed. The site I am referencing is pornhub.com
If you go to watch a 'film' on there, under the flash video there is an option to 'Add a Pornstar'. I was thinking you could utilize this same concept of user blind-voted edits/comments. Then you can use option 1 without problem 1.

A: There are two general things that could help you :

*

*Frameworks. There are a lot of good frameworks which have multiple user input control functions. I suggest trying out Zend or CodeIgniter. Zend may be more complicated on the other hand it is a bit more flexible. CodeIgniter has a larger community and is a bit simpler, however lacks flexibility and sometimes speed.

*CMSs. What you need is not a standard  so I suggest trying out Drupal it is somtimes called a CMS/Framework so it is very flexible and it has a role and permissions system which should meet your needs, if not you can extend it.

In my personal view Drupal is the way to go, it will save you a lot of time. Good luck.


text:
Q: How to replace Visual Studio's integrated help with a browser-based web search?
Possible Duplicate:
Load search URL in browser from Visual Studio

Pressing F1 in VS launches Microsoft's Document Explorer. How can I open the help results in my web browser instead?

A: Have a look in the Options, under Help / Online.
There you can select
- try online first, then local
And you can select multiple providers to search in.


text:
Q: Spring Boot Could not find acceptable representation for XML responses I found multiple solutions for this exception and causes but none worked and it seems illogical.
I have REST service class as the following
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.MediaType;

import java.util.Map;
@RestController
public class UserRestService {

    @RequestMapping(value = "/userLogin", method = RequestMethod.POST, produces = MediaType.APPLICATION_XML_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody ResponseEntity<Map> login(@RequestBody Map<String, String> name) {
        ResponseEntity<Map> res = null;
        name.values().forEach(System.out::println);
        return new ResponseEntity<Map>(name, HttpStatus.OK);
    }
}

As you see, I try to create a POST request with request body as JSON and response as XML, printing the request in the process. It's just simple example but while the request is printed correctly which means it's been received and marshaled to Map. However the response status is 406 (not acceptable)
Exception in the log is
John
30
null
2018-08-16 14:05:48.440  WARN 22820 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
2018-08-16 14:05:48.481  WARN 22820 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

the Request Header simply has
Accept:*/*
Content-Type:application/json

POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example.cms</groupId>
    <artifactId>business</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>2.3.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.3.0.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Noting that adding the following dependency solves the problem
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

Request Body { "name":"John", "age":30, "car":null }
Response if MediaType.APPLICATION_JSON_UTF8_VALUE is used for produces attribute of @RequestMapping is { "name":"John", "age":30, "car":null }
Response if MediaType.APPLICATION_XML_VALUE is used for produces attribute of @RequestMapping & jackson-dataformat-xml used is
<Map>
    <name>John</name>
    <age>30</age>
    <car/>
</Map>

Why using JAXB fails in this ?
Update 01
OK as @Simon comment, I created a sample object (class) to get as request and response with it. Same exact effect. Here is the updated code
public class MockupResponse {

    private String name;
    private Integer age;
    private String car;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getCar() {
        return car;
    }

    public void setCar(String car) {
        this.car = car;
    }

@Override
public String toString() {
        StringBuffer sb = new StringBuffer();
        if (null != name)
            sb.append("Name: " + name + "\n");
        if (null != age)
            sb.append("Age: " + age + "\n");
        if (null != car)
            sb.append("Car: " + car + "\n");

        return sb.toString();
}
}

Service
@RequestMapping(value = "/userLogin", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody ResponseEntity<MockupResponse> login(@RequestBody MockupResponse sample) {
        System.out.println(sample);

        return new ResponseEntity<MockupResponse>(sample, HttpStatus.OK);
    }

A: Add @XmlRootElement to the class that must be serialized by JAXB like
@XmlRootElement
public class MockupResponse {

    private String name;
    private Integer age;
    private String car;
...
}

Then the XML serialization works.
Read more about that in the Spring Doc:
https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html
If you use Java 9 and later you must add JAXB and javax.activation to the dependencies:
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-core</artifactId>
        <version>2.3.0.1</version>
    </dependency>
    <dependency>
        <groupId>com.sun.xml.bind</groupId>
        <artifactId>jaxb-impl</artifactId>
        <version>2.3.0.1</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>


text:
Q: To evaluate a line integral along the curve of intersection of the cylinder $x^2+y^2=a^2$ and the plane $x/a+z/b=1$ Let $C$ be the curve  of intersection of the cylinder $x^2+y^2=a^2$ and the plane $\frac{x}{a}+\frac{z}{b}=1$; how to evaluate $$\int_C (y-z) dx+(z-x)dy+(x-y)dz?$$ I know that the parametrization for $C$ is $(a\cos t, a\sin t,b-b\cos t)$; but I can't determine the limits for $t$ as I can't visualize the intersection curve. Should I use Stoke's theorem? But then I also can't find the relevant surface.

A: You can check why the range for $t$ I provided in my comment will work by checking values of $t$ within that interval - what do you get when $t=0$? $t=\dfrac{\pi}{2}$? and so on.
The integral becomes
$$\begin{align*}I&=\oint_C(y-z)\,\mathrm{d}x+(z-x)\,\mathrm{d}y+(x-y)\,\mathrm{d}z\\[1ex]
&=\int_0^{2\pi}\bigg((a\sin t-b+b\cos t)(-a\sin t)+(b-b\cos t-a\cos t)(a\cos t)+(a\cos t-a\sin t)(b\sin t)\bigg)\,\mathrm{d}t\\[1ex]
&=\int_0^{2\pi}\bigg(-a^2-ab+ab\cos t+ab\sin t\bigg)\,\mathrm{d}t\end{align*}$$

A:
but I can't determine the limits for $t$ as I can't visulaize the
  intersection curve , what shape is it

The cylinder is symmetric around the $z$ axis, with radius $a$.
The plane has a normal vector $n = (1/a, 0, 1/b)$ in the $x$-$z$-plane, it is affine not needing to contain the origin. Distance from the origin is
$1/\lVert n \rVert = ab/\sqrt{a^2+b^2}$.
Intersection curve seems to be an ellipse within the intersection plane.
For the projection in the $y$-$z$-plane we have:
$$
a^2 =
y^2 + \left(a - \frac{a}{b} z\right)^2 =
y^2 + \left(\frac{a(z-b)}{b}\right)^2 \iff \\
\left(\frac{y}{a}\right)^2 + \left(\frac{z-b}{b}\right) = 1
$$


text:
Q: limsup of intersection of events as a subset of intersection of limsups Let $A_1, A_2, \ldots$ and $B_1, B_2, \ldots$ be two sequences of events in some probability triple $(\Omega, \mathcal{F}, \mathbf{P})$. Now, it is true that $\left(\limsup_n A_n\right) \cap \left(\limsup_n B_n\right) \supseteq \limsup_n (A_n \cap B_n)$, and I can think of many different cases where this relation holds true for equality (e.g., let $A_n = B_n$, or $A_n = B_n^c$, or $B_n = \emptyset$, or $B_n = \Omega$). However, I cannot think of any case where $\left(\limsup_n A_n\right) \cap \left(\limsup_n B_n\right) \supset \limsup_n (A_n \cap B_n)$ holds for strict inclusion.
My proof for the relation is simple. Since $A_n \cap B_n \subseteq A_n$ and $A_n \cap B_n \subseteq B_n$, then we can perform some set algebra as follows:
$$\bigcup_{k=n}^\infty (A_k \cap B_k) \subseteq \bigcup_{k=n}^\infty A_k$$
$$\bigcap_{n=1}^\infty \bigcup_{k=n}^\infty (A_k \cap B_k) \subseteq \bigcap_{n=1}^\infty \bigcup_{k=n}^\infty A_k$$
Then we can use the same logic for $B_n$, and come to the conclusion as stated in the beginning.

A: Just take
\begin{align}
\emptyset &\not= A_1 = B_2 = A_3 = B_4 = ...\\
        \emptyset &= B_1 = A_2 = B_3 = A_4 = ...
\end{align}