text:
Q: sparklyr: how to take a balanced sample across groups I want to sample n rows from each of the classes of my Spark DataFrame in sparklyr.
I understand that the dplyr::sample_n function can't be used for this (Is sample_n really a random sample when used with sparklyr?) so I have used the sparklyr::sdf_sample() function. The problem with this is that I can't sample by group i.e get 10 observations from each class, I can only specify the fraction of the entire dataset to sample.
I have a workaround to use sdf_sample() on each group individually in a loop, but since the function does not return an exact sample size, this is still not ideal.
R code for workaround:
library(sparklyr)
library(dplyr)

sc <- spark_connect(master = "local", version = "2.3")

# copy iris to our spark cluster
iris_tbl <- copy_to(sc, iris, overwrite = TRUE)

# get class counts
class_counts <- iris_tbl %>% count(Species) %>%
  collect()
#  Species        n
#  <chr>      <dbl>
#1 versicolor    50
#2 virginica     50
#3 setosa        50

# we want to sample n = 10 points from each class
n <- 10

sampled_iris <- data.frame(stringsAsFactors = F)
for( i in seq_along(class_counts$Species)){

  my_frac <- n / class_counts[[i, 'n']]
  my_class <- class_counts[[i, 'Species']]

  tmp <- iris_tbl %>%
    filter(Species == my_class) %>%
    sdf_sample(fraction = my_frac) %>%
    collect()

  sampled_iris <- bind_rows(sampled_iris, tmp)
}

We don't get exactly 10 samples from each class:
# new counts
sampled_iris %>% count(Species)

#Species        n
#  <chr>      <int>
#1 setosa         7
#2 versicolor     9
#3 virginica      6

I'm wondering if there's a better way to get a balanced sample across groups using sparklyr? Or even using a sql query which I can pass directly to the cluster using DBI::dbGetQuery()?

A:
I can't sample by group

