text:
Q: highlight the navigation menu for the current page In a page with some navigation links,I want the link of the current page are hightlighted,just like this:

The link "HTML Attributes" is highlighted(bolded) since this link will take one to the current page.
I know this can be implemented manually(just hightlighted the according link,but is there some smart way? highlight the right link dynamically and automatically?

A: CSS:
.topmenu ul li.active a, .topmenu ul li a:hover {
    text-decoration:none;
    color:#fff;
    background:url(../images/menu_a.jpg) no-repeat center top;
}

JavaScript:

Html Code:

Home

Newsletter

Forms

Mail

Service

HSE

MainMenu2

submenu1

submenu2

submenu3

A: You can set the id of the body of the page to some value that represents the current page. Then for each element in the menu you set a class specific to that menu item.  And within your CSS you can set up a rule that will highlight the menu item specifically...
That probably didn't make much sense, so here's an example:

Index page

Page 1

In the page1.html, you would set the id of the body to: id="page1".
Finally in your CSS you have something like the following:
#index #menu .index, #page1 #menu .page1 {
  font-weight: bold;
}

You would need to alter the ID for each page, but the CSS remains the same, which is important as the CSS is often cached and can require a forced refresh to update.
It's not dynamic, but it's one method that's simple to do, and you can just include the menu html from a template file using PHP or similar.

A: It seems to me that you need current code as this ".menu-current css", I am asking the same code that works like a charm,   You could try something like this might still be some configuration
a:link, a:active {
    color: blue;
    text-decoration: none;
}

a:visited {
    color: darkblue;
    text-decoration: none;
}

a:hover {
    color: blue;
    text-decoration: underline;
}

div.menuv {
    float: left;
    width: 10em;
    padding: 1em;
    font-size: small;
}

div.menuv ul, div.menuv li, div.menuv .menuv-current li {
    margin: 0;
    padding: 0;
    list-style: none;
    margin-bottom: 5px;
    font-weight: normal;
}

div.menuv ul ul {
    padding-left: 12px;
}

div.menuv a:link, div.menuv a:visited, div.menuv a:active, div.menuv a:hover {
    display: block;
    text-decoration: none;
    padding: 2px 2px 2px 3px;
    border-bottom: 1px dotted #999999;
}

div.menuv a:hover, div.menuv .menuv-current li a:hover {
    padding: 2px 0px 2px 1px;
    border-left: 2px solid green;
    border-right: 2px solid green;
}

div.menuv .menuv-current {
    font-weight: bold;
}

div.menuv .menuv-current a:hover {
    padding: 2px 2px 2px 3px;
    border-left: none;
    border-right: none;
    border-bottom: 1px dotted #999999;
    color: darkblue;
}

A:

A: Css classes are here

Make your HTML like this, Set url as id

Index

Contac

Here write javascript, put this javascript after the HTML code.
    function menuHighlight() {
       var url = window.location.href;
       $('#'+tabst).addClass('new_current');
    }
    menuHighlight();

A: I would normally handle this on the server-side of things (meaning PHP, ASP.NET, etc). The idea is that when the page is loaded, the server-side controls the mechanism (perhaps by setting a CSS value) that is reflected in the resulting HTML the client sees.

A: You can use Javascript to parse your DOM, and highlight the link with the same label than the first h1 tags. But I think it is overkill =)
It would be better to set a var wich contain the title of your page, and use it to add a class at the corresponding link.

A: I usually use a class to achieve this. It's very simple to implement to anything, navigation links, hyperlinks and etc.
In your CSS document insert:
.current,
nav li a:hover {
   /* styles go here */
   color: #e00122;
   background-color: #fffff;
}

This will make the hover state of the list items have red text and a white background. Attach that class of current to any link on the "current" page and it will display the same styles.
Im your HTML insert:

Nav Item 1

Nav Item 2

Nav Item 3

A: Please Look at the following:
Here is what's working:
1.) top menu buttons are visible and highlight correctly
2.) sub menu buttons are not visible until top menu is clicked
Here is what needs work:
1.) when sub menu is clicked, looking for new page to keep the selected sub menu open (i will highlight the selected sub menu button for further clarification on navigation)
Please see code here:
http://jsbin.com/ePawaju/1/edit
or here:
http://www.ceramictilepro.com/_6testingonly.php#

Do I need to put this script in the head section? Where is the best place?

Home

sub1

sub2

sub3

sub4

Repairs

1sub1

2sub2

3sub3

4sub4

JQuery is new to me, any help would greatly be appreciated :)
    var submenu;
$('.vnavmenu li').click(function () {
var elems = $('.vmenu ul:not(.vnavmenu)').length;
var $refClass = $('.' + $(this).attr('data-ref'));
var visible = $refClass.is(':visible');

$('.vmenu ul:not(.vnavmenu)').slideUp(100, function () {

    if (elems == 1) {
        if (!visible) $refClass.slideDown('fast');
    }

    elems--;
});

if (visible) $('#breadcrumbs-pc').animate({
    'margin-top': '0rem'
}, 100);
else $('#breadcrumbs-pc').animate({
    'margin-top': '5rem'
}, 100);
});

A: JavaScript:

CSS:
.active{
    color: #fff;
    background-color: #080808;
}

HTML:

                             MY ACCOUNT

                                    <?php echo anchor('myaccount', 'HOME', 'title="HOME"'); ?>

                                    <?php echo anchor('myaccount/credithistory', 'CREDIT HISTORY', 'title="CREDIT HISTORY"'); ?>

A: I prefer to keep code as short and plain as possible, and avoid using any external files (jquery included).
So here is what I've ended up with for myself after researching several topics - using plain Javascript and CSS, no need for jquery.
Put javascript code right after the menu finishes (after closing ul, div, whatever) - code from a snippet should be between
That would allow for a script to execute right after menu will be loaded.
If you want to call it as a function on page load, then link will change only after all elements (including images) are loaded – place this code in a function, call it on page load, the code itself put before the closing  tag like so:

// restrict search to a parent with specific ID (main), rather than search in the whole document
var a = document.getElementById("navig").getElementsByTagName("a");
console.log("Current URL: ", document.location.href.split("#")[0]);
console.log("Links found in HTML: ");
for (var i = 0; i < a.length; i++) {
  // for debugging you can check all found URLs in console (accessible in development mode) and delete next line after debugging
  console.log(a[i].href);
  // strip off any local (withing page) anchors (symbol "#" and what follows after)
  if (a[i].href.split("#")[0] == document.location.href.split("#")[0]) {
    // add a class to the matched link (), define it in CSS
    a[i].className = "current";
  }
}
nav#navig a.current {
  color: red;
}

url1 name

url2 name

url3 name

Test link matching current URL

A: You can Implement this in various ways usinh PHP or Jquery. Here is how I have implemented it in my Projects.
<?php
    //set a default value when the page is not an active page

    $dashboard_active=$profile_active=$home_active='inactive_page';

    //get the Name of the current page;
    //in simple php set the NAME of the php file similar to the link variable
    //example set page name as home if you are going to print the variable $home/$home_active

    $page = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);

    //OR
    //in Laravel

    $page=Route::currentRouteName();

    //OR
    //send page value from the controller

    ${$page."_active"} = 'active_page';

//the above method will change the value of the current active page variable

        ?>

In html print the php data

<span class=" <?php echo $dashboard_active ?> ">  Dashboard

<span class=" <?php echo $profile_active ?>"> Profile

<span class=" <?php echo $home_active ?>">Home

YOu can also do this with Jquery

IN the CSS you need to add this


text:
Q: Vim and unified diffs In my daily work, I only deal with unified diffs, so I would like to define the alias
alias diff='diff -puN'