As long as the grouping column is string (that's limitation of sparklyr type mapping) that part can easily handled using DataFrameStatFunctions.sampleBy:
spark_dataframe(iris_tbl) %>%
  sparklyr::invoke("stat") %>%
  sparklyr::invoke(
    "sampleBy",
    "Species",
    fractions=as.environment(list(
      "setosa"=0.2,
      "versicolor"=0.2,
      "virginica"=0.2
    )),
    seed=1L
  ) %>% sparklyr::sdf_register()

However no distributed and scalable method will give you "exact sample size". It is possible to use hacks such as:
iris_tbl %>%
  group_by(Species) %>%
  mutate(rand = rand()) %>%
  arrange(rand, .by_group=TRUE) %>%
  filter(row_number() <= 10) %>%
  select(-rand)

but such methods, which depend on window functions, are highly sensitive to skewed data distributions, and in general don't scale well.
If samples are small you can push this a bit further, but oversampling first (using the first method) and then taking exact samples (using the second method), but if your data is large enough to be processed with Spark, small fluctuations shouldn't really matter.


text:
Q: `this` variable is not accessible outside js methods or packages in angular2 typescript this variable is not accessible outside js methods or packages in angular2 typescript.
public mousekeyAction() {
            var mc=0,kc=0;
        gkm.events.on('key.pressed', function (data) {
          this.keyscount= kc++;
          console.log(this.keyscount);
        });
        // Listen to all mouse events (click, pressed, released, moved, dragged)
        gkm.events.on('mouse.*', function (data) {
            this.mousecount=mc++;
           console.log(this.mousecount);
        });
    }

A: you have to use fat arrow as function/callback instead of simple function. this will maintain the scope of this even outside the function too.
Use your function like this :-
public mousekeyAction() {
        var mc=0,kc=0;
        gkm.events.on('key.pressed', (data) => {
            this.keyscount= kc++;
            console.log(this.keyscount);
        });
        // Listen to all mouse events (click, pressed, released, moved, dragged)
        gkm.events.on('mouse.*', (data) => {
            this.mousecount=mc++;
            console.log(this.mousecount);
        });
    }

for more info refer here

*

*https://basarat.gitbooks.io/typescript/docs/arrow-functions.html

A: Assign this to another variable as below
public mousekeyAction() {
  var mc = 0,
    kc = 0,
    self = this;
  gkm.events.on('key.pressed', function(data) {
    self.keyscount = kc++;
    console.log(self.keyscount);
  });
  // Listen to all mouse events (click, pressed, released, moved, dragged)
  gkm.events.on('mouse.*', function(data) {
    self.mousecount = mc++;
    console.log(self.mousecount);
  });
}

Since callback context is different from context of expected this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: VBA Excel - Avoid not exsisting rangenames when copy/paste data from one rangename to another rangename From cells in a sheet (Sheets("Omrnavne")) with several Range names written below each other the code has to find the first value (range name) written, find and select the actual range with this name on Sheets("Specifikationer"), copy data, go to the next value on Sheets("Omrnavne"), find the actual range, paste values and start over.
Problem: if there is written a range name on Sheets("Omrnavne") that don't exist as range name how do one skip this?
With the following code: If Range(whatToFind) Is Nothing Then
I get the error:

Run-time error '1404': Method 'Range' of object'_Global' failed

when searching for a rangename that dosen't exist.
I've tried for hours but with no success. Please help - thanks.
The code is:
Sub Test1()
    Dim whatToFind As String
    Sheets("Omrnavne").Select

    ' Select first line of data*.
    Range("a1").Select

    ' Set Do loop to stop when an empty cell is reached.
    Do Until IsEmpty(ActiveCell)
        whatToFind = ActiveCell.Value

       'Find rangename, select and copy
        Sheets("Specifikationer").Select
        With Sheets("Specifikationer")
            On Error Resume Next
            On Error GoTo 0

            If Range(whatToFind) Is Nothing Then ' <~~~~ ERROR HERE
                Sheets("Omrnavne").Select
                ActiveCell.Offset(2, 0).Select
                whatToFind = ActiveCell.Value
            Else
                Range(whatToFind).Select
                Selection.Copy
            End If
        End With

        ' Find and select rangename to paste to
        Sheets("Omrnavne").Select
        With Sheets("Omrnavne").Select
             ActiveCell.Offset(1, 0).Select
             whatToFind = ActiveCell.Value
             Sheets("Specifikationer").Select
             Range(whatToFind).Select
             Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                 :=False, Transpose:=False
             Application.CutCopyMode = False
        End With

        ' Step down 1 row from present location.
        Sheets("Omrnavne").Select
        ActiveCell.Offset(1, 0).Select
    Loop

End Sub

A: As you have seen already, the ActiveSheet.Range property returns not Nothing, if the range does not exists. Instead it will produce an error. You can DIM an object variable as Range. This variable is Nothing until it is setted. Then you can try setting this variable to the named range within an error handling block. If the variable is further Nothing after this, then the named range not exists.
Example:
 Dim oRange As Range
 On Error Resume Next
 Set oRange = Range("test")
 On Error GoTo 0
 If oRange Is Nothing Then
  MsgBox "No range named ""test"" present."
 Else
  MsgBox oRange.Address
 End If

Greetings
Axel


text:
Q: The image of a segment is not dense into a square Let $f\colon [0,1]^2 \to \mathbf{R}^2$ a continuous injection such that
$$
f(0,0)=(0,0), f(1,0)=(0,1), f(1,1)=(0,2), f(0,1)=(0,3).
$$
Let $S$ be the closed segment joining $(0,0)$ and $(0,3)$.
Prove that $f^{-1}[S]$ is not dense in $[0,1]^2$.

A: As commented by Clement, if $f^{-1}(S)$ were dense in $[0,1]^2$, it would mean that the image of $f$ is $S$. Since $f$ is continuous and injective, from a compact space to a Hausdorff space, we would actually get that $f$ is a homeomorphism.
Now we just need to prove that the square is not homeomorphic to a segment. For every point $p\in[0,1]^2$, the space $[0,1]^2\setminus \{p\}$ is connected. This is not the case with the segment.


text:
Q: Does std::optional copy an object containing a std::unique_ptr I'm trying to return a std::optional to an object containing a std::unique_ptr member. However, when I try to change the optional return type to use a reference, I get errors like this:

error: cannot bind non-const lvalue reference of type std::optional<ObjectWithConnection>& to an rvalue of type std::optional<ObjectWithConnection>

Is this the best way to return _aConnection without encountering any copying/latency across the stack frames?
I use references very often, but I've never used std::optional with std::unique_ptr and I'm concerned what it's doing under the hood.
struct ObjectWithConnection
{
    std::unique_ptr<Connection> _aConnection;
};

struct ConnectionsContainer
{
    // If I change return type to reference, get compiler error
    std::optional<ObjectWithConnection> getConnection(const std::string& key)
    {
        auto iter = _connections.find(key);
        if(iter != _connections.end())
        {
            return std::optional<ObjectWithConnection>(std::move(iter->second));
        }

        return std::nullopt;
    }

    std::unordered_map<std::string, ObjectWithConnection> _connections;
}

struct AnotherClass
{
    // If I change return type to reference, get compiler error
    std::optional<ObjectWithConnection> getConnection(const std::string& key)
    {
        return _container.getConnection(key);
    }

    ConnectionsContainer _container;
};

A: There are no std::optional references. A program is ill-formed if it instantiates an optional with a reference type. Alternatively, an optional of a std::reference_wrapper of type T may be used to hold a reference.


text:
Q: SQL equivalent of 'this' ABL statement Someone might understand this ABL statement...
FOR EACH <table> BREAK BY <field as breakgroup>:
   ....
   IF FIRST-OF(<breakgroup>) THEN DO:
       ....
   END.
   ....
   IF LAST-OF(<breakgroup>) THEN DO:
       ....
   END.
   ....
END.

Above code basically loops through individual records in a table and then runs some codes (....) during specific parts of the execution. Interesting to note is the FIRST-OF and LAST-OF statement where the <breakgroup> value changes and is useful for data aggregation.
Does someone know how to implement/replicate the same logic using SQL perhaps with some VBA as well?

A: Firstly, it is worth noting that SQL, contrary to the OpenEdge ABL, is not a 4GL. It's not supposed to 'execute code' per se, so you will have to use another programming language to execute SQL statements against a Database, retrieve the selected records and then manipulate them with whatever language you might be using.
To get the equivalent of an ABL FIRST-OF or LAST-OF statement, the SQL FIRST() and LAST() function will come in handy (First() and Last() explain those.)
Basically, that means that you will have to do at least three different SQL Select statements I think, on to select all the table entries you want, one to select the first one of a given 'group' (a group, after all, is just a subselection of entries that fulfill certain criteria) and one to select the last one of such a group. For Example
SELECT LAST(CustomerType) WHERE CustomerType = "ValuedCustomer"

Now, if you want to use VBA as your programming language, you can execute SQL statements for instance with a command like this:
DoCmd.RunSQL "SELECT LAST(CustomerType) WHERE CustomerType = 'ValuedCustomer'"

Here is the MSDN entry for that command!
Hope that helped!


text:
Q: mariadb galera cluster failed to initialize on debian wheezy I meet some troubles with initiliazing a Galera cluster, the start of 2nd node always failed, without error message in log.
I have two nodes for the moment, i will install the third later. Here are my configuration
node1 : 192.168.0.21 db01
node2 : 192.168.0.22 db02
both /etc/hosts are field with the hostnames entries.
My galera.cnf looks like this on both nodes :
[mysqld]
#mysql settings
binlog_format=ROW
default-storage-engine=innodb
innodb_autoinc_lock_mode=2
query_cache_size=0
query_cache_type=0
bind-address=0.0.0.0
#galera settings
wsrep_provider=/usr/lib/galera/libgalera_smm.so
wsrep_cluster_name="my_wsrep_cluster"
wsrep_cluster_address="gcomm://192.168.0.21,192.168.0.22"
wsrep_node_address="192.168.0.21" # 192.168.0.22 on db02
wsrep_node_name="db01" # db02 on db02 server
 wsrep_sst_method=rsync
log-error=/var/log/mysql/error.log

I can start service on db01 with this command no trouble :
    service mysql start --wsrep-new-cluster
But when i start db02 with service mysql start i have a failed message. And the service didn't listen on port 3306 on DB02. Here are my logs which said than db02 detect the cluster, detect db01 , and need to synchronize, but the synchronisation doesn't seems to start....
161009 13:33:02 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
161009 13:33:02 mysqld_safe WSREP: Running position recovery with --log_error='/var/lib/mysql/wsrep_recovery.7VTkrM' --pid-file='/var/lib/mysql/db02-recover.pid'
161009 13:33:02 [Note] /usr/sbin/mysqld (mysqld 5.5.52-MariaDB-1~wheezy-wsrep) starting as process 14839 ...
161009 13:33:04 mysqld_safe WSREP: Recovered position f89d319e-8e08-11e6-8b25-ebe3bbf9c45b:2
161009 13:33:04 [Note] WSREP: wsrep_start_position var submitted: 'f89d319e-8e08-11e6-8b25-ebe3bbf9c45b:2'
161009 13:33:04 [Note] /usr/sbin/mysqld (mysqld 5.5.52-MariaDB-1~wheezy-wsrep) starting as process 14890 ...
161009 13:33:04 [Note] WSREP: Read nil XID from storage engines, skipping position init
161009 13:33:04 [Note] WSREP: wsrep_load(): loading provider library '/usr/lib/galera/libgalera_smm.so'
161009 13:33:04 [Note] WSREP: wsrep_load(): Galera 25.3.17(r3619) by Codership Oy <info@codership.com> loaded successfully.
161009 13:33:04 [Note] WSREP: CRC-32C: using hardware acceleration.
161009 13:33:04 [Note] WSREP: Found saved state: f89d319e-8e08-11e6-8b25-ebe3bbf9c45b:-1
161009 13:33:04 [Note] WSREP: Passing config to GCS: base_dir = /var/lib/mysql/; base_host = 192.168.0.22; base_port = 4567; cert.log_conflicts = no; debug = no; evs.auto_evict = 0; evs.delay_margin = PT1S; evs.delayed_keep_period = PT30S; evs.inactive_check_period = PT0.5S; evs.inactive_timeout = PT15S; evs.join_retrans_period = PT1S; evs.max_install_timeouts = 3; evs.send_window = 4; evs.stats_report_period = PT1M; evs.suspect_timeout = PT5S; evs.user_send_window = 2; evs.view_forget_timeout = PT24H; gcache.dir = /var/lib/mysql/; gcache.keep_pages_size = 0; gcache.mem_size = 0; gcache.name = /var/lib/mysql//galera.cache; gcache.page_size = 128M; gcache.size = 128M; gcomm.thread_prio = ; gcs.fc_debug = 0; gcs.fc_factor = 1.0; gcs.fc_limit = 16; gcs.fc_master_slave = no; gcs.max_packet_size = 64500; gcs.max_throttle = 0.25; gcs.recv_q_hard_limit = 9223372036854775807; gcs.recv_q_soft_limit = 0.25; gcs.sync_donor = no; gmcast.segment = 0; gmcast.version = 0; pc.announce_timeout = PT3S; pc.checksum = false; pc.ignore_quorum = false;
161009 13:33:05 [Note] WSREP: Service thread queue flushed.
161009 13:33:05 [Note] WSREP: Assign initial position for certification: 2, protocol version: -1
161009 13:33:05 [Note] WSREP: wsrep_sst_grab()
161009 13:33:05 [Note] WSREP: Start replication
161009 13:33:05 [Note] WSREP: Setting initial position to f89d319e-8e08-11e6-8b25-ebe3bbf9c45b:2
161009 13:33:05 [Note] WSREP: protonet asio version 0
161009 13:33:05 [Note] WSREP: Using CRC-32C for message checksums.
161009 13:33:05 [Note] WSREP: backend: asio
161009 13:33:05 [Note] WSREP: gcomm thread scheduling priority set to other:0
161009 13:33:05 [Note] WSREP: restore pc from disk successfully
161009 13:33:05 [Note] WSREP: GMCast version 0
161009 13:33:05 [Note] WSREP: (def7d829, 'tcp://0.0.0.0:4567') listening at tcp://0.0.0.0:4567
161009 13:33:05 [Note] WSREP: (def7d829, 'tcp://0.0.0.0:4567') multicast: , ttl: 1
161009 13:33:05 [Note] WSREP: EVS version 0
161009 13:33:05 [Note] WSREP: gcomm: connecting to group 'my_wsrep_cluster', peer '192.168.0.21:,192.168.0.22:'
161009 13:33:05 [Note] WSREP: (def7d829, 'tcp://0.0.0.0:4567') connection established to def7d829 tcp://192.168.0.22:4567
161009 13:33:05 [Warning] WSREP: (def7d829, 'tcp://0.0.0.0:4567') address 'tcp://192.168.0.22:4567' points to own listening address, blacklisting
161009 13:33:05 [Note] WSREP: (def7d829, 'tcp://0.0.0.0:4567') connection established to def7d829 tcp://192.168.0.22:4567
161009 13:33:05 [Note] WSREP: (def7d829, 'tcp://0.0.0.0:4567') connection established to 51e5ab0b tcp://192.168.0.21:4567
161009 13:33:05 [Note] WSREP: (def7d829, 'tcp://0.0.0.0:4567') turning message relay requesting on, nonlive peers:
161009 13:33:05 [Note] WSREP: declaring 51e5ab0b at tcp://192.168.0.21:4567 stable
161009 13:33:05 [Note] WSREP: re-bootstrapping prim from partitioned components
161009 13:33:05 [Note] WSREP: view(view_id(PRIM,51e5ab0b,19) memb {
        51e5ab0b,0
        def7d829,0
} joined {
} left {
} partitioned {
})
161009 13:33:05 [Note] WSREP: save pc into disk
161009 13:33:05 [Note] WSREP: clear restored view
161009 13:33:06 [Note] WSREP: gcomm: connected
161009 13:33:06 [Note] WSREP: Changing maximum packet size to 64500, resulting msg size: 32636
161009 13:33:06 [Note] WSREP: Shifting CLOSED -> OPEN (TO: 0)
161009 13:33:06 [Note] WSREP: Opened channel 'my_wsrep_cluster'
161009 13:33:06 [Note] WSREP: Waiting for SST to complete.
161009 13:33:06 [Note] WSREP: New COMPONENT: primary = yes, bootstrap = no, my_idx = 1, memb_num = 2
161009 13:33:06 [Note] WSREP: STATE EXCHANGE: Waiting for state UUID.
161009 13:33:06 [Note] WSREP: STATE EXCHANGE: sent state msg: 2528a615-8e14-11e6-9e93-ab2afde28393
161009 13:33:06 [Note] WSREP: STATE EXCHANGE: got state msg: 2528a615-8e14-11e6-9e93-ab2afde28393 from 0 (db01)
161009 13:33:06 [Note] WSREP: STATE EXCHANGE: got state msg: 2528a615-8e14-11e6-9e93-ab2afde28393 from 1 (db02)
161009 13:33:06 [Warning] WSREP: Quorum: No node with complete state:

        Version      : 4
        Flags        : 0x3
        Protocols    : 0 / 7 / 3
        State        : NON-PRIMARY
        Desync count : 0
        Prim state   : SYNCED
        Prim UUID    : e33a5f6b-8e12-11e6-9981-7b9a76958a99
        Prim  seqno  : 2
        First seqno  : -1
        Last  seqno  : 3
        Prim JOINED  : 1
        State UUID   : 2528a615-8e14-11e6-9e93-ab2afde28393
        Group UUID   : 20836ccf-8e06-11e6-adf3-5330826fa72d
        Name         : 'db01'
        Incoming addr: '192.168.0.21:3306'

        Version      : 4
        Flags        : 00
        Protocols    : 0 / 7 / 3
        State        : NON-PRIMARY
        Desync count : 0
        Prim state   : NON-PRIMARY
        Prim UUID    : 00000000-0000-0000-0000-000000000000
        Prim  seqno  : -1
        First seqno  : -1
        Last  seqno  : 2
        Prim JOINED  : 0
        State UUID   : 2528a615-8e14-11e6-9e93-ab2afde28393
        Group UUID   : f89d319e-8e08-11e6-8b25-ebe3bbf9c45b
        Name         : 'db02'
        Incoming addr: '192.168.0.22:3306'

161009 13:33:06 [Note] WSREP: Full re-merge of primary e33a5f6b-8e12-11e6-9981-7b9a76958a99 found: 1 of 1.
161009 13:33:06 [Note] WSREP: Quorum results:
        version    = 4,
        component  = PRIMARY,
        conf_id    = 2,
        members    = 1/2 (joined/total),
        act_id     = 3,
        last_appl. = -1,
        protocols  = 0/7/3 (gcs/repl/appl),
        group UUID = 20836ccf-8e06-11e6-adf3-5330826fa72d
161009 13:33:06 [Note] WSREP: Flow-control interval: [23, 23]
161009 13:33:06 [Note] WSREP: Shifting OPEN -> PRIMARY (TO: 3)
161009 13:33:06 [Note] WSREP: State transfer required:
        Group state: 20836ccf-8e06-11e6-adf3-5330826fa72d:3
        Local state: f89d319e-8e08-11e6-8b25-ebe3bbf9c45b:2
161009 13:33:06 [Note] WSREP: New cluster view: global state: 20836ccf-8e06-11e6-adf3-5330826fa72d:3, view# 3: Primary, number of nodes: 2, my index: 1, protocol version 3
161009 13:33:06 [Warning] WSREP: Gap in state sequence. Need state transfer.
161009 13:33:06 [Note] WSREP: Running: 'wsrep_sst_rsync --role 'joiner' --address '192.168.0.22' --datadir '/var/lib/mysql/' --defaults-file '/etc/mysql/my.cnf' --parent '14890''
161009 13:33:08 [Note] WSREP: (def7d829, 'tcp://0.0.0.0:4567') turning message relay requesting off

All networks communication seems OK. I've disable firewall for making my test.
No selinux too.
After try to start node2, i have this connections on db01 :
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      7584/mysqld
tcp        0      0 0.0.0.0:4567            0.0.0.0:*               LISTEN      7584/mysqld
tcp        0      0 192.168.0.21:4567       192.168.0.22:53335      ESTABLISHED 7584/mysqld

I don't know if the rsync service should already listen on the node1, and maybe is why my 2nd node can't sync with the cluster.
So what's my missed up there ? Any errors in my configuration ?
P.S : It's the first time than i'm trying to install this. I followed official man page to install this : https://mariadb.org/installing-mariadb-galera-cluster-on-debian-ubuntu/


text:
Q: Automatically add/remove entry to/from /etc/hosts when enabling/disabling apache2 virtualhost When I create virtualhosts, I almost always forget to add an entry to /etc/hosts until I've attempted to check the site in a web browser and moaned about the oversight. What I want to do is modify a2ensite and a2dissite so that, when run, the following happens:

*

*a2ensite looks for the site entry in /etc/hosts. If it's not found, append the site to 127.0.0.1 entries. Otherwise, do nothing.

*a2dissite looks for the site entry in /etc/hosts. If it's found, remove the site from 127.0.0.1. Otherwise, do nothing.

Either that (which MAMP does on OS X) or add a reminder that I need to edit etc/hosts to get the virtualhost working.
I attempted to edit these files, but, seeing as I don't know PERL, I'm not sure what modifications to make. Also, I'm not sure that editing those files is the best option, in the event that apt overwrites my changes when upgrading apache2.


text:
Q: Aware of differences between people in groups People might claim that a person is something-ist, like ageist. But is there a word to reflect that the person is actually not assuming one group is lesser to another but just aware of differences between them?

A: Pluralism perhaps? That a range of views are considered and respected. Also as a phrase catholic tastes, or liberal, open minded, objectivist.

A:
I'm not against anyone, I'm just _________

Respectful of differences.

A: differentiate -- agreeing with @Josh61 in comments
"I am not ageist, but I can differentiate."


text:
Q: buggy eclipse or not? I have this character creation program I'm working on. I'm using Eclipse and it says there are no problems, but it doesn't read a part of my code. What is going on and how do I fix it?
import java.util.Scanner;

public class Character
{
static Scanner scan = new Scanner(System.in);

public static void main(String[] args)
{

    String play = "yes";
    String play1;
    String play2;
    String play3;

    while (play.equals("yes"))
    {

    System.out.println("Let's create a character!");
    System.out.println("Select a type of headwear. (bald, hair, hat)");

    play1 = scan.next();

    System.out.println("Select a type of shirt. (no sleave, short sleave, long sleave)");

    play2 = scan.next();

    System.out.println("Select a type of pants. (short, medium, long)");

    play3 = scan.next(); \\does not read this part

    System.out.println("Your character:");

code followed by a HUGE nested if block.


text:
Q: How can I extract the Windows 8 OEM product key when I can't boot to Windows I have a Dell Inspiron laptop with preinstalled Windows 8, upgraded to Windows 8.1 which cannot boot now. I am able to get in recovery screen with an USB installation kit.
In order to get the correct, legal Windows ISO I need to provide my product key. I understand that this is saved and connected to the BIOS/Mainboard/UEFI.
If I access the command prompt from the recovery menu, is there any command which provides me my OEM product key?


text:
Q: How can i have 2 input link in DataStage sequence job?
As you can see that when the SEQ_DIM_ACCOUNT Job executed it has 2 conditions with Success and Failure.
I wanted to run execute_command_60 when it's failed, but if execute_command_60 has been run, then i wanted the execute_command_60 to get to the SEQ_DIM_BUSINESS_PARTNER, but when i tried to link the execute_command_60 to SEQ_DIM_BUSINESS_PARTNER it gave me an error "the destination stage cannot support any more input links"
Is there a way to do that?

A: Yes it is possible with the help of a Sequencer stage.
Add that after the Execute_Command and before the SEQ_DIM_BUSINESS_PARTNER. This Stage kan take any number of Input-Links and you only have to specify if All or Any input links have been run to go on


text:
Q: HOW TO PROVIDE DataSource To UiComponent  I've Created A UIcomponent form Having  As Below.
<dynamicRows name="docrows">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="componentType" xsi:type="string">dynamicRows</item>
                    <item name="addButtonLabel" xsi:type="string" translate="true">Add New</item>
                    <item name="additionalClasses" xsi:type="array">
                        <item name="admin__field-wide" xsi:type="boolean">true</item>
                    </item>
                </item>
            </argument>
            <container name="record">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="isTemplate" xsi:type="boolean">true</item>
                        <item name="is_collection" xsi:type="boolean">false</item>
                        <item name="component" xsi:type="string">Magento_Ui/js/dynamic-rows/record</item>
                        <item name="componentType" xsi:type="string">container</item>
                        <item name="positionProvider" xsi:type="string">attachment_options.position</item>
                    </item>
                </argument>
                <field name="path">
                    <argument name="data" xsi:type="array">
                        <item name="config" xsi:type="array">
                            <item name="dataType" xsi:type="string">string</item>
                            <!--<item name="source" xsi:type="string">path</item>
                            <item name="dataScope" xsi:type="string">path</item>-->
                            <item name="label" xsi:type="string" translate="true">Document</item>
                            <item name="visible" xsi:type="boolean">true</item>
                            <item name="formElement" xsi:type="string">fileUploader</item>
                            <item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
                            <item name="previewTmpl" xsi:type="string">Themecafe_ProductAttachment/file-preview</item>
                            <item name="prefixName" xsi:type="string">option.order</item>
                            <item name="prefixElementName" xsi:type="string">option_</item>
                            <!--<item name="required" xsi:type="boolean">false</item>-->
                            <item name="uploaderConfig" xsi:type="array">
                                <item name="url" xsi:type="url" path="attachment/index/upload/field/path"/>
                            </item>
                        </item>
                    </argument>
                </field>
                <field name="doc_title">
                    <argument name="data" xsi:type="array">
                        <item name="config" xsi:type="array">
                            <item name="dataType" xsi:type="string">text</item>
                            <item name="label" xsi:type="string" translate="true">Document Title</item>
                            <item name="formElement" xsi:type="string">input</item>
                            <item name="source" xsi:type="string">doc_title</item>
                            <item name="sortOrder" xsi:type="number">10</item>
                            <!--<item name="prefixElementName" xsi:type="string">txt_</item>-->
                            <item name="dataScope" xsi:type="string">name</item>
                            <item name="notice" xsi:type="string" translate="true">Enter Document Title</item>
                            <item name="validation" xsi:type="array">
                                <item name="required-entry" xsi:type="boolean">true</item>
                            </item>
                        </item>
                    </argument>
                </field>
                <actionDelete>
                    <argument name="data" xsi:type="array">
                        <item name="config" xsi:type="array">
                            <item name="componentType" xsi:type="string">actionDelete</item>
                            <item name="dataType" xsi:type="string">text</item>
                            <item name="fit" xsi:type="boolean">false</item>
                            <item name="label" xsi:type="string">Actions</item>
                            <item name="sortOrder" xsi:type="string">100</item>
                            <item name="additionalClasses" xsi:type="string">data-grid-actions-cell</item>
                            <item name="template" xsi:type="string">Magento_Backend/dynamic-rows/cells/action-delete</item>
                        </item>
                    </argument>
                </actionDelete>
            </container>
        </dynamicRows>

Record Inserted Properly Into Database Tables.
Now When I Edit The Record I want That Amount of DynamicRows Belongs To Record...
i've tried DataProvider But It Just Not Working.
Is that Any Way That i Can Provide DataSource To <DynamicRows> UiComponent Element????


text:
Q: Issue with downloading zip file from internet Issue with downloading zip file from internet
import requests
url = '"file:///Users/rituraj/Downloads/fo01NOV2018bhav.csv%20(1).zip"'

# download the file contents in binary format
r = requests.get(url)

with open("/Users/rituraj/Desktop/bhavcopy/myzip.zip","wb") as zip:
    zip.write(r.content)

Error I get:
    AttributeError Traceback (most recent call last) <ipython-input-17-8b95bb6c7ef7> in <module>
   3 import zipfile 4 ----> 5  urllib.urlretrieve('file:///Users/rituraj/Downloads/fo01NOV2018bhav.csv%20.zip') 6 7
    # download the file contents in binary format AttributeError: module 'urllib' has no attribute 'urlretrieve'


text:
Q: Соответствие хеш-фунций и хеш алгоритмов Уточняю вопрос (видимо либо я вас не понял, либо вы меня). Вот части проги
private void FormLoad(object sender, EventArgs e)
{
    m_MethodCombo.Items.AddRange(new[]{"MD5", "SHA1", "MD160"});
}

private void CalcClick(object sender, EventArgs e)
{
    var method = (string)m_MethodCombo.SelectedItem;
    HashAlgorithm alg;
    switch (method)
    {
        case "MD5" :
            alg = MD5.Create();
            break;
        case "SHA1" :
            alg = SHA1.Create();
            break;
        case "MD160":
          alg = RIPEMD160.Create();
         break;
        default :
            throw new ApplicationException("Unknown hash method");
    }
    m_OutputBox.Lines =
        m_InputBox
            .Lines
            .Select(line => ComputeHash(alg, line))
            .ToArray();
}

Видно, что MD160 соответстует хеш алгоритм RIPEMD160. Требуется, чтобы по элементу из выпадающего списка (например MD160) определить название хеш алгоритма (в данном случае RIPEMD160). То есть в моем классе Algorithm будет конструктор, которому будет передан элемент выпадающего списка, а в конструкторе каким-то образом по этому предаваемомму аргументу будет инициализировано поле типа HashAlgorithm моего класса Algorithm. Вопрос заключается в том каким образом это сделать(как я вижу решение: перебрать все HashAlgorithm-ы и с помощью каких-то их методов получать название хеш-функций им соответствующих, но как их пребрать я не знаю и как получить соотвю им названия хеш-функций)?
а так чтоб по всем существующим алгоритмам проходить(не знаю применим ли тут итерартор)и получать названия соответствующих им функций и сравнивать названия этих хеш функций с выбранным элементом из выпадающего списка, т. е. без создания собсбтвенного словаря нельзя обойтись?
A: походу я вас не примильно понял, но суть словаря остаётся:
допустим вы создаёте класс Algorithm
Добавьте в этот класс приватный словарь Dictionary<string, Func<HashAlgorithm>> d
и в статическом конструкторе класса или где-нить ещё добавьте в этот словать название алгоритмов и сами методы их создания:
d.Add("MD160", RIPEMD160.Create);
d.Add("SHA1", SHA1.Create);
d.Add("MD5", MD5.Create);

теперь конструктор:
public HashAlgorithm AlgWhatYouNeed {get; private set;}//где-то в классе
...
public Algorithm(string algName)
{
    ...
    AlgWhatYouNeed = d[algName]();//вернёт именно тот Create, который вам нужен
    ...
}

в вашем случае:
...
var method = (string)m_MethodCombo.SelectedItem;
Algorithm alg = new Algorithm(method);
...
m_OutputBox.Lines =
    m_InputBox
        .Lines
        .Select(line => ComputeHash(alg.AlgWhatYouNeed, line))
        .ToArray();


text:
Q: Can flags send a post into the Low Quality Posts review queue? I'm trying to clear the last few TODOs in What are the guidelines for reviewing?, so it can eventually go into the FAQ. The section on the Low Quality Posts queue currently says:

Questions appear in the low quality post queue both by algorithm and by flags from users. [TODO remove this todo if you know this information is correct :) ]

I couldn't find any meta post stating that flags can take a post into that queue. New Feature: Community Review Tasks - Now in Beta says just that this task targets posts that we've algorithmically determined to be low quality.
Should we remove the mention to flags, or does anyone know a post to back that information up?

A: As of July 2013, Very Low Quality flags automatically add the flagged post to the Low Quality review queue. As of April 2014, Not An Answer flags do the same.
Each review task requires a minimum number of "Looks OK" reviews (2 on SO, 1 everywhere else) to be dequeued; this number increases by one for each pending flag on the post (edits, closing and deletion dequeue the task in the normal fashion).
Once reviewed, further flags do not re-add the post to the queue. At this point, a moderator will need to intervene. These flags will continue to appear in the moderator queue for this reason.
These changes replace the previous handling of these flags by 10K users. Details can be found here.


text:
Q: Match a vector to a list of vectors I have a list of vectors lis which I need to match to another vector vec
lis <- list(c(2,0,0),c(1,1,0), c(1,0,1), c(0,2,0), c(0,1,1), c(0,0,2))
vec <- c(1,1,0)

So either I would get a logical output
 [1] FALSE  TRUE  FALSE  FALSE  FALSE  FALSE

Or just the position within lis of the match
I've been trying things along these lines:
unlist(lis) %in% vec

but the problem is the position of the number is important i.e. distinguish between c(1,1,0) and c(1,0,1) which I haven't been able to do. I would like to avoid for loops as this needs to be quite efficient (fast).

A: sapply(lis, identical, vec)
# [1] FALSE  TRUE FALSE FALSE FALSE FALSE

Benchmark:
l1 <- list(1:1000)[rep(1, 10000)]
v1 <- sample(1000)
AG <- function() sapply(l1,function(x)all(x==v1))
J <- function() sapply(l1, identical, v1)
microbenchmark(AG(), J())
# Unit: milliseconds
#  expr      min       lq    median        uq      max neval
#  AG() 76.42732 84.26958 103.99233 111.62671 148.2824   100
#   J() 32.14965 37.54198  47.34538  50.93195 104.4036   100

A: sapply(lis,function(x)all(x==vec))
[1] FALSE  TRUE FALSE FALSE FALSE FALSE

A: The answers by @agstudy and @Julius involve a loop over the (long) lis object; here's an alternative assuming that all elements of lis are the same length as vec to allow vector comparison of the unlisted reference
shortloop <- function(x, lst)
    colSums(matrix(unlist(lst) == x, length(x))) == length(x)

which is fast when lis is long compared to vec.
longloop <- function(x, lst)
    sapply(lst, identical, x)

l1 = rep(lis, 1000)
microbenchmark(shortloop(vec, l1), longloop(vec, l1))
## Unit: microseconds
##                expr       min         lq    median         uq      max neval
##  shortloop(vec, l1)   793.009   808.2175   896.299   905.8795  1058.79   100
##   longloop(vec, l1) 18732.338 21649.0770 21797.646 22107.7805 24788.86   100

Interestingly, using for is not that bad from a performance perspective compared to the implicit loop in lapply (though more complicated and error-prone)
longfor <- function(x, lst) {
    res <- logical(length(lst))
    for (i in seq_along(lst))
        res[[i]] = identical(x, lst[[i]])
    res
}
library(compiler)
longforc = cmpfun(longfor)
microbenchmark(longloop(vec, l1), longfor(vec, l1), longforc(vec, l1))
## Unit: milliseconds
##               expr      min       lq   median       uq      max neval
##  longloop(vec, l1) 18.92824 21.20457 21.71295 21.80009 23.23286   100
##   longfor(vec, l1) 23.64756 26.73481 27.43815 27.61699 28.33454   100
##  longforc(vec, l1) 17.40998 18.28686 20.47844 20.75303 21.49532   100


text:
Q: avrdude problem with sck , how to recover locked avr with external clock fuse bit I wrote this code:
#ifndef F_CPU
#define F_CPU 1105920UL
#endif

#include <avr/io.h>
#include <util/delay.h>

int main(void){
    DDRC=0b00100000;
    while(1){
        PORTC=0b00100000;
        _delay_ms(5000);
        PORTC=0b00000000;
        _delay_ms(1000);
    }
}

I programed it in atmega8:
sudo avrdude -c usbasp -p m8 -U flash:w:my.hex

micro programed ,OK, not problem:
i wanted use external crystal; then i connected crystal 11.0592 to pin 10 and 9, and rewrite fuse bit:
sudo avrdude -c usbasp -p m8 -U lfuse:w:0xE0:m

fuse bit rewrite and OK.not problem

now i realized this value 1105920UL is mistake, i edit code and change 1105920UL to 11059200UL ,
but when i programed micro, avrdude get me error:
$sudo avrdude  -c usbasp -p m8 -U flash:w:my.hex

avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

My micro is lock?
or i must rewire sck?
how to i resolve this problem?!?
Thank you

A: Your problem is lfuse:0xE0 means "external clock". You have to use an integrated 8 to 16MHz crystal oscillator and connect it to XTAL1. Your device should be reprogrammable again, at least.
To use a bare crystal, you need an lfuse setting of 0xEE. But you cannot change this now, you had to connect the external oscillator you had selected before first.

A: I programed another micro (atmega16) and use it from external clock,
$regfile = "m16def.dat"
$crystal = 8000000
Config Portd = Output

Do

Toggle Portd.1
Loop

End

Or in codevision (with internal rc 8Mhz) :
while(1){
    PORTD.0 = ! PORTD.0
}

and connect D0 pin (atmega16) to xtal1 of locked micro (atmega8),
and now we can program locked micro and change fuse bit or set to default value.

U1 is atmega16 for use external clock
U2 is atmega8, locked micro, and we want change it fuse bit

thank from @Janka


text:
Q: AngularJS SPA needs to reload to recognize the jwt token in localstorage everything good ?
Today I need your help to solve a token authentication problem (jwt) in my SPA AngularJS application (I use NodeJS in the backend).
When I log in, the credentials are validated in the backend and if I succeed I get a token that is stored in localstorage.
But when I start making my requests to the protected endpoints it is not possible to access, enough to both have to reload the page, which is a tragedy for my SPA AngularJS application.
I have two more verification methods that I use to check the token:
isLoggedIn: that verifies that the token has not been issued.
currentUser: which takes the user data in the payload of the token.
These two methods are called by the navbar controller which updates the links and the user name of the navbar.
One final note is: I have a method: logout, which excludes the token, but even after deleting I have to reload the page, otherwise I can still make requests to protected endpoinds, and having to reload my SPA is a tragedy.
I hope I have given you all the details about the problem,
Best regards

A: *

*If you want that after login token should be go with every request without refreshing your application then you have to create a Interceptor or a service where you set your token in options and it'll go with your every request.

You can refer to this article and let me know further if any query (Click me!).

*Make sure on clicking logout
localStorage.setItem('isLoggedIn', JSON.stringify(false));
this.currentUser("");

A: Not sure what your auth flow is but you need a http-service that will either get or post the token based on the current state.
Something like
  get(url: string, options?: RequestOptionsArgs, silent: boolean = false): Observable<Response> {
  let getStream = () => {
    return Observable.from([true])
      .flatMap((_) => {
        if (!silent) this.beginActivity();
        return this.authHttp.get(url, this.prepareOptionsForJsonApi(options));
      })
      .catch((res) => { return this.handleError(res); })
      .do(noop,
      (error) => { this.publishError(error); },
      () => { if (!silent) this.endActivity(); });
  };

  return this.whenTokenReady(getStream);
}

  post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
  let postStream = () => {
    return Observable.from([true])
      .flatMap((_) => {
        this.beginActivity();
        return this.authHttp.post(url, body, this.prepareOptionsForJsonApi(options));
      })
      .catch((res) => { return this.handleError(res); })
      .do(noop,
      (error) => { this.publishError(error); },
      () => { this.endActivity(); });
  };

  return this.whenTokenReady(postStream);
}

A: Problem solved.
I was using the $ resource of angularjs and passing the token as an object in the headers as below, calling the method of calling the token of the localstorage directly on the object.
return $resource('user/:userId', null, {

      'update': {
        method: 'PUT',
        headers: {
          Authorization: 'Bearer ' + AuthService.getToken();
        }
      };

So I changed, created a variable token and called the method of calling the token, and then passed the variable token to the headers in the object.
var token = AuthService.getToken();

    return $resource('user/:userId', null, {

      'update': {
        method: 'PUT',
        headers: {
          Authorization: 'Bearer ' + token
        }
      },


text:
Q: App pool settings for Exchange Server 2013 IIS and Processor Affinity Is it ok to enable processor affinity on the Exchange 2013 app pools? I am running on vmware and have multiple sockets / cores. I see that the defaults are false to Processor affinity.
Will this cause any issues or break anything?


text:
Q: How to convert DateTime to Date in MongoDB for filtering? I am a newbie to MongoDB and having a hard time querying documents with simple filtering. I would like to ask if what is the equivalent of CAST(datetime AS DATE) of mysql in MongoDB?
here's my code.
"inspection": {"hourbeg": "2020-11-23 10:12:20"}
    Bson filters = Filters.and(new BasicDBObject("center.code", code),
            new BasicDBObject("inspection.hourbeg", transactionDate));
    Bson sorts = Sorts.descending("printedOn");

    List<Document> vehicles = collection.find()
            .sort(sorts)
            .filter(filters)
            .into(new ArrayList<Document>());

Im still trying to understand this Aggregate in MongoDB.

A: Never mind guys, I was able to solve my problem using this method. Might be useful for others as well.
    String startDate = transactionDate.toString()+" 00:00:00";
    String endDate = transactionDate.plusDays(1).toString()+" 00:00:00";

    Bson gt = Filters.gt("inspection.hourbeg", startDate);
    Bson lt = Filters.lt("inspection.hourbeg", endDate);

    Bson andDate = Filters.and(gt, lt);

    Bson filters = Filters.and(new BasicDBObject("center.code", code),
            andDate);
    Bson sorts = Sorts.descending("printedOn");

    List<Document> vehicles = collection.find()
            .sort(sorts)
            .filter(filters)
            .into(new ArrayList<Document>());


text:
Q: How to force a non-breaking line with a thin space I am looking to make a space between to characters non-breaking line...
Here is a demo of what I am talking about:
http://jsfiddle.net/hGdXE/1/
I have also tried this:

The problem is that this code does not work in Kobo eBook readers.
Is there any other way to make this work?

A: There are basically four approaches in general to the issue of non-breaking thin space: 1) Use U+202F NARROW NO-BREAK SPACE, which would be a purely character-level solution, but browser and font support is a problem. 2) Use U+2009 THIN SPACE and try to make it non-breaking, as you have tried. This mostly works, but it is clumsy, and you would need to include characters from each side of the thin space, as in your fiddle. 3) Use a normal space, U+0020 SPACE, and try to make it both non-breaking and suitably narrow with the use of CSS. 4) Use U+00A0 NO-BREAK SPACE and try to make it narrow with CSS.
The last approach seems to be the best shot in general. You would need to wrap the no-break space in an inline element and set its display property to inline-block, so that width setting will have an effect:

with CSS code like
.fine {
  display: inline-block;
  width: 0.125em;
}

I hope this works with Kobo ebook reader. It should, since the no-break space is generally well supported in browsers, with just some exceptions in IE, and the CSS styling is simple.


text:
Q: Git push from post-update hook fails - X is not a repository I am trying to setup a central repository that will automatically push to another repository when it is pushed to from my local machine. I have been Googling for several days now and I have tried every command combination I could find with no luck.
The setup:
I first created the central repository as a bare and then cloned it to the second machine as a non-bare. I added the second machine as a remote, called "www", to the first machine. I confirmed that I could execute "git push www master" manually from the first machine and it will update the second via SSH. I then cloned the repository to my local development machine via HTTP. I can push from local to central just fine.
My post-update hook in its current form:
#!/bin/bash

cd /var/git_repos/site.git

unset $(git rev-parse --local-env-vars)

branch=$(git rev-parse --abbrev-ref HEAD)

if [ "$branch" == "master" ];
then
  echo "Pushing $branch to www..."
  env -i git push www master
fi

exec git update-server-info

I have cobbled this together from various SO and blog posts. It works fine when executed manually from the CLI of the first machine ("cd /var/git_repos/site.git/hooks; ./post-update") but I get the error message "www is not a Git repository" when executed as a hook.
The output:
$ git push
Password:
Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 264 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: Pushing master to www...
remote: fatal: 'www' does not appear to be a git repository
remote: fatal: The remote end hung up unexpectedly
To https://xxx@git.xxx.xxx/site.git
   e3d3a1d..103c819  master -> master

Can anyone tell me what I am doing wrong?
Edit: I have figured out that my initial issue was that the permissions on site.git were not entirely set correctly. Having fixed that problem, I have a new problem.
New output:
$ git push
Password:
Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 332 bytes, done.
Total 3 (delta 1), reused 0 (delta 0)
remote: I am apache <---- Output of "whoami" for debugging
remote: Pushing master to www...
remote: ssh: connect to host 192.168.1.79 port 22: Permission denied
remote: fatal: The remote end hung up unexpectedly
To https://nnn@git.nnn.nnn/site.git
   29d504c..f14f201  master -> master

I have tried adding the following to my /etc/sudoers file with no luck:
apache ALL=NOPASSWD: /usr/bin/ssh

A: This is the error you get when trying to push to an unknown remote. Try:
git push thisisprobablynotaremote master

Check
git remote -v

and make sure that www is properly defined, also check
git config --list

www should be there as well.
Print the output of all commands from the hook itself and compare the output.

A: I would suggest changing the www to the full url of the remote repo you are pushing to. Additionally changing master to master:master might be of help.

A: Don't do
unset $(git rev-parse --local-env-vars)

I think you saw the hooks where people were trying to do a git pull from a different repo. You are just doing all the commands relative to the current repo. So you don't have to do that.
Similarly, don't do:
env -i git push www master

remove the env -i


text:
Q: Why is my boolean field still showing up as part of the request body after I used @JsonIgnore and @JsonIgnoreProperties? In my Swagger documentation, for POST requests, it should not show the boolean field in the request body.
I want to ignore the booleanValue field in the DTO class below:
public class MyDto {
    private String stringValue;
    @JsonIgnore
    private int intValue;
    private boolean booleanValue;
}

I have tried using @JsonIgnore and @JsonIgnoreProperties, but it is not working.
1.  @JsonIgnore
    private boolean booleanValue;

2.  @JsonIgnoreProperties(value = { "booleanValue"})
    public class MyDto {
      /* ... */
    }

How can I ignore the boolean field in the MyDto class?

A: is your boolean field starts with isSomething or hasSomething? if yes, then the @Jsonignore doesn't work on it. you need to change it to "something"

A: Use @ApiModelProperty and set the hidden element to true:
@ApiModelProperty(hidden = true)
private boolean booleanValue;

A: You will need to change dataType from boolean to Boolean, then it will work.
Thanks


text:
Q: Weird colored terminal response by git Recently I was scared to death by the following colored terminal response.
It was triggered by the git push command.
Does anybody have a clue where this colored response comes from?

A: Just a guess, but perhaps the fine folks at Atlassian who run BitBucket are celebrating the Supreme Court ruling on gay marriage. That is their logo in rainbow-colored ASCII art...


text:
Q: How to write a SOQL query to order by records a user has ever modified? Imagine I'm building a ticketing system and I want agents to automatically receive the "next" Ticket__c. However, I want to be smart about what comes next by adding some kind of best effort stickiness to the system where you'll work on tickets you had previously worked with before working on other tickets.
I want to sort by 4 things:

*

*User owns the ticket

*Owner has modified the ticket at any point in the past

*The current User is in the same User.Group__c as the current Owner of the ticket

*Date the ticket was created (this one is easy of course)

My biggest challenge is figuring out how to query for all of this and add it all into an ORDER BY clause so I can query tons of objects quickly and efficiently.
For #2, how would I query from something a User has every modified? One thought was to create a text field with a space delimited list of Ids of people who have ever modified the proof, then I could query WHERE ModifiedIds__c LIKE ('%' + UserInfo.getUserId() + '%') or something of that intent. However, I'm not sure how to add that into ORDER BY.
For #3, if Group__c is a custom field on the user, do I have to copy the current owner's Group__c to the object through a trigger and then index the field to both make it accessible and performant? Since Owner is polymorphic, I can't query by Owner.Group__c = . Right?


text:
Q: Can't seem to connect my android to my php server I am new to android development and i've been working on this project to create a login function. But I seem to have problems retrieving the info from my server. Cant get my code to work.
Login.java
package com.httpkhronolog.khronolog;

import android.app.ActionBar;
import android.app.Notification;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class Login_Activity extends AppCompatActivity {

    public static final String SERVER_ADDRESS = "http://www.khronolog.com/mobile/";
    public static final String TAG_LOGINSTATUS = "loginStatus";
    EditText etUsername, etPassword;
    ImageButton ibLogin;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        context = this;

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        etUsername = (EditText) findViewById(R.id.etUsername);
        etPassword = (EditText) findViewById(R.id.etPassword);
        ibLogin = (ImageButton)findViewById(R.id.ibLogin);

        ibLogin.setOnClickListener(new View.OnClickListener(){
           public void onClick(View v){
               String username = etUsername.getText().toString();
               String password = etPassword.getText().toString();

               if(username.length() == 0 || password.length() == 0){
                   Toast toast = Toast.makeText(context, "Username or password not entered", Toast.LENGTH_SHORT);
                   toast.show();
                   return;
               }else
               {
                    new checkUserDetails().execute(username, password);
               }
           }
        });

    }

    public class checkUserDetails extends AsyncTask<String, Boolean, Boolean>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(String... params) {

            DataOutputStream printout;
            HttpURLConnection urlConn;
            BufferedReader reader;
            URL url;
            String json;
            JSONObject jObj;
            Boolean JSONLogin = false;

            //send POST login details to server
            try {
                url = new URL(SERVER_ADDRESS + "login.php");
                urlConn = (HttpURLConnection) url.openConnection();
                urlConn.setRequestMethod("POST");
                urlConn.setDoOutput(true);
                urlConn.setRequestProperty("Accept-Charset", "UTF-8");
                urlConn.setReadTimeout(10000);
                urlConn.setConnectTimeout(15000);

                HashMap<String, String> map = new HashMap<String, String>();
                map.put("username", params[0]);
                map.put("password", params[1]);

                StringBuilder sb = new StringBuilder();
                for(HashMap.Entry<String, String> e : map.entrySet()){
                    if(sb.length() > 0){
                        sb.append("&");
                    }
                    sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=").append(URLEncoder.encode(e.getValue(), "UTF-8"));
                }

                String loginDetails = sb.toString();

                printout = new DataOutputStream(urlConn.getOutputStream());
                printout.writeBytes(loginDetails);
                printout.flush();
                printout.close();

                reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                StringBuilder sb2 = new StringBuilder();
                String result = null;
                while((result=reader.readLine())!=null) {
                    sb2.append(result + '\n');
                    Log.d("Results", sb2.toString());
                };

                json = result.toString();

                jObj = new JSONObject(json);

                JSONLogin = jObj.getBoolean(TAG_LOGINSTATUS);
                Log.d("LoginStatus!!!!", JSONLogin.toString());

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                Log.d("JsonConvertion", "FAILED TO CONVERT JSON");
            }

            return JSONLogin;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
        }
    }

    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_login_, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    */
}

login.php on server
<?php
if (isset($_POST['username'])) {
        // Define $username and $password
        $username=$_POST['username'];
        $password=$_POST['password'];
        // Establishing Connection with Server by passing server_name, user_id and password as a parameter
        $connection = mysql_connect("localhost", "SomeAdmin", "somepassword");
        // To protect MySQL injection for Security purpose
        $username = stripslashes($username);
        $password = stripslashes($password);
        $username = mysql_real_escape_string($username);
        $password = mysql_real_escape_string($password);
        // Selecting Database
        $db = mysql_select_db("khronolo_systemdb", $connection);
        // SQL query to fetch information of registerd users and finds user match.
        $query = mysql_query("select * from user_table where password='$password' AND email='$username'", $connection);
        $rows = mysql_num_rows($query);
        if ($rows == 1) {
            $returnValue[] = array("loginStatus"=> "true");
            echo json_encode($returnValue);
        }
        else {
            $returnValue[] = array("loginStatus"=> "false");
            echo json_encode($returnValue);
        }
        mysql_close($connection); // Closing Connection
    }
}

?>
stacktrace error
    10-18 18:12:05.310 2594-2711/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime: Process: com.httpkhronolog.khronolog, PID: 2594
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime: java.lang.RuntimeException: An error occurred while executing doInBackground()
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at android.os.AsyncTask$3.done(AsyncTask.java:309)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:818)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:  Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.net.InetAddress.lookupHostByName(InetAddress.java:464)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.net.InetAddress.getAllByName(InetAddress.java:215)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.httpkhronolog.khronolog.Login_Activity$checkUserDetails.doInBackground(Login_Activity.java:125)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.httpkhronolog.khronolog.Login_Activity$checkUserDetails.doInBackground(Login_Activity.java:82)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:818)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:  Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at libcore.io.Posix.android_getaddrinfo(Native Method)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.net.InetAddress.lookupHostByName(InetAddress.java:451)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.net.InetAddress.getAllByName(InetAddress.java:215)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.httpkhronolog.khronolog.Login_Activity$checkUserDetails.doInBackground(Login_Activity.java:125)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.httpkhronolog.khronolog.Login_Activity$checkUserDetails.doInBackground(Login_Activity.java:82)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:818)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:  Caused by: android.system.ErrnoException: android_getaddrinfo failed: EACCES (Permission denied)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at libcore.io.Posix.android_getaddrinfo(Native Method)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.net.InetAddress.lookupHostByName(InetAddress.java:451)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.net.InetAddress.getAllByName(InetAddress.java:215)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.httpkhronolog.khronolog.Login_Activity$checkUserDetails.doInBackground(Login_Activity.java:125)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at com.httpkhronolog.khronolog.Login_Activity$checkUserDetails.doInBackground(Login_Activity.java:82)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
10-18 18:12:05.310 2594-2711/? E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:818)
10-18 18:12:05.328 1296-1846/? W/ActivityManager:   Force finishing activity com.httpkhronolog.khronolog/.Login_Activity