in my .zshrc.
This alias is not respected when I use the shell from the vim command line mode, i.e., when I enter :!diff file1 file2. I believe this is because vim does not invoke an interactive shell.
Thus, I moved the alias from .zshrc to .zshenv which allows me to get plain old unified diffs from within vim (I usually prefer this output over vimdiff's).
On the other hand, doing this breaks vimdiff which apparently is unable to parse unified diffs (It spawns Error E97, but neither its explanation in help E97 nor the references seem to be useful to me: either they seem unrelated (e.g. the shell option) or are above my head (the diffexpr option).

How should I go about having both vimdiff and my alias for diff work at the same time?

A: Changing the semantics of the diff command indeed wreaks havoc on Vim (this is explained under :help diff-diffexpr: The output of "diff" must be a normal "ed" style diff.  Do NOT use a context diff.), and potentially other programs, too.
A pure shell alias with the same name is fine, as that is only considered when you type commands interactively (or in shell functions, which you should have few of). If you need a changed diff command for non-interactive use (e.g. in Vim's :! command), better define a shell wrapper script / exported shell function / alias in .zshenv under a different name, e.g. diffu.

If you really want to stick to an identical, exported alias (despite the risks of breaking programs), you have to reconfigure Vim so that it doesn't use it. Unfortunately, there's no simple option for the diff executable; you have to write an entire custom 'diffexpr'. Fortunately, there's an example for that under :help diff-diffexpr that emulates the default one. You just need a tiny change to make it avoid your diff alias, e.g. by specifying the full path to diff.
set diffexpr=MyDiff()
function MyDiff()
   let opt = ""
   if &diffopt =~ "icase"
     let opt = opt . "-i "
   endif
   if &diffopt =~ "iwhite"
     let opt = opt . "-b "
   endif
   silent execute "!/usr/bin/diff -a --binary " . opt . v:fname_in . " " . v:fname_new .
    \  " > " . v:fname_out
endfunction

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to achieve matplotlib radial gradient background I am trying to get matplotlib background as:
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

ticks = ["Low", "Moderate", "High"]
plt.xlabel(r"x $\longrightarrow$", fontsize=14)
plt.ylabel(r"y $\longrightarrow$", fontsize=14)
plotlim = plt.xlim() + plt.ylim()
print(plotlim)
ax.imshow([[1, 1], [0, 0]],
          cmap=plt.cm.Reds,
          interpolation='bicubic',
          extent=plotlim)
plt.xticks(np.arange(len(ticks)) / 2, ticks, fontsize=14)
plt.yticks(np.arange(len(ticks)) / 2,
           ticks,
           rotation='90',
           ha='center',
           fontsize=14)
plt.show()

Problem is this is giving the gradient along y-axis, while I want a radial gradient, something like:

A: I think you just need to adjust the matrix that you are interpolating such that the gradient in that matrix is pointing to the uppper right corner:
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

ticks = ["Low", "Moderate", "High"]
plt.xlabel(r"x $\longrightarrow$", fontsize=14)
plt.ylabel(r"y $\longrightarrow$", fontsize=14)
plotlim = plt.xlim() + plt.ylim()
print(plotlim)
ax.imshow([[0.5, 0.5, 0.5], [0, 0.5, 0.5], [0, 0, 0.5]],
          cmap=plt.cm.Reds,
          interpolation='bicubic',
          extent=plotlim, vmin=0, vmax=1)
plt.xticks(np.arange(len(ticks)) / 2, ticks, fontsize=14)
plt.yticks(np.arange(len(ticks)) / 2,
           ticks,
           rotation='90',
           ha='center',
           fontsize=14)

fig.savefig("test.png")

This give the following picture:

EDIT:
You can also build up the gradient without interpolation to get a nice circular gradient:
x = np.linspace(0, 1, 256)
y = np.linspace(1, 0, 256)

xArray, yArray = np.meshgrid(x, y)
plotArray = np.sqrt(xArray**2 + yArray**2)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(plotArray,
          cmap=plt.cm.Reds,
          vmin=0,
          vmax=1)


text:
Q: How to run these two rows on one query I have a table with this structure
Name    Type    Collation   Attributes  Null    Default Extra   Action
 1  user_id int(11)         No          None         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 2  amount  decimal(16,8)   No          None         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 3  aff int(11)             No             0         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 4  jackpot int(11)         No             0         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 5  paidout int(11)         No             0         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 6  type    int(11)         No             0         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 7  created timestamp       No   CURRENT_TIMESTAMP   Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More

I am trying this 2 rows on the same query without success:
UPDATE `trans` where paidout=1 GROUP BY user_id
UPDATE `trans`where paidout=0 GROUP BY user_id

also just to view not to update would be fine
like this
SELECT * FROM  `trans` where paidout=1 GROUP BY user_id
SELECT * FROM  `trans` where paidout=0 GROUP BY user_id

I need to run these 2 rows on the same query
I need to group  the table rows by user_id  but the the same user_id has paidout=1 in some rows and paidout=0 in some other rows
so i want to group by user_id where paidout=1 and GROUP BY user_id where paidout=0
so i will get 2 rows for each user_id

A: Wild guessing what you want from the little you gave us:
SELECT user_id,paidout,count(*),sum(amount) FROM trans GROUP BY user_id,paidout

A: If you want to simply view all records which have Paidout=0 and Paidout=1, you need to do :
SELECT * from `trans` WHERE paidout = 1

or
SELECT * from `trans` WHERE paidout = 0

or (If you want both)
SELECT * from `trans` WHERE paidout = 1 OR paidout = 0

A Group By clause is only needed if you want to use an aggregate function (Sum, Average, Max, Min, etc).
If you DO want a to run an Aggregate function(For example, if you want the number of records with paidout = 1 and 0), then you will do :
SELECT paidout, count(paidout) FROM `trans` GROUP BY paidout

I hope this has solved your problem, if not, please do reply with more details and I will update this answer!
Note : These are only the most basic ways to run these queries, you can further tweak and optimize them for your own need, but that is beyond the scope of this answer!


text:
Q: Add class jquery nth I have several li elements. I would like to add the class col-md- * according to the position. The result would be as below. How to do this using jQuery?

A: You could use the selector 4n+2 and add the next LI to that collection, add the class, and then just store that selection to exclude it when adding the other class

var sm4 = $('ul li:nth-child(4n+2)').next('li').addBack().addClass("col-sm-4");
$('ul li').not(sm4).addClass("col-sm-8")
.col-sm-8 {color : red}
.col-sm-4 {color : blue}

test

test

test

test

test

test

test

test

test


text:
Q: Cross Apply At Different Level I have xml data that looks like this:
<game>

  <teams>
    <home id="363" color="000099">Brazil</home>
    <away id="375" color="c5b358">Germany</away>
  </teams>

  <gameInfo>
    <homeScore>1</homeScore>
    <awayScore>7</awayScore>
    <clock>90</clock>
  </gameInfo>

</game>

I would like to create a table that has the columns in this order: home,away,homeID, awayID, homeScore, awayScore. I can't seem to get the home id (363 and 375) into the table:
select *
from (
select

e.value('(./teams/home/text())[1]', 'nvarchar(100)') home,
e.value('(./teams/away/text())[1]', 'nvarchar(100)') away,
e.value('./teams/home/@id', 'int') homeID,
e.value('./teams/away/@id', 'int') awayID
e.value('(./gameInfo/homeScore/text())[1]', 'int') homeScore,
e.value('(./gameInfo/awayScore/text())[1]', 'int') awayScore

from (select * from [XMLTest].[dbo].[MATCHES]) t
cross apply t.data.nodes('game') as t2(e)

) events

A: You missed to mention the position for Id.
value() always requires a positional reference to identify the node you want.
Change your select like this.
SELECT e.value('(./teams/home/text())[1]', 'nvarchar(100)') home,
       e.value('(./teams/away/text())[1]', 'nvarchar(100)') away,
       e.value('(./teams/home/@id)[1]', 'int')              homeID,
       e.value('(./teams/away/@id)[1]', 'int')              awayID,
       e.value('(./gameInfo/homeScore/text())[1]', 'int')   homeScore,
       e.value('(./gameInfo/awayScore/text())[1]', 'int')   awayScore
FROM   [MATCHES] t
       CROSS apply t.data.nodes('game') AS t2(e)

Example:
DECLARE @xml XML='<game>

  <teams>
    <home id="363" color="000099">Brazil</home>
    <away id="375" color="c5b358">Germany</away>
  </teams>

  <gameInfo>
    <homeScore>1</homeScore>
    <awayScore>7</awayScore>
    <clock>90</clock>
  </gameInfo>

</game>'

SELECT cs.e.value('(./teams/home)[1]', 'nvarchar(100)') home,
       cs.e.value('(./teams/away)[1]', 'nvarchar(100)') away,
       cs.e.value('(./teams/home/@id)[1]', 'int')          homeID,
       cs.e.value('(./teams/away/@id)[1]', 'int')          awayID,
       cs.e.value('(./gameInfo/homeScore)[1]', 'int')   homeScore,
       cs.e.value('(./gameInfo/awayScore)[1]', 'int')   awayScore
FROM   @xml.nodes('game') AS cs (e)

Result:
home    away    homeID  awayID  homeScore   awayScore
------  ------- ------  ------  ---------   ---------
Brazil  Germany 363     375     1           7


text:
Q: How to display Object Details by a reference via a TapGestureRecognizer within a ListView in Xamarin Forms MVVM I have a ListView displaying multiple cases, and I would like to display its page details when I click on the the Reference from the list.  I only get a blank page.
I have tried EventHandler from my XAML and did not work.
  <ListView ItemsSource="{Binding GetCases}" HasUnevenRows="True">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <ViewCell.View>
                                <StackLayout Margin="20,0,20,0">
                                    <Label Text="Case Reference:" FontSize="14" TextColor="Green"/>
                                    <Label FontSize="12" TextColor="Blue" FontAttributes="Bold">
                                        <Label.FormattedText>
                                            <FormattedString>
                                                <Span Text="{Binding Reference}" TextColor="Blue" TextDecorations="Underline">   // I can get the list of References here, but can go to their details
                                                    <Span.GestureRecognizers>
                                                        <TapGestureRecognizer Tapped="TapGestureRecognizer_OnTapped"  NumberOfTapsRequired="1" />
                                                        <TapGestureRecognizer Command="{Binding Path=BindingContext.GoToPageDetails, Source={x:Reference Page}}" />    //This approach takes me to the Page Details, but it is blank
                                                    </Span.GestureRecognizers>
                                                </Span>
                                            </FormattedString>
                                        </Label.FormattedText>
                                    </Label>
                                </StackLayout>
                            </ViewCell.View>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

VIEWMODEL
 public CasesViewModel(INavigation navigation)
    {
        IGetDataFromServer cases = new GetDataFromServer();
        Navigation = navigation;
        GoToPageDetails = new Command(async () => await PageDetails());
        GetCases = cases.GetCases();     // This code retrieves my data from server - it Works fine
    }

public Command GoToPageDetails { get; set; }
    public async Task PageDetails()
    {
        await Navigation.PushAsync(new CaseDetails());
    }

CASE DETAILS XAML
<ListView ItemsSource="{Binding GetCases}" HasUnevenRows="True">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <ViewCell.View>
                                <StackLayout Margin="20,0,20,0">
                                    <Label Text="PERSONAL DETAILS" FontSize="Large" TextColor="Black" Margin="0,0,0,20" />
                                    <Label Text="Status:" FontSize="14" TextColor="Green"/>
                                    <Label Text="{Binding status}"
                                FontSize="12" TextColor="Black" />
                            </StackLayout>
                          </ViewCell.View>
                      </ViewCell>
                  </ DataTemplate>
               </ ListView.ItemTemplate>
 </ ListView>

CASE DETAILS VIEWMODEL
 public CaseDetailsViewModel(INavigation navigation)
    {
        IGetDataFromServer cases = new GetDataFromServer();
        Navigation = navigation;
        GetCases = cases.GetCases().FirstOrDefault();
    }
    public CasesFull GetCases { get; set; }

I can navigate to Case Details page, but it is blank.  Maybe I am not passing the reference to the page, or maybe it is something else.
Thanks for your help.

A: I finally solved the problem.
The issue was in my Case Details View Model, as I had to add the Model in all properties of the Cases Details View model (see below).
<ListView ItemsSource="{Binding GetCases}" HasUnevenRows="True">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                            <StackLayout Margin="20,0,20,0">
                                <Label Text="PERSONAL DETAILS" FontSize="Large" TextColor="Black" Margin="0,0,0,20" />
                                <Label Text="Status:" FontSize="14" TextColor="Green"/>
                                <Label Text="{Binding Case.status}"
                            FontSize="12" TextColor="Black" />
                        </StackLayout>
                      </ViewCell.View>
                  </ViewCell>
              </ DataTemplate>
           </ ListView.ItemTemplate>

Where Case is my Model.
If anyone wants to display details of an object, this code can be your solution.
Thanks  Umar3x for your help.


text:
Q: Akka don't elect existing worker node as seed node, once the seed node is killed I am a newbie with akka.
Having a very simple configuration of one seed node and one non-seed node.
Please find below, sequence of operation :-

*

*Seed node started :-

val pConfig = ConfigFactory.load("application.conf").getConfig("PrimaryNode")

val demoSystem = ActorSystem("DemoSystem", pConfig)

[INFO] [04/01/2017 23:42:48.438] [run-main-0] [akka.remote.Remoting] Starting remoting
[INFO] [04/01/2017 23:42:48.673] [run-main-0] [akka.remote.Remoting] Remoting started; listening on addresses :[akka.tcp://DemoSystem@127.0.0.1:2551]
[INFO] [04/01/2017 23:42:48.688] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Starting up...
[INFO] [04/01/2017 23:42:48.759] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Registered cluster JMX MBean [akka:type=Cluster]
[INFO] [04/01/2017 23:42:48.759] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Started up successfully
[INFO] [04/01/2017 23:42:48.776] [DemoSystem-akka.actor.default-dispatcher-3] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Metrics will be retreived from MBeans, and may be incorrect on som
e platforms. To increase metric accuracy add the 'sigar.jar' to the classpath and the appropriate platform-specific native libary to 'java.library.path'. Reason: java.lang.ClassNotFoundException: org.hyperic.sigar.Sigar
[INFO] [04/01/2017 23:42:48.779] [DemoSystem-akka.actor.default-dispatcher-3] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Metrics collection has started successfully
p: akka.actor.ActorSystem = akka://DemoSystem

[INFO] [04/01/2017 23:42:48.795] [DemoSystem-akka.actor.default-dispatcher-2] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Node [akka.tcp://DemoSystem@127.0.0.1:2551] is JOINING, rol
es []
[INFO] [04/01/2017 23:42:48.805] [DemoSystem-akka.actor.default-dispatcher-2] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Leader is moving node [akka.tcp://DemoSystem@127.0.0.1:2551] to [U
p]

*Non-seed node started :-

val sConfig = ConfigFactory.load("application.conf").getConfig("SecondaryNode")
val secSystem = ActorSystem("DemoSystem", sConfig)

[INFO] [04/01/2017 23:44:15.530] [run-main-0] [akka.remote.Remoting] Starting remoting
[INFO] [04/01/2017 23:44:15.845] [run-main-0] [akka.remote.Remoting] Remoting started; listening on addresses :[akka.tcp://DemoSystem@127.0.0.1:49169]
[INFO] [04/01/2017 23:44:15.847] [run-main-0] [akka.remote.Remoting] Remoting now listens on addresses: [akka.tcp://DemoSystem@127.0.0.1:49169]
[INFO] [04/01/2017 23:44:15.854] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Starting up...
[INFO] [04/01/2017 23:44:15.929] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Registered cluster JMX MBean [akka:type=Cluster]
[INFO] [04/01/2017 23:44:15.929] [run-main-0] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Started up successfully
[INFO] [04/01/2017 23:44:15.945] [DemoSystem-akka.actor.default-dispatcher-3] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Metrics will be retreived from MBeans, and may be incorrect on some platforms. To increase metric accuracy add the 'sigar.jar' to the classpath and the appropriate platform-specific native libary to 'java.library.path'. Reason: java.lang.ClassNotFoundException: org.hyperic.sigar.Sigar
[INFO] [04/01/2017 23:44:15.951] [DemoSystem-akka.actor.default-dispatcher-3] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Metrics collection has started successfully
s: akka.actor.ActorSystem = akka://DemoSystem

[INFO] [04/01/2017 23:44:16.265] [DemoSystem-akka.actor.default-dispatcher-14] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Welcome from [akka.tcp://DemoSystem@127.0.0.1:2551]

And seed node moves non-seed node to up (seed node logs after starting
  non-seed node) :-

[INFO] [04/01/2017 23:44:16.190] [DemoSystem-akka.actor.default-dispatcher-14] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Node [akka.tcp://DemoSystem@127.0.0.1:49169] is JOINING, roles []

[INFO] [04/01/2017 23:44:16.782] [DemoSystem-akka.actor.default-dispatcher-25] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:2551] - Leader is moving node [akka.tcp://DemoSystem@127.0.0.1:49169] to [Up]

*Now seed node is killed (logs on non seed node says, that seed node is quaretined) :-

............
............

[WARN] [04/01/2017 23:46:14.301] [DemoSystem-akka.remote.default-remote-dispatcher-6] [akka.tcp://DemoSystem@127.0.0.1:49169/system/endpointManager/reliableEndpointWriter-akka.tcp%3A%2F%2FDemoSystem%40127.0.0.1%3A2551-2] Association with remote system [akka.tcp://DemoSystem@127.0.0.1:2551] has failed, address is now gated for [5000] ms. Reason: [Association failed with [akka.tcp://DemoSystem@127.0.0.1:2551]] Caused by: [Connection refused: no further information: /127.0.0.1:2551]
[INFO] [04/01/2017 23:46:14.959] [DemoSystem-akka.actor.default-dispatcher-21] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Leader is auto-downing unreachable node [akka.tcp://DemoSystem@127.0.0.1:2551]
[INFO] [04/01/2017 23:46:14.960] [DemoSystem-akka.actor.default-dispatcher-20] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Marking unreachable node [akka.tcp://DemoSystem@127.0.0.1:2551] as [Down]
[INFO] [04/01/2017 23:46:15.953] [DemoSystem-akka.actor.default-dispatcher-21] [akka.cluster.Cluster(akka://DemoSystem)] Cluster Node [akka.tcp://DemoSystem@127.0.0.1:49169] - Leader is removing unreachable node [akka.tcp://DemoSystem@127.0.0.1:2551]
[WARN] [04/01/2017 23:46:15.953] [DemoSystem-akka.remote.default-remote-dispatcher-5] [akka.remote.Remoting] Association to [akka.tcp://DemoSystem@127.0.0.1:2551] having UID [-273153546] is irrecoverably failed. UID is now quarantined and all messages to this UID will be delivered to dead letters. Remote actorsystem must be restarted to recover from this situation.

Now when i check the following things on non-seed node console :-

*

*which node is the leader

Leader ship is successfully transferred to the non seed node
scala> val cluster = Cluster(secSystem)

scala> cluster.state
res1: akka.cluster.ClusterEvent.CurrentClusterState = CurrentClusterState(TreeSet(Member(address = akka.tcp://DemoSystem@127.0.0.1:49169, status = Up)),Set(),Set(akka.tcp://DemoSystem@127.0.0.1:49169),Some(akka.tcp://DemoSystem@127.0.0.1:49169),Map())

scala> cluster.state.leader
res2: Option[akka.actor.Address] = Some(akka.tcp://DemoSystem@127.0.0.1:49169)

*which node is the seed node :-

Seed node still points to the dead node
scala> cluster.settings.SeedNodes
res0: scala.collection.immutable.IndexedSeq[akka.actor.Address] = Vector(akka.tcp://DemoSystem@127.0.0.1:2551)

I was thinking, that the non-seed node will be elected as a new seed node, but that was not the case.
Also, please find below configuration of two nodes :-
PrimaryNode {
  akka {
    actor {
      provider = "akka.cluster.ClusterActorRefProvider"
    }
    remote {
      log-remote-lifecycle-events = off
      enabled-transports = ["akka.remote.netty.tcp"]
      netty.tcp {
        hostname = "127.0.0.1"
        port = 2551
      }
    }
    cluster {
      seed-nodes = ["akka.tcp://DemoSystem@127.0.0.1:2551"]
      auto-down-unreachable-after = 10s
    }
  }
}

SecondaryNode {
  akka {
    actor {
      provider = "akka.cluster.ClusterActorRefProvider"
    }
    remote {
      enabled-transports = ["akka.remote.netty.tcp"]
      netty.tcp {
        hostname = "127.0.0.1"
        port = 49169
      }
    }
    cluster {
        seed-nodes = ["akka.tcp://DemoSystem@127.0.0.1:2551"]
        auto-down-unreachable-after = 10s
    }
  }
}

Please enlighten me. Why the non seed node was not elected as new seed node once the previous seed node was killed.

A: Sorry that I have very little time now, I'll try my best in a few words.
There's no such thing as seed node election.
Once an akka cluster has booted, every cluster member can act as a seed node for a joining node i.e., be used as initial contact point by any joining node. And this happens without configuration as all cluster nodes listen for incoming connections.
Before a cluster has booted though, the (first) seed node is very important as it is required to be part of the initial nodes available when starting up the cluster. Without that node, the cluster won't be able to boot. But once booted (as said above), that seed node can disappear and everything will be still fine.
This is most likely why the value of cluster.settings.SeedNodes doesn't change or is not updated. It has no impact after initial cluster setup.
references:

*

*http://doc.akka.io/docs/akka/2.4.17/common/cluster.html#Seed_Nodes

*http://doc.akka.io/docs/akka/2.4.17/scala/cluster-usage.html#Joining_to_Seed_Nodes


text:
Q: How can I 'not allow' the user to retrieve same information from the server multiple times in my 'React' Weather-app? I'm learning React and as a practice I'm building a weather-app.
My App Photo
Everything is ok. but I want When a User type a City name for example 'London' and click the Search button and get the data . the next search if it's 'london' (which is currently visible) i don't want my handleGetData function to call server for data.
How should implement this logic ? What should i change? I will appreciate your help
import React, { Component } from "react";
import InputSearch from "./common/inputSearch";
import http from "../services/httpService";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import Weather from "./weather";

class App extends Component {
  state = {
    city: {
      name: "",
      info: [],
    },
  };

  handleChange = (e) => {
    const city = this.state.city;
    city.name = e.currentTarget.value;
    this.setState({ city });
  };

  handleGetData = async () => {
    try {
      const city = this.state.city;
      const apiEndPoint = `http://api.weatherapi.com/v1/forecast.json?key=97de37820e0e4a29b9c90051221604&q=${city.name}&days=3&aqi=no&alerts=no`;
      const { data } = await http.get(apiEndPoint);
      city.info = data;
      this.setState({ city });
    } catch (e) {
      const expectedError =
        e.response.status && e.response.status > 400 && e.response.status < 500;
      if (expectedError) {
        toast.error("Something failed while getting Data");
      }
    }
  };

  render() {
    const { city } = this.state;
    return (
      <React.Fragment>
        <ToastContainer />
        <InputSearch
          stateCityName={city.name}
          onChanges={this.handleChange}
          onGettingData={this.handleGetData}
        />
        <Weather data={city.info} data2={city} />
      </React.Fragment>
    );
  }
}

export default App;

A: You can use a new state as your previousSearch and compare it with your current search
It's something like this but I didn't test it though so you may have to do some modification
    state = {
        city: {
            name: "",
            info: [],
        },
        previousSearch: "",
    };

    handleChange = (e) => {
    const city = this.state.city;
    prevCity = city.name;
    city.name = e.currentTarget.value;
    this.setState({ city, previousSearch: prevCity });
    };

  handleGetData = async () => {
    try {
      const city = this.state.city;
      if(previousSearch !== city.name) {
        const apiEndPoint = `http://api.weatherapi.com/v1/forecast.json?key=97de37820e0e4a29b9c90051221604&q=${city.name}&days=3&aqi=no&alerts=no`;
        const { data } = await http.get(apiEndPoint);
        city.info = data;
        this.setState({ city });
      }

    } catch (e) {
      const expectedError =
        e.response.status && e.response.status > 400 && e.response.status < 500;
      if (expectedError) {
        toast.error("Something failed while getting Data");
      }
    }
  };

Have fun


text:
Q: php objects: property Object Vs stdClass Object - which one is better? Sometimes I use __get or stdClass to convert arrays to object. But I can't decide I should stick to. I wonder which one is better and faster, any ideas?
class property
{

    public function __get($name)
    {
        return (isset($this->$name)) ? $this->$name : null;
    }
}

$object = new property();
$object = new stdClass();

so if I use new property(), I will have a property object output,
property Object
(
....
)

while if I use new stdClass(), I will have a stdClass object output,
stdClass Object
(
....
)

so I can get the object data like this $item->title.
EDIT:
how I do the actual array to object conversion.
public function array_to_object($array = array(), $property_overloading = false)
    {

        # If $array is not an array, let's make it array with one value of former $array.
        if (!is_array($array)) return $array;

        # Use property overloading to handle inaccessible properties, if overloading is set to be true.
        # Else use std object.
        if($property_overloading === true) $object = new property();
            else $object = new stdClass();

        foreach($array as $key => $value)
        {
            $key = (string) $key ;
            $object->$key = is_array($value) ? self::array_to_object($value, $property_overloading) : $value;
        }

        return $object;
    }

A: First off, an (almost) empty class definition like you have is almost like an stdClass so there won't be any major issues by using either.
That said, one advantage your "named" class has over stdClass is that you can define what happens when a non-existent property is being accessed by taking advantage of the __get magic method.
class property
{
   public function __get($name)
   {
       return null;
   }
}

The above is a simpler rewrite of your original property class; when __get() is being called, you already know that $this->$name is not set. Although this won't cause a notice, it doesn't prevent a fatal error when you try to reference $obj->bla->bla where $obj->bla doesn't exist.
It might be more useful to throw an exception when a non-existent property is being accessed:
class property
{
   public function __get($name)
   {
       throw new Exception("Property $name is not defined");
   }
}

This allows your code to catch the exception before it turns into a fatal runtime error that stops your script altogether.

A: If you just use your "property" class as a dumb data container, take stdClass or even an array.


text:
Q: ReferenceProperty relations not working properly in Google App Engine with Django I am working on an application using Google application engine and Django. I am using app engine patch. Some of the models have ReferenceProperty fields.
The issue is that when I am deleting some entries of the Referenced model, it should delete the entries where this ReferenceProperty is being used following the foreign key kind of relation. But actually it is not happening. The field remains without the deleted field and which is causing an error message:
ReferenceProperty failed to be resolved

Following is an example of the model:
class Topic(db.Model):
  title = db.StringProperty(required = True)
  body = db.TextProperty(required = True)
  category = db.ReferenceProperty(Category,required = True)
  status = db.StringProperty(default="open")
  creator = db.ReferenceProperty(User,required = True)

class Category(db.Model):
  name = db.StringProperty(required = True)
  creation_date = db.DateTimeProperty(auto_now_add=True)
  creator = db.ReferenceProperty(User,required = True)
  class Meta:
    verbose_name = "Category"
    verbose_name_plural = "Categories"
  def __unicode__(self):
    return '%s' % (self.name)

When I am deleting some of the categories, the related topics should also be deleted. But the topics are not deleted and cause the "ReferenceProperty failed to be resolved error" message.
Please suggest.
Thanks in advance.

A: This happens when the reference you are attempting to follow leads to a nonexistent entity - probably because you've already deleted it. Since you're trying to delete it anyway, you should simply catch and ignore this exception.


text:
Q: Silverlight application with external web service references I have a standalone Silverlight 4 application that has a service reference from a WCF project different from the web site where the SL object is stored (used). The service url are hardcoded  and the web site where my SL object is stored (used) was not generated using the project wizard (in which you create the Silverlight project and its web site).
So, my questions are:

*

*how could I stop using hardcoded url values from SL?(from the
serviceReference.client file)

*how could I fix the Wcf service port value? (everytime it chooses a different port value: like localhost:randomPort/... to keep the randomPort fixed )?

*how can I debug the SL project once it is loaded? (followed the steps from here but it keeps throwing the error 2104 unable to download the silverlight client. check your web server settings)

A: For Hardcoded URLs:
var serviceClient = new YourServiceReference.ServiceClient();
 serviceClient.Endpoint.Address=new EndpointAddress("http://yourservice.com/Service.svc");
How could I fix the Wcf service port value?
In WCF Project properties go to WEB ->Servers -> Use Visual Studio Development Server ->Specific Port [add port you want] or you can setup your service on your local IIS


text:
Q: Redirect javascript Form I am trying to figure out how to make a form rediect for my website.
<form id="redirect_form" method="POST" action="http://mypage.net/index.php?autojoin=">
    <input type="TEXT" name="field_1" value="<?php echo htmlentities($_GET ['autojoin']); ?>">
</form>
<script type="text/javascript">
    document.getElementById('redirect_form').submit();
</script>

If I want to type in the box TheLobby, I want it to redirect to http://mypage.net/index.php?autojoin=TheLobby
I can't figure out why when I go to the page I have it just auto directs over to http://mypage.net/index.php?autojoin=

A: Your script is submitting the form even before a user can enter any details.
Instead use this code:
<form id="redirect_form" method="POST" action="http://mypage.net/index.php?autojoin=">
    <input type="text" name="field_1" value="<?php echo htmlentities($_GET ['autojoin']); ?>">
    <input type="submit" name="submit" value="submit">
</form>


text:
Q: Extending Internal Link and External Link to allow selection of Images I need to extend selection of external and Internal Link and provide a image selection.
Please see the snapshot in the below :

Here the above snapshot allows you to add properties for External Link.In the same popup can we add a field Called Image(as shown in screenshot) which will allow user to select images from the media library??
Thanks,
Suhas

A: If you are using Sitecore 7.2 and want to update internal link then you need to do with Sitecore speak and in case of external link simply update under /shell/Applications/Dialogs/ExternalLink folder.
To render this field create CustomLinkRenderer class and inheri this class by LinkRenderer of Sitecore.Kernel.dll.
Please see below code for CustomLinkRenderer

public class CustomLinkRenderer : LinkRenderer
    {
        public CustomLinkRenderer(Item item)
            : base(item)
        {

        }
        public override RenderFieldResult Render()
        {
            string str8;
            SafeDictionary<string> dictionary = new SafeDictionary<string>();
            dictionary.AddRange(this.Parameters);
            if (MainUtil.GetBool(dictionary["endlink"], false))
            {
                return RenderFieldResult.EndLink;
            }
            Set<string> set = Set<string>.Create(new string[] { "field", "select", "text", "haschildren", "before", "after", "enclosingtag", "fieldname" });
            LinkField linkField = this.LinkField;
            if (linkField != null)
            {
                dictionary["title"] = StringUtil.GetString(new string[] { dictionary["title"], linkField.Title });
                dictionary["target"] = StringUtil.GetString(new string[] { dictionary["target"], linkField.Target });
                dictionary["class"] = StringUtil.GetString(new string[] { dictionary["class"], linkField.Class });
            }
            string str = string.Empty;
            string rawParameters = this.RawParameters;
            if (!string.IsNullOrEmpty(rawParameters) && (rawParameters.IndexOfAny(new char[] { '=', '&' }) < 0))
            {
                str = rawParameters;
            }
            if (string.IsNullOrEmpty(str))
            {
                Item targetItem = this.TargetItem;
                string str3 = (targetItem != null) ? targetItem.DisplayName : string.Empty;
                string str4 = (linkField != null) ? linkField.Text : string.Empty;
                str = StringUtil.GetString(new string[] { str, dictionary["text"], str4, str3 });
            }
            string url = this.GetUrl(linkField);
            if (((str8 = this.LinkType) != null) && (str8 == "javascript"))
            {
                dictionary["href"] = "#";
                dictionary["onclick"] = StringUtil.GetString(new string[] { dictionary["onclick"], url });
            }
            else
            {
                dictionary["href"] = HttpUtility.HtmlEncode(StringUtil.GetString(new string[] { dictionary["href"], url }));
            }
            // Add onclick attribute for Google event tracking
            dictionary["onclick"] = LinkField.GetAttribute("on_click");
            StringBuilder tag = new StringBuilder("<a", 0x2f);
            foreach (KeyValuePair<string, string> pair in dictionary)
            {
                string key = pair.Key;
                string str7 = pair.Value;
                if (!set.Contains(key.ToLowerInvariant()))
                {
                    FieldRendererBase.AddAttribute(tag, key, str7);
                }
            }
            tag.Append('>');
            if (!MainUtil.GetBool(dictionary["haschildren"], false))
            {
                if (string.IsNullOrEmpty(str))
                {
                    return RenderFieldResult.Empty;
                }
                tag.Append(str);
            }
            return new RenderFieldResult { FirstPart = tag.ToString(), LastPart = "</a>" };
        }
    }

You need to extend this class as per your need to render image.

A: If you are talking about a whole field and not just an external link inside of a rich text field, you should create a custom field based on the documentation to do so in SDN:
http://sdn.sitecore.net/Articles/API/Creating%20a%20Composite%20Custom%20Field.aspx
You can inherit most functionality from the current link field.

A: You can actually extend any dialog by editing the xml files in /shell/Applications/Dialogs
In another thread I have shown how to add a maxlength to the title field, that should help you get on your way: Limit number of Characters entered for Link Title Field in General Link


text:
Q: history.js + Google Let's talk about AJAX-crawling by google:
Since history.js is a nice alternative to ugly hashbang urls I was wondering about one certain issue:
For HTML5 browsers, nice urls are created if ajax-content is loaded and should be indexed by google. For none-HTML5 browsers (e.g. IE 9 does not support history.pushState) the old hashbang is used.
So which version is seen by google? Are there any risks google sees duplicate content (one time with nice url, one time with hashbang) ?
Thank you for any thoughts on that.

A: If a ajax page needs to be indexed with google we need to server a html snapshot of the page from the server.
For ex: xyz.com/page1#!name=john
Google crawler finds this #! identifier and requests http://xyz.com/page1?_escaped_fragment_=name=john
This way our server can server the html snapshot of the page.
Now when our URLs are prettified and appended with #! ajax pages will be indexed.
For pages with only # appended in the URLs, google crawler won;t be able to see the content loaded via ajax and it won't be indexed. So there won't be any possibility of duplication
We can also use the link tag in the head section of the page with rel cannonical url pointing to the mail url. See http://googlewebmastercentral.blogspot.in/2009/02/specify-your-canonical.html for reference.

A: HTML
link1
link2

JavaScript
$(document).on('click', '[data-history]', function(e){
    e.preventDefault();
    History.pushState($(this).data().history, this.title, this.href);
})

For client with JavaScript enabled, the hisotory.js will handle this to an AJAX request, for client without JavaScript, it will request the normal page.

A: I would recommend to use solely HTML5 History API for browsers that support the API (about 70% of browsers) while serving regular static pages to browsers that do not. This way, there will be no possibility that search engines will see anything different from full canonical static URLs.


text:
Q: Generating liquibase xml file from current database I have tried to create liquibase XML existing from MySQL database. My goal is to generate liquibase XML schema from MySQL database.
Any way to achieve this solution.
I have already tried with dropwizard command
java -jar myjar-4.1.0.jar --changeLogFile="generate.xml" --diffTypes="data" generateChangeLog

but it does not work for me.

A: After trying so many time finally I got my solution.
Follow following steps to generate migration from existing MySQL database.
Add initial migrations.xml into the project with below lines.
<?xml version="1.0" encoding="UTF-8"?>
    <databaseChangeLog
            xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
             http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd">
    </databaseChangeLog>

Run: above migration with "db migrate" for dropwizard,  it'll create databaseChangeLog and databaseChangeLogLock tables into Database.
Run Following command as per requirement.
Command Syntax :
liquibase --driver=com.mysql.jdbc.Driver --classpath=[path to db driver jar] --changeLogFile=[Path to above migration.xml]  --url=[Database URL] --username=[Username] --password=[Password] [command parameters]

U can refer this link or link for above common parameter
Note:
Command require [path to DB driver jar], JDBC.jar file for this if you don't have.


text:
Q: Show tooltip at top using jquery I am using this jquery tooltip to show the description for my link buttons. But this tooltip is getting displayed at the bottom and how can I display the tooltip at the top of my link button.
https://jqueryui.com/tooltip/
HTML:

<title></title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

<link rel="stylesheet" href="/resources/demos/style.css">

<form id="form1" runat="server">

Department

                    Manufacturer

                    ToolTip

</form>

A: Use the position property when declaring the tooltip.
$( ... ).tooltip({
    position: {
        my: "center bottom", // the "anchor point" in the tooltip element
        at: "center top", // the position of that anchor point relative to selected element
    },
    // other properties
});

A: See this link: http://api.jqueryui.com/tooltip/#option-position
And in action here (based on EyasSH answer)
$( document ).tooltip({
    position: {
        my: "center bottom", // the "anchor point" in the tooltip element
        at: "center top", // the position of that anchor point relative to selected element
    }
});

If your tooltip is too large you can offset your anchor further by using -40 after bottom in the my field:
$( document ).tooltip({
    position: {
        my: "center bottom-40", // the "anchor point" in the tooltip element
        at: "center top", // the position of that anchor point relative to selected element
    }
});


text:
Q: Can I estimate the optimal proportions of ingredients in a blend? I'm trying to find the optimal blend of 4 ingredients, to maximize liking of a beverage.
I can write a function for liking such as:

Liking is on a scale of 0 - 1 (0% - 100%).
I conducted 10 taste tests to gather data, then estimated a simple regression (this is in R):
# Data on blends tested in taste tests
X    <- rbind( c(.93,   .01,   0.03, .03 ),
               c(.92,   .02,   0.03, .03 ),
               c(.94,   .00,   0.03, .03 ),
               c(.94,   .02,   0.02, .02 ),
               c(.91,   .03,   0.03, .03 ),
               c(.97,   .01,   0.01, .01 ),
               c(1,     .00,   0.00, .00 ),
               c(.92,   .01,   0.03, .04 ),
               c(1,     .00,   0.00, .00 ),
               c(.87,   .05,   0.04, .04 )
               )
# Liking results from taste tests
Y <- c(0.841217,
        0.841213,
        0.84121,
        0.84121,
        0.841204,
        0.841201,
        0.8412,
        0.841187,
        0.841187,
        0.841172)

# Regression analysis (no intercept model)
glm(Y~X-1)

The results of the regression analysis were:
Call:  glm(formula = Y ~ X - 1)

Coefficients:
    X1      X2      X3      X4
0.8412  0.8404  0.8445  0.8386

Degrees of Freedom: 10 Total (i.e. Null);  6 Residual
Null Deviance:      7.076
Residual Deviance: 8.169e-10    AIC: -193.9

So, this gives me some insight as to the relative weight of each ingredient in determining liking, but it doesn't directly tell me which levels of the ingredients I should set to maximize liking. Of course, I could specify this model differently, such as using the binomial distribution or testing interactions, or worry about my small sample size, but I'm trying to keep it simple for now and focus on finding the right methodological framework for what I'm trying to do.
I was thinking that I could set up some sort of optimization function to determine the best levels (ingredient proportions) based on:

*

*The weights from the regression

*The constraint that the sum of the ingredients' proportions adds up to 1 (i.e. 100%)

*An objective function that specifies maximization of liking

*A constraint that liking is between 0 and 1

However, it's not clear to me how I can setup such an optimization model.
Am I heading in a reasonable direction? Is optimization the appropriate tool and, if so, how can such an optimization be setup (mapping the examples I found in various optimization packages to this use case was a point of confusion for me)?
Or, is it possible to determine the optimal levels directly from the regression results?

A: Mathematical optimization is a tool that is often used to optimize a decision given some objective function and some constraints.
In your case, the decision variables would be the amount of each ingredient (we'll call them $X_1$, $X_2$, $X_3$, and $X_4$), and the optimization would take the form of a linear program:
\begin{align*}
\max_{X_1,X_2,X_3,X_4} &~ ~~0.8412X_1 + 0.8404X_2 + 0.8445X_3 + 0.8386X_4 \\
s.t. &~ ~~X_1+X_2+X_3+X_4 \leq 1 \\
&~ ~~0.8412X_1 + 0.8404X_2 + 0.8445X_3 + 0.8386X_4 \leq 1 \\
&~ ~~X_1, X_2, X_3, X_4 \geq 0 \\
\end{align*}
If you had your coefficients from your model in a vector coef in R, this could be implemented with the lpSolve package as:
library(lpSolve)
coef <- c(0.8412, 0.8404, 0.8445, 0.8386)
mod <- lp(direction = "max",
          objective.in = coef,
          const.mat = rbind(rep(1, length(coef)), coef),
          const.dir = c("<=", "<="),
          const.rhs = c(1, 1))
mod$solution
# [1] 0 0 1 0

Rather unsurprisingly in this case, the optimization model simply selects 100% of the ingredient with the maximum coefficient.
To summarize, mathematical optimization could be used to identify ingredient proportions yielding the highest predicted value, but with the current simple constraints you could probably solve the optimization problem of interest by inspection.

A: You might want to check out Beta Regression, which is a form of GLM based on a Beta distribution. A similar question was answered here. The corresponding R package is betareg

A: A late response, but the issue is interesting.
This problem can be easily transformed into one where the variables are not proportions. Rather than focusing on the proportions of the ingredients, you would focus on how much of each ingredient you add to a standard measure of vodka. That way, you variables become absolute measures that have no upper bound. The vodka variable is then omitted (it is redundant, as it would be 1 in all cases).
d <- cbind(Y, X[,-1] / X[,1])
colnames(d) <- c("Like", "peach", "peppermint", "juice")
d <- as.data.frame(d)

Now you can do a regression type analysis. With the model, you could use a combination of function predict() and optimization to find the best mix.
But unfortunately you have too little data to run a meaningful regression, so for now, continue mixing!


text:
Q: Why is the JVM not platform independent, given that Java (the language) is platform independent? Just curious to know when java is made platform independent then are there any specific reasons JVM is made platform dependent..

A: Because there needs to be some way to convert the platform-independent application's Java calls to calls that are compatible with the underlying OS.

A: No, JVMs are not platform independent. In fact they are platform specific run time environment provided by the vendor. Each platform (Windows, UNIX, Mac etc) has its own JVM to run Java applications. Although the byte code supports connection to multiple databases..
Think of Music being played in a MP3 player, CD player and old faithful cassette players(Boom Box). The output is always the same, ie music. But the input (media ie .mp3 files for MP3 Players, CDs for CD Players and cassettes for Cassette Players) vary depending on the system [here the systems will be the various Operating Systems like Windows, UNIX, Mac etc..]. Hope i was able to solve your problem..

A: The JVM executes Java code, but is written in platform specific languages such as C/C++/ASM etc. The JVM is not written in Java and hence cannot be platform independent.

A: I found that this was a great answer to the question:

JVM translates bytecode into machine language
Every Java program is
  compiled into an intermediate language called Java bytecode. The JVM
  is used to both translate the bytecode into the machine language for a
  particular computer, and actually execute the corresponding
  machine-language instructions as well. The JVM and bytecode combined
  give Java its status as a "portable" language.
Machine language is OS dependent
Given the previous information, it should be easier to deduce an
  answer to the question. Since the JVM must translate the bytecode into
  machine language, and since the machine language depends on the
  operating system being used, it is clear that the JVM is platform
  (operating system) dependent. This fact can be verified by trying to
  download the JVM – you will be given a list of JVM's corresponding to
  different operating systems, and you will obviously pick whichever JVM
  is targeted for the operating system that you are running.

Quoted from Is the JVM Platform Dependent?

A: Unless you have a CPU that can directly execute Java bytecode (there are such things) you need to be able to interact with the OS (for things like reading files, connecting to the network, displaying to the screen, etc...).
You can write a JVM in other languages (such as Java or JavaScript) but ultimately there needs to be something that can interact with the underlying OS.

A: The JVM must be platform dependent to allow your Java to run on the specific platform. A JVM for Windows will translate your Java into different system calls than a JVM for OS X.

A: JVM depends on operating system. For the code to be independent, something should be dependent and that is JVM. While downloading JDK it asks for which OS you want to download it for. Which clearly implies that JVM is platform dependent.

A: The JVM is not platform independent
The key here is that the JVM depends on the operating system – so if you are running Mac OS X you will have a different JVM than if you are running Windows or some other operating system. This fact can be verified by trying to download the JVM for your particular machine – when trying to download it, you will be given a list of JVM's corresponding to different operating systems, and you will obviously pick whichever JVM is targeted for the operating system that you are running.

A: simply like - * - makes a +.
We all know Java is platform independent
but OS where we write the code is platform dependant
and Output should be platform independent
so, we make jvm (which is in-between and installed with jre) platform dependent so that the output is independent.

A: I think that it could be platform independent if many different languages (each one written in specific different platform )where combined to make it change its own code dynamically.But all these take some great effort to happen and maybe destroy its portability.

A: JVM translate the byte code which is universal to machine code which is machine dependent hence JVM is platform dependent. Due to this byte code java is platform independent.

A: No, JVM is platform dependent. The code written in Java is not platform dependent. If you write Java code on a Windows operating system you can run that code on Linux or other operating Systems. But the JVM for Windows and Linux is different. JVM are found in JRE and when you download JRE from Oracle it says JRE for Window, Linux and other operating systems

A: JVM is platform dependent because it takes java byte code and generates byte code for the current operating system. So Java software is platform dependent but Java language is platform independent because different operating system have different JVMs.

A:
Hope this image can make it clear.
When you install java on your machine, you are asked to select your OS.
That means java to be installed on a Windows machine is not the same as the one on a mac.
Java installation comes with JDK, JRE, and JVM that are OS-specific.
JDK has a compiler that converts your Java code to bytecode and bytecode is platform-independent. JVM can read this bytecode and using an interpreter convert them to OS-specific instructions which vary based on your OS.
All JDK, JRE, and JVM are platform-dependent. But JAVA is platform-independent because bytecode is platform-independent.
Content summarized from here

A: It is platform-independent. Because java has bytecode it is platform-independent. So, when it writes once run everywhere.


text:
Q: A way to describe my interest in getting to know people's stories I want to be able to phrase the interest I have in meeting new people and talking to them about their life stories and experiences.
It is a level deeper than just an extrovert, who would be someone who likes to meet new people. I like getting to know them better.
Though it's also not someone who likes to make a lot of friends. Just meeting people, have great conversations, and move on ahead.
It is for an application of sorts and I want to be able to mention this specific interest I have.

A: Social, friendly, empatic, I would say

A: The word you are looking for here is empathy
The quality of being able to hear out another person, and not just because it makes them feel better, but because you love doing it; that's empathy. The person is then said to be empathetic in nature.

An empathetic person is someone who can share another person's feelings. If you tell an empathetic person that your heart is broken, she might touch her own heart and gaze at you sadly through moist eyes.

"Empathetic is a recent term; it comes from empathy, which was coined by the German philosopher Rudolf Lotze in 1858. Lotze believed that when you look at a work of art, you project your own sensibilities onto it. So if you feel sad when you see a painting of a woman weeping over a dying lover, that's because you can imagine what it's like to lose someone you love."...Reference


text:
Q: Where to use MongoDB and where MySQL? I am thinking about using one of two databases - MySQL and MongoDB. I am planning to storing text and numeric data and I will building my app in RoR.
So I don't know, which database system could be better for this purpose - can you help me, please, under which criterium I will decide?

A: I have used also MySQL and MongoDB with Mongoid in my projects, and I can say that if you want to keep binary data like images, mp3s and other stuff in your database so try Mongo, for other reasons you can use SQL databases. MongoDB has no structure - you processing the hash, so you can dynamicly add and remove keys/columns.
In your case I would use MySQL.

A: In my opinion you should base your decision on the purpose of your application. Do you want to search through your text data, how will you define keys. There is little use in going for MySQL if you have to request each record and scan it. Even if there is functionality to do text scans in MySQL (does it have that?) MongoDB will probably do the job more efficiently. The other way around, if you are not going to use MongoDB's strong points then you might as well go for MySQL.
Another factor might be the deadline for implementing something. If you need it fast, don't waste time on learning something new. If you have time to experiment, figure out the key features you will most likely rely upon in your application.

A: Let me cast this question within more general setting and into some historical perspective.
In the 60s they were asking whether to use hierarchical or network database
In the 70s the debate was relational against network
In the 80s Relational turned into SQL databases, so question mutated to SQL vs. network
In the 90s it was SQL against object databases
In 00s it was SQL against XML databases
Today we have SQL vs. NoSQL
Do you see a pattern here? Would you still bet some money onto SQL competitor, especially if it's nothing more than glorified hash table?

A: I think, if you need a hard structure you should use MySQL because it't its nature, but if you need something more dynamic, whith no structure at all (schema-less) you should use MongoDB, I've never use MongoDB but I know it's more object/document oriented.

A: It would be helpful if you could provide some more detail. Would your data easily fit into a schema, or do you need the flexibility that a document store offers? What about auto-sharding, etc? Without more information, no one can give you advice that fits your needs. Lacking that, you can't hope for feedback any better than people's personal preferences, which is little more than a flamewar waiting to happen.


text:
Q: Passing arguments to jQuery event handler while creating an object I'm creating an object dynamically and binding onclick event to it:
jQuery('<a/>', {
    click: function() { foo(arg1, arg2) },
    ...
})

Everything is working fine. The question is if it can be simplified so I don't need funciton() wrapper for calling foo function with arguments?
Thanks in advance.

A: You can't pass additional arguments to jQuery event handlers, jQuery passes the event object as the one argument to event handlers.
In jQuery 1.7 and up, the on() function allows you to extend the event object by passing an object containing the data you want to use inside your handler. You can access the data on the event.data object
function foo(event) {
    event.data.arg1;
    event.data.arg2;
}

jQuery('<a/>').on('click', {arg1: val1, arg2: val2}, foo)

A: The extra closure provided by the anonymous function is a necessary step — unless you can be certain of ECMAscript 5 support (IE8 and below don't), in which case you can use the bind method:
jQuery('<a/>', {
    click: foo.bind(this, arg1, arg2)
})

You can still use this method in IE8 and below if you're willing to include the Underscore micro-library, which contains a shim for bind:
jQuery('<a/>', {
    click: _.bind(foo, this, arg1, arg2)
})

If you can't do either of these, then you're out of luck!


text:
Q: Is there one word/phrase for a village or city that is recently established? I am looking for a word or phrase or even something like a idiom to describe a city or village or a colony that has been newly or freshly established and thus does not things like government or a well structured society.
Primary focus should be that it is established newly, so words like 'anarchy' don't work. 'Virgin' cannot be used to describe a society I guess.
For example

Vandals roam in your _____ city so you pick up your gun and with help
  of your friends you lock them inside your basement, one by one.

I have looked that thesaurus for new, but I find no word appealing.
Any connotation should work.
A compound word will also work fine.


text:
Q: Java Reactor Pattern with java.io Package I see in several application source like Minecraft and JIrcs they both use java.io to implement Reactor Plugin (if I'm not wrong) and also in this article. So, what is the difference between java.io and java.nio when implementing Reactor Pattern? I mean, like performance advantage, process efficiency etc and where i can get good tutorial if you think java.io is the good solution to implement Reactor Pattern (since google give me tons of java.nio tuts not java.io as i want)

A: It isn't really true that NIO is faster. Paul Tyma demolished that myth sometime back.
http://mailinator.blogspot.in/2008/02/kill-myth-please-nio-is-not-faster-than.html
http://paultyma.blogspot.in/2008/03/writing-java-multithreaded-servers.html
Hope that help.

A: I hope you can get a conclusion with the below information taken from the book
at page no.42

java.io.* classes use the decorator design pattern. The decorator
  design pattern attaches responsibilities to objects at runtime.
  Decorators are more flexible than inheritance because the
  inheritance attaches responsibility to classes at compile time. The java.io.* classes use the decorator pattern to construct different
  combinations of behaviour at runtime based on some basic classes.

and 43.

Java has no long been suited for developing programs that perform a
  lot of I/O operations. Furthermore, commonly needed tasks such as file
  locking, non-blocking and asynchronous I/O operations and ability to
  map file to memory were not available. Non-blocking I/O operations
  were achieved through work around such as multithreading or using JNI.
  The New I/O API (aka NIO) in J2SE 1/4 has changed this
  situation.
         A server's availability to handle several client requests effectively depends on how it uses I/O streams. When a server has to
  handle hundreds of clients simultaneously, it must be able to use I/O
  services concurrenty, one way to cater for this scenario in Java is to
  use threads but having almost one-to-one ratio of threads (100 clients
  will have 100 threads) is prone to anormous thread overhead and can
  result in performance and scalability problems due to consumtion of
  memory stacks (i.e. each thread has its stack, Refer Q34,
  Q42 in Java section) and CPU context switching(i.e. switching between threads as opposed to doing real computation.). To overcome
  this problem, a new set of non-blocking I/O classes have been
  introduced to the Java platform in java.nio package. The non-blocking
  I/O mechanism is built around Selectors and channels. Channels,
  Buffers and Selectors are the core of the NIO.

and read more.
Here are some reference links which provide Java IO vs Java NIO :
Java IO Faster Than NIO – Old is New Again!, Java IO vs Java NIO and IO vs. NIO – Interruptions, Timeouts and Buffers.

A: It is important to understand the differences between blocking and non-blocking I/O. The java.io package does NOT support non-blocking I/O so it won't scale for a large number of connections. Moreover, with blocking I/O you can only resort to the terrible one-client-to-one-thread model which is completely unsuitable for low-latency systems. I suggest you take a look on this article written by me about an asynchronous network I/O library that implements the reactor pattern, so you can understand how non-blocking plays a key role in high-performance systems.


text:
Q: Date validation using jquery, prevent entering yeterdays date. I am trying to validate a date input field.
I can prevent jquery datepicker to prevent from entering old dates using,
 $('#delivery_date').datePicker({ minDate: 0 });

But user can still enter date manually. How to prevent or validate this?

A: // when the field changes value
$('#delivery_date').on('change',function(){
    var today = new Date();
    today = new Date(today.getYear(), today.getMonth(), today.getDate());
    // compare the value of the field with whatever you want to test against
    if($(this).val() > today){
         // if the test fails, change the value to default
         $(this).datepicker('setDate', new Date());
    }
})

A: $('#delivery_date').on('change', function(){
    var today = new Date();
    if(new Date($(this).val()) < new Date(today.getYear(), today.getMonth() - 1, today.getDate()) $(this).datepicker('setDate', new Date());
});


text:
Q: Where can I find a list of create-react-app options? I know create-react-app can accept the flag--typescript for creating a project with TypeScript, but I couldn't find the complete options list anywhere.
Is this the only flag it supports for project creation?

A: Found it thanks to @JJJ
npx create-react-app --help


text:
Q: How to get POINT OF VIEW of specific Place using Google Maps I want to use Google Places Autocomplete - Per Session, with Place Details included, and when an user clicks on an item, display a Google Map StreetView with the Place.
The way I was trying to do was: when a user clicks on an autocomplete-list, I use getPlace() function for getting geometry.coordinates (lat and long), and initialize Google Map Street View with that information.
The problem is the start point of view of Google Map Street View, that is random.
Do you know how can I solve it? I think I can't get that information with Place Details. Is there any other way?
Thanks!

A: From the Places API, get the place coordinates.

Example: Belgian Embassy, Paris returns 48.87501200000001, 2.2944579999999632

Now use these coordinates to get Street View:

Obviously, it doesn't show the Belgian Embassy.
At the time the Panorama Service returns the data, you can get its real coordinates, in this case 48.87519271414293, 2.294281201461672 which as you can see is not exactly the same than the place coordinates.
Using the Geometry Library, you can compute the heading between the panorama coordinates and your place coordinates.
let heading = google.maps.geometry.spherical.computeHeading(StreetViewCoords, PlaceCoords);
This will get you a heading.
Now before showing the panorama, set its heading:
streetView.setPov({
  heading: heading,
  pitch: 0
});

Street View is now heading to the Belgian Embassy:

Proof of concept below:

var map;
var panorama;
var panoramaService;
var streetView;
var placeCoords;

function initialize() {

  placeCoords = new google.maps.LatLng(48.87501200000001, 2.2944579999999632);

  map = new google.maps.Map(
    document.getElementById("map-canvas"), {
      zoom: 5,
      center: placeCoords,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

  panoramaService = new google.maps.StreetViewService();

  var panoramaOptions = {
    disableDefaultUI: true
  };

  panorama = new google.maps.StreetViewPanorama(document.getElementById("pano"), panoramaOptions);

  map.setStreetView(panorama);

  streetView = map.getStreetView();
  runPanoramaService();
}

function runPanoramaService() {
  panoramaService.getPanoramaByLocation(placeCoords,
    100,

    function(streetViewPanoramaData, streetViewStatus) {
      if (streetViewStatus == "OK") {

        let heading = google.maps.geometry.spherical.computeHeading(streetViewPanoramaData.location.latLng, placeCoords);

        streetView.setPosition(streetViewPanoramaData.location.latLng);

        streetView.setPov({
          heading: heading,
          pitch: 0
        });

        streetView.setVisible(true);
      }
    });
}

initialize();
#map-canvas {
  height: 80px;
}

#pano {
  height: 160px;
}


text:
Q: Как загрузить изображение в timge через проводник? image1.Picture.LoadFromFile();

Подскажите, где почитать о работе с изображениями в дельфи.
A: В любом поисковике наберите свой вопрос)
Тут например можете почитать:
http://mydelphiprogramms.jimdo.com/%D1%83%D1%80%D0%BE%D0%BA%D0%B8/%D0%B3%D1%80%D0%B0%D1%84%D0%B8%D0%BA%D0%B0-%D0%B2-delphi/
http://www.snkey.net/books/delphi/ch3-5.html


text:
Q: Why should a type not depend on types from its containing namespace? Also posted here, but with no real academic answer:
why namespace types should not depend on nested namespaces types?
If I understand it correctly, the point is that a type Product.Business.Modules.Module can depend on Product.Business.Product, but not the other way around, because Product is the foundation for Module. However, looking at my project structure, I violate this guideline:
namespace Product.Business
{
    using Modules;

    class Product
    {
        public IEnumerable<Module> Modules { get; }

        // Module is abstract, with many different kinds defined in Modules.
    }
}

However, I would like to extend the question.

*

*Where can I find supporting information to back this guideline?

*Why is this bad practice?

*Is it valid to have types depend on types from other namespaces with the same containing namespace? (e.g. Product.Business.Security depending on types in Product.Business.Modules?

In a sense violating this guideline creates a sort of circular namespace dependency, but I'd like to understand more of the why of this guideline rather than just a blanket statement. The only other information I was able to find was from the linked Msdn article. This can actually change the architecture and layout of a class library significantly.

A: To start with, I'll address your 3rd question. I have not seen any advice against that and seems to be a reasonable thing to do. You separate namespaces logically and one branch of your code might make use of another.
When it comes to nesting the namespaces however, you are creating a hierarchy. As a hypothetical example, consider a company that is testing out some data tools they are developing: Company.Data will have abstract classes and base classes that Company.Data.SqlServer will depend on. SqlServer provides specific implementation for the abstract stuff in the containing namespace. Due to feedback or the need to support another database system, the time may come when for maintainability, they decide to move the SqlServer classes out to a different library.
It is trivial to make the new assembly reference the original Company.Data and go on. The classes in Company.Data will proceed as though nothing changed. If, however, they had dependencies on the contained namespace and/or its classes, doing so breaks Company.Data. It will defeat the purpose of separating concerns. That would mean if they make a product to support MySQL, Company.Data.MySql would have a dependency on Company.Data.SqlServer.
Techniques such as the Provider Model design Pattern will no longer be possible or viable.


text:
Q: Can't see Elasticsearch daemon I'm trying to run elasticsearch as a daemon on a server.
I have run this command:
./bin/elasticsearch -d -p somefilename

but I can't find any proof of the daemon actually running, since ps -e | grep elastic does not produce any output. How can I see the process?

A: Elasticsearch runs on JVM. to see the PID of elasticsearch, you can use "jps" command.
with "ps ef" , only you can see java related process.
if you insist on using ps you can try this:
ps axms |grep -i elasticsearch

"axms" option show the details of all process.


text:
Q: Subquery/alias duplication in SqlAlchemy with polymorphic tables and "limit" Given this polymorphic model
class OrganizationBase(Base):
    __tablename__ = "x_organization_base"
    __mapper_args__ = {
        "polymorphic_identity": "base",
        "polymorphic_on": "model_type",
    }

    model_type = db.Column(db.String(), nullable=False)
    id = Column(Integer(), primary_key=True)

cont'd
class UmbrellaOrganization(OrganizationBase):
    __tablename__ = "x_umbrella_organization"
    __mapper_args__ = {"polymorphic_identity": "umbrella"}

    id = db.Column(Integer, db.ForeignKey(OrganizationBase.id), primary_key=True)
    umbrella_accounting_id = db.Column(db.String(255), nullable=False, unique=True)

    properties = db.relationship(
        "UmbrellaOrganizationProperty",
        lazy="joined",
        backref=backref("umbrella_organization", uselist=False),
    )

class Organization(OrganizationBase):
    __tablename__ = "x_organization"
    __mapper_args__ = {"polymorphic_identity": "organization"}

    id = db.Column(Integer, db.ForeignKey(OrganizationBase.id), primary_key=True)
    umbrella_accounting_id = db.Column(
        db.String(255),
        db.ForeignKey(UmbrellaOrganization.umbrella_accounting_id),
        nullable=False,
        index=True,
    )

and this eagerly loaded relationship
class UmbrellaOrganizationProperty(Base):
    __tablename__ = "x_umbrella_organization_property"

    id = Column(Integer(), primary_key=True)
    umbrella_organization_id = db.Column(
        Integer, db.ForeignKey(UmbrellaOrganization.id), nullable=False, index=True
    )
    type = db.Column(db.String(), nullable=False)

this query will produce invalid SQL:
query = (
    db.session.query(
        Organization,
        UmbrellaOrganization,
    )
    .join(
        UmbrellaOrganization,
        UmbrellaOrganization.umbrella_accounting_id == Organization.umbrella_accounting_id,
    )
)

y = query.limit(5)

Specically, there main query will be duplicated with the same alias 'anon_1' occuring twice:
ProgrammingError: (psycopg2.errors.DuplicateAlias) table name "anon_1" specified more than once

This only happens with limit() applied.
It appears that the polymorphism mapper wants to join the (eagerly loaded) UmbrellaOrganziationProperty to both the UmbrellaOrganization and OrganizationBase, even though it does not belong there. Without changing the model, the only way I have found to prevent this is telling it to not load OrganizationProperty eagerly, by adding this query option:
    .options(lazyload(UmbrellaOrganization.properties))

This is potentially problematic because client code may expect the properties in the results. What else can I do?


text:
Q: why xgboost is providing same prediction even if the values are different? start_value = 1.04
end_value = 1.05
step_size = 0.002

future = pd.DataFrame(np.arange(start_value, end_value, step_size),columns=["ROP(m/h)"])

df_and_future = pd.merge(df, future, how='outer',on='ROP(m/h)')
future_w_features['pred'] = reg.predict(future_w_features[Feature])

future_w_features['pred']

output:
0     0.711265
1     0.683333
2     0.683333
3     0.630986
4     0.630986
5     0.646690
6     0.581228
7     0.581228
8     0.581228
9     0.737150
10    0.617984
11    0.537148
12    0.712174
13    0.702487
14    0.677768
15    0.609756
16    0.564915
17    0.564915
18    0.610641
19    0.646690
20    0.532850
21    0.594250
22    0.594250
23    0.459278
24    0.615803
25    0.529335
26    0.529335
27    0.687666
28    0.642691
29    0.642691
30    0.700694
31    0.679649
32    0.585743
33    0.510179
34    0.684137
35    0.737150
36    0.737150
37    0.737150
38    0.737150
39    0.737150
40    0.737150

We expect to obtain different predicted data but failed to obtain it as it is showing same data over & over


text:
Q: How to alternate between left align and right align on each line of text? I don't have a good use case for this. I'm wondering if it's possible to set up LaTeX to switch between left align and right align for each line in a paragraph. For example, lines 1, 3, 5, 7, 9, etc. are left aligned, while lines 2, 4, 6, 8, etc. are right aligned. Obviously this could be done by hand, but I'm wondering if there is a way to set a document up so that it does it automatically without having to slap line breaks everywhere? Note, this is in the context of normal text, not equations. Again, I don't have any real use case for this, just wondering if it's possible and if so how to go about it.
Example:
  This is a line which is indented and left aligned,
       which is followed by a line which is right aligned,
which is followed by a line which is left aligned,
       which is followed by a line which is right aligned,
which is followed by a line which is left aligned,
       which is followed by a line which is right aligned,
which is followed by a line which is left aligned,
       which is followed by a line which is right aligned,
which is followed by a line which is left aligned,
                       all in one giant useless paragraph.

A: If you first set in a box you can (as long as there are no color whatsits or other non removeable items) deconstruct the list and rebuild with re-aligned line boxes

\documentclass{article}

\newif\ifpushright
\def\repack{%
\par
\global\pushrightfalse
\global\setbox1\vbox{}%
\loop
\count0=\lastnodetype
\ifnum\count0=1
\setbox0\lastbox
\global\setbox1\vbox{%
\ifpushright
\global\pushrightfalse
\hbox to \hsize{\hfill\unhbox0\unskip\unskip}%
\else
\global\pushrighttrue
\box0
\fi
\unvbox1
}%
\else\ifnum\count0=11
\skip0=\lastskip
\unskip
\global\setbox1\vbox{%
\vskip\skip0
\unvbox1
}%
\else\ifnum\count0=13
\count2=\lastpenalty
\unpenalty
\global\setbox1\vbox{%
\penalty\count2
\unvbox1
}%
\fi\fi\fi
\ifnum\count0>-1
\repeat
}
\begin{document}

{\raggedright\parindent=15pt
 This is a line which is indented and left aligned,
       which is followed by a line which is right aligned,
which issss followed by a line which is left aligned,
       which is followed by a line which is right aligned,
which is followed by a line which is left aligned,
       which is followed by a line which is right aligned,
which is followed by a line which is left aligned,
       which is followed by a line which is right aligned,
which is followed by a line which is left aligned,
                       all in one giant useless paragraph.

}

\bigskip

\setbox0\vbox{\raggedright\parindent=15pt
 This is a line which is indented and left aligned,
       which is followed by a line which is right aligned,
which issss followed by a line which is left aligned,
       which is followed by a line which is right aligned,
which is followed by a line which is left aligned,
       which is followed by a line which is right aligned,
which is followed by a line which is left aligned,
       which is followed by a line which is right aligned,
which is followed by a line which is left aligned,
                       all in one giant useless paragraph.
\repack}
\unvbox1

\end{document}

A: A typical use case I can imagine for aligning lines in this way would involve prior knowledge of where in the text the line breaks will be, for example, because they make up a poem.
If that is the case, you can define an end-of-line macro like the following:
\newcount\linecount
\everypar={\count\linecount=1 }
\def\\{\ifodd\count\linecount\hfil\break\vadjust{}\hfil
  \else\break
  \fi
  \advance\count\linecount by1 }
  This is a line which is indented and left aligned,\\
       which is followed by a line which is right aligned,\\
...


text:
Q: TYPO3 Mask_Export: Any way I can export my mask elements without deleting the content? I'm currently working on a TYPO3 Project and used the mask extension for the first time. I created a lot of elements, used them on the site and filled them with content. I just read in the manual that the mask extension itself causes some performance problems which i didn't knew about..
I installed the mask_export extension to prevent those, but now my content is gone.. I tried to just tell my TYPO3 to use the new content element but my contents ist still not displayed in it.
Is there any way I can use the mask_export extension in a running project without deleting my content?

A: If You use ext:mask_export your defined mask elements are exported in a new extension.
While the elements are exported they were renamed acording to the new extension name.
If you now deactivate mask and enable your new extension, your existing content (tt_content-records) have the wrong CType (there is no rendering definition).
Solution:
Reenable mask, deactivate your new extension and build a test-page with all content elements, then disable mask and enable your extension and build all content elments again (additionally). Now you can do a SQL-query (SELECT CType FROM tt_content WHERE pid=123) to identify the used CTypes and do database wide replacements.
Be aware, that the extension name may be used in other places (e.g. prefix for tables or fields). This needs to be fixed too.
Conclusion:
It's a bad idea to replace mask after content is inserted, as it generates a lot of manual work in the database.


text:
Q: Update table with values from another table I have 2 tables, one With a unique key the other With no unique key. In both tables there are one column "name" which are identical.  I want to update table two With the unique key from table one where table.one.name = table.two.name.  There are multi rows in table two, only one in table one.
Is this possible?

A: In Oracle database is it possible with sql command:
update table2 a set a.col = :nValue
where a.name = (select b.name from table1 b where b.name = a.name and b.key = :nUniqueKey)

In others databases it will be the similar.


text:
Q: ASP.NET MVC - Open Table in new window and print I'm using ASP.NET MVC and have a table with 9 columns which shows results from the database where the user can filter values based on columns. The table structure looks like this:

                @Html.DisplayNameFor(model => model.ID)

                @Html.DisplayNameFor(model => model.YEAR)

        @foreach (var item in Model)
        {

                    @Html.DisplayFor(modelItem => item.ID)

                    @Html.DisplayFor(modelItem => item.YEAR)

                    <input type="checkbox" class="chkCheckBoxId" name="airlineId" value="@item.ID" />

                    @Html.ActionLink("EditValue", "Edit", new { id = item.ID })

        }

Now I need a button, so that the dynamically generated table opens in a new window and the print dialog opens automatically. I had this piece of code:

    <input type="submit" value="print" onclick="printTable()" class="btn fl btn-print">

The problem here is that the table is completely unsorted when printed so the rows/columns are shifted.
I found this example:
https://datatables.net/extensions/buttons/examples/print/simple.html
This is exactly what I need (open the table in a new window and open print dialog). But unfortunately this sample has a lot of code in the javascript files that I don't need. There is a search field included and a pagination.
Can someone help me please? Thank you very much!

A: Ok I found a good solution.
This is the code I used:

and right before the table-tag the link to click:

    [print table]

There opens no new window but the table is well formated for printing.


text:
Q: Are these songs from "My Little Pony: Friendship is Magic"?

Are these songs from "My Little Pony: Friendship is Magic"?

A: Unlikely
These both seem to be fan productions, with songs taken from other sources.
The first song is "Come Little Children," from the film Hocus Pocus (1993). This is shown in the credits:

The singer is not any one of the actors who voiced Princess Luna, as seen here.
The second song appears to be something called "Daylight's End" from League of Legends.

The songs were presumably chosen because they made good theme music for the fan animations centered around Princess Luna.


text:
Q: Background selector declaration in CSS In CSS declaration for a selector is given as:
background-attachment: scroll;
background-color: transparent;
background-image: url(/images/ucc/green/btn-part2.gif);
background-repeat: no-repeat;
background-position: right top;

I want to optimize the code and change it to:
background: scroll transparent url(/images/ucc/green/btn-part2.gif) no-repeat right top;

My question is, Is this correct way and does it work in IE7/8, Firefox, Safari?

A: Yes, this is the correct way and it works in all major browsers. You can read more about the CSS background property which can be used to set all background-* properties together.
Update: Yes, the following rule will work:
background
{
    background: transparent url(/images/ucc/green/btn-part2.gif) no-repeat scroll 20px 40px;
}

Except the browser will attempt to apply this rule to an <background> element in the DOM. And since there's no such element in HTML, the rule will never be applied to anything. :-) So you have to change the rule selector to select the container element you want to apply the background property to:
div#myDivIWantToSetBackgroundTo
{
    background: transparent url(/images/ucc/green/btn-part2.gif) no-repeat scroll 20px 40px;
}

Btw, you can play with various values for the background property on the W3School site.

A: Yes it works. Take a look at point 6 here - http://www.domedia.org/oveklykken/css-shorthands.php

A: http://www.w3schools.com/css/css_background.asp

When using the shorthand property the
  order of the property values are:
* background-color
* background-image
* background-repeat
* background-attachment
* background-position

background
{
    background: transparent url(/images/ucc/green/btn-part2.gif) no-repeat scroll right top;
}


text:
Q: The log file contains the log statements with message stamp as shown below The log file contains the log statements with message stamp as shown below.
The utility lists out all the actions that took more than the specified time. The time is specified in seconds from the command line.
Input:
#<process id> <date time> <log level> <file name> <line number> <actual message>

1098 2007-02-28 15:23:09 WARN db_util.c 5928 Config file not found, using default values
1098 2007-02-28 15:23:09 INFO db_util.c 5908 Connecting to database
1098 2007-02-28 15:23:17 INFO db_util.c 5908 Connected to database
1098 2007-02-28 15:23:17 ERROR log_test.c 198 Unable to setup our satellite launch system
1098 2007-02-28 15:23:18 INFO log_test.c 198 Reconnecting to launch the satellite
1098 2007-02-28 15:23:21 INFO log_test.c 198 Reconnected. Initialize to launch the satellite

Eg: If the utility is executed by giving the input file as input and 2 seconds the performance threshold time, it should produce this output:
1098 2007-02-28 15:23:09 INFO db_util.c 5908 Connecting to database
1098 2007-02-28 15:23:18 INFO log_test.c 198 Reconnecting to launch the satellite.

I have found this code working for the above mentioned problem statement:
awk -v threshold=$1 '{texttime=mktime(gensub(/-|:/," ", "g", $2" "$3))} NR>1 && texttime-prevtexttime>threshold{print prevrecord} {prevtexttime=texttime; prevrecord=$0}' $2

Is there any more elegant way of converting the current record's date and time to a unix timestamp? Other than this (mktime(gensub(/-|:/," ", "g", $2" "$3)))

A: With awk? Not really (just change /-|:/ to /[-:]/). I believe perl has strptime() which would save you one function call for the equivalent code but IMHO it's not worth changing tools/languages just for that.


text:
Q: Dynamically updating slow log in ES 2.4.1? I want to enable slow log for my Elasticsearch 2.4.1.But when i tried it dynamically, it is showing error for me ?
PUT _cluster/settings
     {
      "transient": {
        "index.search.slowlog.threshold.query.debug": "0s",
        "index.search.slowlog.threshold.fetch.debug": "0s",
        "index.indexing.slowlog.threshold.index.debug": "0s"
      }
    }

The response in logs
[2017-02-22 12:44:33,650][WARN ][action.admin.cluster.settings] [Powderkeg] igno
ring transient setting [index.indexing.slowlog.threshold.index.trace], not dynam
ically updateable
[2017-02-22 12:44:33,651][WARN ][action.admin.cluster.settings] [Powderkeg] igno
ring transient setting [index.search.slowlog.threshold.fetch.trace], not dynamic
ally updateable
[2017-02-22 12:44:33,651][WARN ][action.admin.cluster.settings] [Powderkeg] igno
ring transient setting [index.search.slowlog.threshold.query.trace], not dynamic
ally updateable
[2017-02-22 13:58:30,051][WARN ][action.admin.cluster.settings] [Powderkeg] igno
ring transient setting [index.indexing.slowlog.threshold.index.debug], not dynam
ically updateable
[2017-02-22 13:58:30,051][WARN ][action.admin.cluster.settings] [Powderkeg] igno
ring transient setting [index.search.slowlog.threshold.fetch.debug], not dynamic
ally updateable
[2017-02-22 13:58:30,052][WARN ][action.admin.cluster.settings] [Powderkeg] igno
ring transient setting [index.search.slowlog.threshold.query.debug], not dynamic
ally updateable

A: This settings should be given at index level not cluster level.
PUT indexname/_settings
     {

        "index.search.slowlog.threshold.query.debug": "0s",
        "index.search.slowlog.threshold.fetch.debug": "0s",
        "index.indexing.slowlog.threshold.index.debug": "0s"

    }