I am aware that my problem is at the aynctask but I am not sure how to solve it :(. Please help

A: Add Internet permission to AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


text:
Q: Java 8 Executor callable passing thread as argument I need some help running the process in multi-thread environment (java 8) in parallel to process quicker. Here is my use case.

*

*Retrieve records from the database (large amount, millions of records) ex : select * from EMP where …..and MOD(PK,totalLoops -1) =currentLoop  LIMIT 10,000 (Haven't decided the limit yet) – PostgreSQL DB

*Make a connection to cloud platform, read JSON and then validate data from database to JSON keys and returns tvalidated or not

*Update the database with the validation status for each recorded retrieved above.

The idea of retrieving the set of records from the database and run the process in parallel is by using MOD value and the thread ID will be replaced by "?"
in the query. Ex MOD (id,ThreadID) = Thread -1
Q1 . The issue is, I am not able to pass the Thread ID as an argument to the Runnable or Callable.
Q2. Can I also use stream and forEach for the ArrayList to call -  process.getGCPDataFromJSON(); I can overload this method.
 Is it possible to have a thread and streaming inside a thread and have multiple threads ?
     private int totalNumberOfThreads = 10;

Callable<String> callableTask = () -> {

            TimeUnit.MILLISECONDS.sleep(1000);
            System.out.println("Current time :: " + LocalDateTime.now());

   for (int i=0; i<10; i++{

           process.getGCPDataFromJSON(ArrayList queryDataList =
        DataAccess.getInstance().getDataToProcess(i, totalNumberOfThreads));

   }
   return "Done"

    };

    //Executor service instance
    ExecutorService executor = Executors.newFixedThreadPool(2);
     //2. execute individual tasks using submit() method
    Set<Callable<String>> callables = new HashSet<Callable<String>>();

    for (int i =0; i<10; i++){
        executor.submit(callableTask);
        callables.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "Task Done:";
            }
        });
    }

    String result = executor.invokeAny(callables);
    System.out.println("result = " + result);

    //Shut down the executor service
    executor.shutdownNow();


text:
Q: How to run test files (NOT tests in file) sequentially? Variables between files are interconnected. Framework is Mocha How to run test files (NOT tests in file) sequentially? Variables between files are interconnected. Framework is Mocha
for example tree in spec:

*

*test#1.js

*test#2.js

First I need run test#2.js -> important variables will be store as global , then I need to use global variables from test#2.js
and run test#1.js
I did try this method https://www.npmjs.com/package/mocha-order-tests


text:
Q: Why does my React js contact form is not working? I'm new to React JS. I built a contact form using JSX and PHP but the form isn't working. The same code would work in an HTML & CSS website but it isn't working here. When I'm submitting this form, the page is redirecting to /contact.php without showing any if else alert of PHP. Neither the console has any error.
Here is the JSX for contact form:
<form method = 'post' id = 'contactform' action = 'contact.php'>

            Your name

            <input type = 'text' name = 'name' className = 'input-area' required/>

             Your email

             <input type = 'email' name = 'email' className = 'input-area' required/>

             Your (whatsapp) number

             <input type = 'tel' name = 'number' className = 'input-area' required/>

            Communication preference

            <select form = 'contactform' name = 'commPre' className = 'input-select' required>
                <option value = 'opt1'>Option 1</option>
                <option value = 'opt2'>Option 2</option>
            </select>

            Reason to contact

            <select form = 'contactform' name = 'rtc' className = 'input-select' required>
                <option value = 'opt11'>Option 1</option>
                <option value = 'opt22'>Option 2</option>
            </select>

            How did you find me?

            <select form = 'contactform' name = 'how' className = 'input-select' required>
                <option value = 'opt111'>Option 1</option>
                <option value = 'opt222'>Option 2</option>
            </select>

            Your message

            <textarea name = 'msg' className = 'input-area input-msg' required></textarea>

        <input type = 'submit' name = 'submit' value = 'Send' className = 'send-btn'/>

And here is the PHP:
<?php
    if (isset($_POST['submit'])){
        $name = $_POST['name'];
        $email = $_POST['email'];
        $number = $_POST['number'];
        $commPre = $_POST['commPre'];
        $rtc = $_POST['rtc'];
        $how = $_POST['how'];
        $msg = $_POST['msg'];

        $to = 'myemail@gmail.com';
        $subject = 'Message from website';
        $message = "Name: ".$name."\n"."Email: ".$email."\n"."Phone number: ".$number."\n"."Communication preference: ".$commPre."\n"."Reason to contact: ".$rtc."\n"."How did you find me: ".$how."\n"."Message: ".$msg;

        if(mail($to, $subject, $message)){
            echo
            '';
        }

        else{
            echo
            '';
        }
    }
?>


text:
Q: How to get frequency of logging using bash if each line contains a timestamp? I have a program that during it's operation it writes to a text file. In this text file each line consists of 4 parts.

*

*Thread ID (a number)

*A date in the format yyyy-mm-dd

*A timestamp in the format 12:34:56.123456

*A function name

*Some useful comments printed out by the programs

An example of what a log line would look like would be something like this:
127894 2020-07-30 22:04:30.234124 foobar caught an unknown exception
127895 2020-07-30 22:05:30.424134 foobar clearing the programs cache
127896 2020-07-30 22:06:30.424134 foobar recalibrating dankness

The logs are printed in chronological order and I would like to know how I to get the highest frequency of these logs. For example I wanted to know at what minute or second of the day the program has the highest congestion.
Ideally I'd like an output that could tell me for example, "The highest logging frequency is between 22:04:00 and 22:05:00 with 10 log lines printed in this timeframe".

A: Let's consider this test file:
$ cat file.log
127894 2020-07-30 22:04:30.234124 foobar caught an unknown exception
127895 2020-07-30 22:05:20.424134 foobar clearing the programs cache
127895 2020-07-30 22:05:30.424134 foobar clearing the programs cache
127895 2020-07-30 22:05:40.424134 foobar clearing the programs cache
127896 2020-07-30 22:06:30.424134 foobar recalibrating dankness
127896 2020-07-30 22:06:40.424134 foobar recalibrating dankness

To get the most congested minutes, ranked in order:
$ awk '{sub(/:[^:]*$/, "", $3); a[$2" "$3]++} END{for (d in a)print a[d], d}' file.log | sort -nr
3 2020-07-30 22:05
2 2020-07-30 22:06
1 2020-07-30 22:04

22:05 appeared three times in the log file and is, thus, the most congested, followed by 22:06.
To get only the top most congested minutes, add head.  For example:
$ awk '{sub(/:[^:]*$/, "", $3); a[$2" "$3]++} END{for (d in a)print a[d], d}' file.log | sort -nr | head -1
3 2020-07-30 22:05

Note that we select here based on the second and third fields.  The presense of dates or times in the texts of log messages will not confuse this code.
How it works
sub(/:[^:]*$/, "", $3) removes everything after minutes in the third field.
a[$2" "$3]++ counts the number of times that date and time (up to minutes) appeared.
After the whole file has been read, for (d in a)print a[d], d prints out the count and date for every date observed.
sort -nr sorts the output with the highest count at the top.  (Alternatively, we could have awk do the sorting but sort -nr is simple and portable.)
To sort down to the second
Instead of minutes resolution, we can get seconds resolution:
$ awk '{sub(/\.[^.]*$/, "", $3); a[$2" "$3]++} END{for (d in a)print a[d], d}' file.log | sort -nr
1 2020-07-30 22:06:40
1 2020-07-30 22:06:30
1 2020-07-30 22:05:40
1 2020-07-30 22:05:30
1 2020-07-30 22:05:20
1 2020-07-30 22:04:30

A: With GNU utilities:
grep -o ' [0-9][0-9]:[0-9][0-9]' file.log | sort | uniq -c | sort -nr | head -n 1

Prints
frequency  HH:MM

HH:MM is the hour and minute the highest frequency occurs and frequency is the highest frequency. If you drop the | head -n 1 then you will see the list of frequencies and minutes ordered by frequencies.


text:
Q: 404 Error in Post method from react to API In this project Get method is working and headers also applied in API. When I am posting It giver and error 404 (Failed to load resource: the server responded with a status of 400 (Bad Request))
In Api Modal I have this code :
    using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace Pay_Roll_Managment_System.Models
{
    public class Employee
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //Id auto-generated by the database
        public int EmployeeId { get; set; }
        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }
        [Required]
        public string Address { get; set; }
        [Required]
        public DateTime Birthdate { get; set; }
        [Required]
        public string ContactInfo { get; set; }
        [Required]
        public bool Gender { get; set; } // 1 == male , 0 == female
        [Required]
        public string RegistrationNo { get; set; }

        public string ImgUrl { get; set; }
        [Required]
        public DateTime CreatedOn { get; set; }

        [ForeignKey("PoistionId")]
        public Position Position { get; set; }
        public int PoistionId { get; set; }

    }
}

and in controller I have this code for post method
     [HttpPost]
        [ProducesResponseType(201, Type = typeof(Employee))]
        [ProducesResponseType(500)]

        public IActionResult CreateEmpoyee([FromBody]Employee EmployeeToCreate)
        {
            if (EmployeeToCreate ==null)
            {
                return BadRequest(ModelState);
            }

            //Checking the method of Employee forign key. 2 if conditions have to be satisified

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            //creating employee
            if (!_EmployeeRepository.CreateEmployee(EmployeeToCreate))
            {
                return StatusCode(500, ModelState);
            }
            return CreatedAtRoute("GetEmployee", new { EmployeeId = EmployeeToCreate.EmployeeId });

        }

in React Post component I have this code
    import React from 'react';
import {Component} from 'react';
import {Modal,Button,Row,Col, Form} from 'react-bootstrap';
import Snackbar from '@material-ui/core/Snackbar';
import IconButton from '@material-ui/core/IconButton';

export class EmployeeRegPop extends Component {
    constructor(props) {
        super(props);
        this.state = {Snackbaropen:false,Snackbarmsg:''}
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    SnackbarClose = (event)=>{
    this.setState({Snackbaropen:false,
    })
  }

    handleSubmit(event){
      event.preventDefault();
        fetch('http://localhost:xxxxxx/api/employees',{
          method:'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
          },
          body:JSON.stringify({
            id:null,
            FirstName:event.target.FirstName.value,
            LastName:event.target.LastName.value,
            Address:event.target.Address.value,
            Birthdate:event.target.Birthdate.value,
            ContactInfo:event.target.ContactInfo.value,
            Gender:event.target.Gender.value,
            RegistrationNo:event.target.RegistrationNo.value,
            CreatedOn:event.target.CreatedOn.value,
            PoistionId:event.target.PoistionId.value,
          })
        })
        .then(res=>res.json())
        .then((result)=>
        {
             alert(result)
            this.setState({SnackbarOpen:true, Snackbarmsg:"Added Successfully"})
        },
        (error)=>{
          this.setState({SnackbarOpen:true, Snackbarmsg:"failed"})
        })
    }
    render() {
        return (

          <Snackbar
            anchorOrigin ={{vertical:'bottom',horizontal:'center'}}
            open = {this.state.Snackbaropen}
            autoHideDuration = {3000}
            onClose = {this.SnackbarClose}
            message = {{this.state.Snackbarmsg}}
            action ={[
              <IconButton
                key = "close"
                arial-label="Close"
                color ="inherit"
                onClick={this.SnackbarClose}>
                x
              </IconButton>
            ]}
          />

            <Modal
              {...this.props}
              size="lg"
              aria-labelledby="contained-modal-title-vcenter"
              centered
            >
              <Modal.Header closeButton>
                <Modal.Title id="contained-modal-title-vcenter">
                  Employee Registration
                </Modal.Title>
              </Modal.Header>
              <Modal.Body>

            <Row>
                <Col sm= {6}>
                    <Form onSubmit ={this.handleSubmit}>

                        <Form.Group controlId ="FirstName">
                        <Form.Label> First Name</Form.Label>
                        <Form .Control
                        type ="text"
                        name = "FirstName"
                        required
                        placeholder ="First Name"
                        />
                        </Form.Group>

                        <Form.Group controlId ="LastName">
                        <Form.Label>Last Name</Form.Label>
                        <Form .Control
                        type ="text"
                        name = "LastName"
                        required
                        placeholder ="Last Name"
                        />
                        </Form.Group>

                        <Form.Group controlId ="Address">
                        <Form.Label>Address</Form.Label>
                        <Form .Control
                        type ="text"
                        required
                        name = "Address"
                        placeholder ="Address"
                        />
                        </Form.Group>

                        <Form.Group controlId ="Birthdate">
                        <Form.Label>Birth Date</Form.Label>
                        <Form .Control
                        type ="Date"
                        name = "Birthdate"
                        placeholder ="Birth date"
                        />
                        </Form.Group>

                        <Form.Group controlId ="Gender">
                        <Form.Label>Gender</Form.Label>
                        <Form .Control
                        type ="text"
                        name = "Gender"
                        placeholder ="Gender"
                        />
                        </Form.Group>

                        <Form.Group controlId ="ContactInfo">
                        <Form.Label>contact Info</Form.Label>
                        <Form .Control
                        type ="number"
                        name = "ContactInfo"
                        placeholder ="contact Info"
                        />
                        </Form.Group>

                        <Form.Group controlId ="RegistrationNo">
                        <Form.Label>Registration No</Form.Label>
                        <Form .Control
                        type ="text"
                        name = "RegistrationNo"
                        placeholder ="Registration No"
                        />

                        <Form.Group controlId ="CreatedOn">
                        <Form.Label>Created On</Form.Label>
                        <Form .Control
                        type ="Date"
                        name = "CreatedOn"
                        placeholder ="Created On"
                        />
                        </Form.Group>

                        <Form.Group controlId ="PoistionId">
                        <Form.Label>Position Id</Form.Label>
                        <Form .Control
                        type ="int"
                        name = "PoistionId"
                        placeholder ="Position Id"
                        />
                        </Form.Group>
                        </Form.Group>
                        <Form.Group>
                        <Button variant ="primary" type = "submit">
                        Add Employee</Button>
                        </Form.Group>
                    </Form>
                </Col>
            </Row>
      </Modal.Body>
      <Modal.Footer>
        <Button variant ="danger" onClick={this.props.onHide}>Close</Button>
      </Modal.Footer>
    </Modal>

        )
    }
}

export default EmployeeRegPop

Please help to find the error and I am working for 2 days in this error now. I need any other requirements please let know.


text:
Q: What does the work on a current carrying wire in a Magnetic Field? We consider that the force acting on a current carrying wire placed in a uniform magnetic field perpendicular to the length of the wire is given by $IBl$. If the wire moves by a distance $x$ in a direction perpendicular to its length the raise in its kinetic energy is $IBlx$
Now basically the magnetic forces are acting on the electrons moving inside the wire and is always perpendicular to the instantaneous velocity so it cannot perform any work on it and normals are also unable to provide any net work done on the system, so what provides the change in kinetic energy of the system?

A: First, just as a reminder, the force of a particle due to a magnetic field is $$\vec{F_B}=q\vec{v}\times\vec{B}$$. As you mentioned the force due to the magnetic field is always perpendicular to the velocity but it is also perpendicular to the magnetic field so the differential work is $$dw_B=\vec{F_B}\cdot d\vec{s}=q(\vec{v}\times\vec{B})\cdot \vec{v}dt=0 $$ so we have verified that the work is indeed zero due to the magnetic field. $\vec{F_B}$ cannot change the speed of the particle so it cannot change it's kinetic energy, but it can change the direction of $\vec{v}$. The total force on the particle is $$\vec{F}=q(\vec{E}+\vec{v}\times\vec{B})$$ so the total work on a particle is $$dw=q\vec{E}\cdot\vec{v}dt$$ which is non zero.
Now lets consider the wire which is really just a group of moving charges. positive particles inside the wire are pushed upward in the wire due to the magnetic force and negative particles are pushed downward (where the up-down directions are orthogonal to the wire velocity v and magnetic field B). The separation of charges induces an E field which produces a force on the respective particles in the opposite direction. In equilibrium the two forces balance and we have $$qvB=qE$$ and the emf across length l is $$\mathcal{E}=El=Bvl$$. When you are talking about an EMF in the wire you should consider the wire in a magnetic field closed by a loop outside the field (see http://hyperphysics.phy-astr.gsu.edu/hbase/electric/elevol.html#c4 , In your problem the circuit is not closed so the wire goes nowhere) The induced emf can be seen as the work done per unit charge so it is really the E field that changes the velocity of the particles (changes their kinetic energy)perpendicular to the B field.

A:
so what provides the change in kinetic energy of the system?

In standard EM theory, there are no magnetic poles, only electric ones. Magnetic force on charged particle is always perpendicular to the velocity of the particle, and thus magnetic forces do not work. Generally, if any work is done on the matter, it has to be due to other forces, either mechanical force (like normal or friction force) or electrical force due to electric field.
In your case, since there are no external forces other than magnetic, the working forces have to be internal, i.e. due to the wire itself.
There is no problem with internal forces doing net work - this happens daily. For example, consider how person on a bicycle acquires kinetic energy - the force working on the bike is due to biker and the force working on the biker is due to bike while net positive work is done on the system. The energy for this comes from the energy stored in the biker.

In the case of wire, imagine that wire consists of charged particles (conduction charges) moving inside and along a perfectly reflecting tube (the wire without the conduction charges). Magnetic field acts on the particles and would curve their motion as it happens in vacuum, if the tube did not prevent that. If the wire is held static (by external mechanical force), part of the normal force of the tube cancels the magnetic force and the rest curves the motion of the charges so that they can move along the tube.
When the external mechanical force is removed and the wire is allowed to move, the reaction forces of the charged particles on the tube can do work on the tube. The tube also does work on the charges, while net result is that net work is done on the system.
In this view the work is due to contact mechanical forces, but sometimes it is believed that all mechanical contact forces are ultimately electromagnetic forces on the microscopic level. So if we went deeper into this, the working forces are actually microscopic electric forces - the electric force of the charge works on the lattice and the electric force of the lattice works on the charge.
If the circuit is made of perfect conductor without any source of voltage, the kinetic energy increases at the expense of the magnetic energy in the space around the wire.
If the circuit is made of Ohmic wire and has a source of voltage, kinetic and internal energy of the wire increases also due to energy supplied by the source of voltage.

A: Your wire must be part of an electrical circuit (no closed loop = no current). Let us assume that the "return wire" is far away, where there is no magnetic field. So we have a large loop.
Now the motion of the wire in the magnetic field will induce a current that will oppose the magnetic flux change. What happens is that the magnetic field "seen" by the wire becomes less - and since the energy stored in the magnetic field goes as the integral of $B^2$ over the volume, there will be less energy in the magnetic field.
So the "source" of the energy of the wire is the energy that used to be stored in the magnetic field.

A: Newton's 3rd law of motion :
Every action has equal and opposite reaction.
When a rod is moving in a magnetic field,
An emf is developed in it similarly when current is passed or emf is induced across a stationary wire,
It starts moving or a force it acted on it which is responsible for motion or tendency to bring it in motion


text:
Q: How to avoid discontinuities in a mesh I try to display a gyroid structure (triply periodic minimal surface) in python. I have tried several packages but pyvista seems the more appropriate for my study. The gyroid is a periodic minimal surface that can be modelled according to the following equation:
sin(a(i - 1))  * cos(a(j -  1)) + sin(a(j -  1))  * cos(a(k -  1)) + sin(a(k -  1)) * cos(a(i -  1)) < b
where a is a scaling parameter equal to 2pi/l and l is the unit cell length. The value b controls the volume fraction and typically varies between 1.32 and 0.15.
It seems to work well nevertheless from a certain value of b, discontinuities appear in my mesh which is not correct. I tried to use pymesh to repair it or scypy.interpolate but it changes nothing. Do you have an idea? Thanks in advance.

import pyvista as pv
import numpy as np
from numpy import cos, sin, pi
from random import uniform
from scipy.interpolate import RegularGridInterpolator
import pymeshfix

lattice_par = 1.0  # Unit cell length

a = (2*pi)/lattice_par

def gyroid(x, y, z, b=1.2):
    return sin(a*(x - 1))*cos(a*(y - 1)) + sin(a*(y - 1))*cos(a*(z - 1)) + sin(a*(z - 1))*cos(a*(x - 1)) - b

# %% Data

x, y, z = np.mgrid[-2:2:31j, -3:3:31j, 0:4:31j]

vol = gyroid(x, y, z)

grid = pv.StructuredGrid(x, y, z)

grid["vol"] = vol.flatten()

contours = grid.contour([0])  # Isosurface = 0

# %% Visualization

pv.set_plot_theme('document')

p = pv.Plotter()

p.add_mesh(contours, scalars=contours.points[:, 2], show_scalar_bar=False, interpolate_before_map=True,
           show_edges=False, smooth_shading=False, render=True)

p.show_axes_all()

p.add_floor()

p.show_grid()

p.add_title('Gyroid')

p.show(window_size=[2040, 1500])


text:
Q: Cakephp: Load models without model files I have tables that are created on the fly and I'd like to access it
thru Model. Since those tables are dynamically created, I don't have
the model .php files for them. The tables are created conforming to
Cake's naming convention. I tried to use loadModel() to load them but
Cake still complains that the tables are missing.
Is there a solution for it?
Thank you.

A: As of this writing, using CakePHP 2.1.2
In your controller add App::uses('AppModel', 'Model');. Then instantiate the model
    $RemoteHeader = new AppModel(array(
                'table' => 'SOP10100',
                'ds' => 'external',
                'name' => 'RemoteHeader',
                'alias' => 'InvoiceHeader',
                'primaryKey' => 'id',
                'hasMany' => array(
                    'InvoiceDetail' => array(
                        'foreignKey' => 'SOPNUMBE',
                        'counterCache' => false
                ))));

then fetch the data with any Model parameters you need:
    $data = $RemoteHeader->find('all', array(
            'fields' => array(
            'SOPNUMBE',
            'CUSTNAME',
            'DUEDATE',
            'DOCDATE',
            'DOCAMNT',
            'SUBTOTAL')));

A: Create /app/models/dynamic.php with class
class Dynamic extends AppModel {
    var $name = 'Dynamic'
    var $useTable = null;
}

in Your controller's action
$this->Dynamic->useTable = 'newly-created-table';

It's not tested, let me know if having issues