text:
Q: Select tag and materialize datapicker disappearing when submitting form in React Trying to submit a form that has many input fields and 3 select tags(SetUp Component). Whenever I hit submit the select tags disappear and materialize datapicker doesn't show.
here's the Form component's code:
import React, { Component } from 'react';
import Network from './Form/Network';
import GenInfo from './Form/GenInfo';
import Address from './Form/Address';
import Setup from './Form/Setup';
import { connect } from 'react-redux';
import { currentHotel } from '../../../redux/actions/hotelAction';
import { Card } from 'react-materialize';

class Form extends Component {

  state = {
    razaoSocial: '',
    nomeFantasia: '',
    cnpj: '',
    noQuartos: '',
    noRecepcao: '',
    cep: '',
    pais: '',
    estado: '',
    cidade: '',
    rua: '',
    numero: '',
    bairro: '',
    complemento: '',
    pms: '1',
    channel: '1',
    motorReservas: '1',
    idHotel: '',
    statusHotel: '',
    date: ''
  }

  handleSetInfo = (e) => {
    console.log(e.target.value);
    this.setState({
        [e.target.id]: e.target.value
    });
  }

  handleSubmit = (e) =>{
    e.preventDefault();
    const { currentHotel } = this.props;
    currentHotel(this.state.razaoSocial);
  }

  render() {
    const { razaoSocial, nomeFantasia, cnpj, noQuartos, noRecepcao, cep, pais, estado, cidade, rua, numero, bairro,
      complemento, pms, channel, motorReservas, idHotel, statusHotel, date } = this.state;
    return (

      <Card className="formHotel hoverable">
        <form onSubmit={this.handleSubmit}>
          <Network></Network>
          <GenInfo handleSetInfo={this.handleSetInfo}
            razaoSocial={razaoSocial}
            nomeFantasia={nomeFantasia}
            cnpj={cnpj}
            noQuartos={noQuartos}
            noRecepcao={noRecepcao}
          ></GenInfo>
          <Address handleSetInfo={this.handleSetInfo}
            cep={cep}
            pais={pais}
            estado={estado}
            cidade={cidade}
            rua={rua}
            numero={numero}
            bairro={bairro}
            complemento={complemento}></Address>
          <Setup handleSetInfo={this.handleSetInfo}
            pms={pms}
            channel={channel}
            motorReservas={motorReservas}></Setup>

              <button type="submit" value="submit" href="#" className="waves-effect waves-light btn-small btn">Concluir</button>

        </form>
      </Card>
    );
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    currentHotel: (hotel) => dispatch(currentHotel(hotel))
  }
}

const mapStateToProps = ({ hotels }) => {
  return {
    hotels
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Form);

As you can see I added the values to the select tags on Form's state and pass them and the function handleSetInfo to handle select tags. Unfortunately it is not working
And this is the SetUp Component component
import React, { Component } from 'react';

class Setup extends Component {
  render() {

    const { handleSetInfo, pms, channel, motorReservas} = this.props;

    return (

SETUP

              <select id="pms" value={pms} onChange={(e) => handleSetInfo(e)}>
                <option value="" disabled>Escolha</option>
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
              </select>
              PMS

              <select id="channel" value={channel} onChange={(e) => handleSetInfo(e)}>
                <option value="" disabled>Escolha</option>
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
              </select>
              Channel

              <select id="motorReservas" value={motorReservas} onChange={(e) => handleSetInfo(e)}>
                <option value="" disabled>Escolha</option>
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
              </select>
              Motor de Reservas

    );
  }
}

export default Setup;

Does anyone understand why this is happening?


text:
Q: json string into array?
Possible Duplicate:
Taking .get json string, turn into array?

Im using the following to retrieve a string from php, i would like to know how to make my string into an array.
Jquery
$.get("get.php", function(data){
    alert(data);
    //alert($.parseJSON(data));
}, "json");

the commented out section seems to have no effect, so I cant really tell what I am doing wrong, could someone please advice?
PHP
<?php

$username="root";
$password="root";
$database="testing";

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

$name= $_GET['name'];

$query="SELECT * FROM tableone ";
$result=mysql_query($query);

$num=mysql_numrows($result);

mysql_close();

$array = array();

$i=0;
while ($i < $num) {

    $first=mysql_result($result,$i,"firstname");
    $last=mysql_result($result,$i,"lastname");
    $date=mysql_result($result,$i,"date");
    $ID=mysql_result($result,$i,"id");

    $array[$i] = $first;

    $i++;
}

echo json_encode($array);

?>

Output:
["James","Lydia","John"]

A: $.getJSON("get.php", function(data) {
    // data is already an array => you can loop to get individual elements
    // for example
    $.each(data, function(index, element) {
        alert(element);
    });
});

Also make sure that in your PHP file you have set the proper Content-Type response header top application/json.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Howto create a branch from tag in CVS with intelliJ I checked a specific tag representing some release from CVS using intelliJ Idea 9.0. Now I made few fixes to the code and want to create a branch for the same release starting from this tag. So what I want to do is exactly this: Start branch (before I commit my changes it will be the same as the tag) and keep the tag as it is for reference.
I wonder if command CVS -> Create branch on the project root in IntelliJ will do the trick. I went through the official IntelliJ doc but it's still unclear to me if the branch will be created from the currently checked out tag.

A: Yes, Create branch should work as you expect.


text:
Q: XML attribute order I have this code for writing my XML
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.IndentChars = ("\t");

        XmlWriter writer = XmlWriter.Create("sample.xml",settings);
        writer.WriteStartDocument();
        writer.WriteStartElement("Report", "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition");
        writer.WriteAttributeString("xmlns","rd", null, "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
        writer.WriteEndElement();
        writer.WriteEndDocument();

        writer.Close();

The code above yields this output in my sample.xml:
<?xml version="1.0" encoding="utf-8"?>
<Report xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition" />

However, what I would like as an output would be this:
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">

I tried re-order my codes but that didn't seem to work.


text:
Q: Mathf.Clamp Function distorts the object size I'm making the SpaceShooter game in Unity.
Here is the function.
 void FixedUpdate ()
{

    float moveHorizontal = Input.GetAxis ("Horizontal");
    float moveVertical = Input.GetAxis ("Vertical");

    Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
    Player.GetComponent<Rigidbody>().velocity=movement*speed;

    Player.GetComponent<Rigidbody> ().rotation = Quaternion.Euler(0.0f,0.0f,Player.GetComponent<Rigidbody> ().velocity.x * -tilt);
}

In the above code when I add the Clamp function to limit the Ship to the boundaries, the Ship size reduces from the sides.
This is the Clamp function code that reduces the size of the ship.
 Player.GetComponent<Rigidbody> ().position=new Vector3
    (
        Mathf.Clamp(Player.GetComponent<Rigidbody>().position.x, boundary.xMin, boundary.xMax),
        0.0f,
        Mathf.Clamp(Player.GetComponent<Rigidbody>().position.z, boundary.zMin, boundary.zMax)
    );

Ship size Before:

Ship size After:

I've given the screen boundary values accurately in the Clamping funtion.

A: Modifying the position of the Rigidbody indeed moves the Transform, but after the last physic step. While it is considered faster, it may cause some undesired behaviour, as you are moving something the physic of the engine is also using, and doing it in the FixedUpdate function which should mostly be used for Physics matter. Replace Player.GetComponent<Rigidbody>().position with Player.GetComponent<Transform>().position. Also, as you are not using any physic here but you are instead modifying an object position directly, set this part of the code in the Update function instead.
void Update()
{
    Transform playerTransform = Player.GetComponent<Transform>();

    playerTransform.position=new Vector3
    (
        Mathf.Clamp(playerTransform.position.x, boundary.xMin, boundary.xMax),
        0.0f,
        Mathf.Clamp(playerTransform.position.z, boundary.zMin, boundary.zMax)
    );
}

If you ever want to move an object using its Rigidbody, never do it this way by the way. Consider using the MovePosition function instead. Moving it the way you did cause it to teleport and not compute collisions on the same frame, but on the next one.
As a side note, you should save a reference to the player's transform in your class, so you don't have to use the GetComponent function everytime.

A: Solved the problem by pushing the background "quad" beneath (about -4) the plane and set the ship's Y value to 0


text:
Q: Why is execvp() executing twice using fork()? I am implementing a shell.
When attempting a command other than changing directories, execvp() runs, the child terminates and a new child is created. When I change directories, the child does not terminate and a new child is created. Here is a sample of my code:
for(;;) {
    printf("bash: ");
    parse();
    ...
    pid_t pid = fork()
    if (pid == 0)
        if (!strcmp(line[0], "cd"))
            if (!line[1]) (void) chdir(getenv("HOME"));
            else (void) chdir(line[1]);
        else execvp(line[0], line);
    ...
    if (pid > 0) {
        while (pid == wait(NULL));
        printf("%d terminated.\n", pid);
    }
}

cd ../; ls; runs correctly, except I have to Ctrl+D twice to end the program.
Though, if I pipe the same information (ie. mybash < chdirtest), it runs correctly once, terminates the child, runs again except in the original directly, then terminates the final child.

A: cd should not be invoked through a child process, the shell itself should change its current directory (that's the property of an internal command: modify the process of the shell itself).
A (primitve) shell should looks like:
for(;;) {
    printf("bash: ");
    parse();

    // realize internal commands (here "cd")
    if (!strcmp(line[0], "cd")) {
       if (!line[1]) (void) chdir(getenv("HOME"));
       else (void) chdir(line[1]);
       continue; // jump back to read another command
    }

    // realize external commands
    pid_t pid = fork()
    if (pid == 0) {
        execvp(line[0], line);
        exit(EXIT_FAILURE); // wrong exec
    }

    // synchro on child
    if (pid > 0) {
        while (pid == wait(NULL));
        printf("%d terminated.\n", pid);
    }
}


text:
Q: How to make cross site HTTP GET JSON request I am using AngularJS to make a cross site json call as following:
$http.get('http://ipinfo.io/json').success(function(response){

The above request works fine for Chrome and Mozilla Forefox, but it doesn't work on IE 9. IE 9 is the only version I've tested it on. I am assuming it wouldn't work on other IE versions either.
Could somebody tell me the mistake I am committing here for its not working in IE 9?

A:
This is how I do it and this does not through any errors for me. Hope this can fix your problem.
//controller
(function() {
    var ipInfo = function($scope,IPService){
        IPService.ipServiceProvider()
         .success(function(data){
          console.log(data);
       })
         .error(function(status,error){
           console.log(status);
           console.log(data);
       })
    };
    ipInfo.$inject = ['$scope',IPService];
    angular.module('app').controller('ipInfo',ipInfo);
}());

//services
 (function() {
    var IPService= function($http) {
        var urlBase = "http://ipinfo.io/json";
        var factory = {};
        factory.ipServiceProvider= function() {
            return $http.get(urlBase);
        };
        return factory;
    };
    IPService.$inject = ['$http'];
    angular.module('app').factory('IPService',IPService);
}());

Please let me know if you have any problems
Update :
If you see this screen click on Yes. This usually pops up in IE8 and IE9.


text:
Q: WPF - Binding to an ItemsSource AND SelectedIndex throws exception? This code gives me an "Argument out of range" exception. When I remove the binding to the SelectedIndex, the ComboBox is populated just fine and no exception is thrown.
Any idea what I am doing wrong? Is this (for some reason) not possible?
Code:
public class RuleMap<T> : INotifyPropertyChanged
{
    public ObservableCollection<string> Options
    {
        get
        {
            return new ObservableCollection(){"A", "B", "C"};
        }
    }

    public int SelectedIndex
    {
        get
        {
            return 0;
        }
    }
}

public ObservableCollection<RuleMap> FilterItemSource;

XAML:
<ItemsControl ItemsSource="{Binding FilterItemSource}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">                                 <ComboBox Width="150" SelectedIndex="{Binding SelectedIndex}"
                          ItemsSource="{Binding Options}"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

A: I guess that SelectedIndex it is a ReadOnly Property.
Other problem can be that 0 it's not in the collection

A: I think that Items are not added before selectedIndex is Binded, and since there are no item, it is showing Argument out of Range exception.

A: Turns out the ComboBox control was fundamentally broken to begin with. Thanks to this Blog Post by Rockford Lhotka, we were able to override the ComboBox control with one that could correctly bind to SelectedItem property.
Ick.

A: I would avoid returning a new collection from your Options property. You're making an assumption that WPF only accesses the property once.
But you also have the option of using a CollectionView where you're currently returning an ObservableCollection. If you're using a MVVM architecture, your ViewModel can expose the property as CollectionView and it has the notion of a "current" item.


text:
Q: How to disable Expect:100-Continue when using WCF in Windows Store App I need to get rid of the Expect: 100-Continue header in HTTP message, when communicating with WebService using WCF in Windows Store App.
I have found a lot of solutions, but none of them is possible in Windows 8:

*

*ServicePoint.Expect100Continue = false; doesn't exist in Store App any more (No SericePoint or ServicePointManager class),

*I cannot change configuration in web.config file, because it doesn't exist in Store App,

*It is possible to change the flag in HttpClient, but I cannot access it, when using WCF,

*I tried to manipulate with message headers using IClientMessageInspector, but the default HTTP headers are being added later, in higher layers, so my changes will be ovverriden.

Does anyone have any other ideas?

A: There are 2 ways to deal with this.
You can turn set expect100Continue="false" in you app.config or web.config, but this will be global. This could be an issue if some external services prefer to use the header expect100Continue. Here's how:
<system.net>
     <settings>
        <servicePointManager expect100Continue="false"/>
     </settings>
</system.net>

Or you can do it in code for a specific endpoint as follows:
System.Net.ServicePoint servicePoint =
     System.Net.ServicePointManager.FindServicePoint(myWcfService.Endpoint.Address.Uri);
servicePoint.Expect100Continue = false;
// now execute some service operation


text:
Q: Angular RouterLinkActive with redirected routes I have found an interesting behavior in the way routerLinkActive when using routes with route params. The behavior only occurs when using a redirect route.
Consider an application with these two routes:
  { path: 'page2/:id', component: Page2Component },
  { path: 'page2', redirectTo: '/page2/', pathMatch: 'full' },

And, in the same app, a page with these links with routerLinkActive:
      Page 2

      Page 2 / Foo

I would expect the first link (/page2) to be have the active class only when the url is /active and not when the url is /active/foo. However, when I have the redirect route shown above, the first link never gets the active class applied to it.
It does work as expected if, instead of the redirect route, I just have a second route as follows:
  { path: 'page2/:id', component: Page2Component },
  { path: 'page2', component: Page2Component },

However, it's a better practice to use the redirect route, because then the component does not get re-loaded when navigating to itself from itself (i.e. navigating from /page2/foo to /page2/bar). So I'd prefer the redirect route, but I can't see how to get the [routerLinkActiveOptions]="{exact: true}" working when using a redirect route.
Here are examples in stackblitz:
Broken example with redirect route: https://stackblitz.com/edit/angular-ivy-ii1882?file=src/app/app.module.ts
Working example with non-redirect route: https://stackblitz.com/edit/angular-ivy-rh1tj1?file=src/app/app.module.ts
Is there a solution that would allow me to have both a redirect route and a working routerLinkActiveOptions?

A: EDIT: The real answer to this problem is to use query strings instead of route parameters for optional parameters. See below for more info.
Originally my answer was that the correct way to do this is to pass an empty parameter as part of the routerLink like this:
[routerLink]="['page2', '']"

EDIT: But actually, this approach has another side effect. routerLinks that are set to simply [routerLink]="['page2', '']" act as if {exact: true} is set to true on routerLinkActiveOptions even without adding routerLinkActiveOptions. This is because it is looking specifically for a route with an empty string as a parameter. The real solution here is to use querystring parameters instead of route parameters if the parameter is not required.
Side note: It does seem like routerLink="page2" could feasibly work the same way and my initial bug report has been changed to a feature request: Github Issue


text:
Q: Vertically Responsive Design: Scaling an image proportionally in div I found this very useful site Vertically Responsive Design : Keeping Things Above The Fold where its shown how to create div that scales text within it when adjusting the browser window height (not width).
What i'm searching for is to do the exact same thing but with an image. In other words an image that scales in and out when adjusting the browser window height while keeping it's proportions.
Anyone have any suggestions?
Thanks!
UPDATED: Fiddle here: https://jsfiddle.net/1pu67mLg/
This is the HTML for the text (from nitinh.com):

lorem ipsum dolor sit amet

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis euismod felis. Phasellus id pretium dui proin finibus.

                    Lorem ipsum dolor sit amet article.

And the CSS (from nitinh.com):
.container{
    min-width:600px;
    max-width:1080px;
    min-height:100%;
    width:150vh;
    margin:0 auto;
    font-family:'Lato',sans-serif
}

.hero-unit{
    min-width:600px;
    max-width:1080px;
    min-height:calc(690px * (90/150));
    height:90vh;
    width:150vh;
    background-color:#2fa1b2;
    position:relative;
    box-sizing:border-box;
    padding:10px 30px
}

.hero-unit h1{
    font-weight:400px;
    font-size:7vh
}

.hero-unit .text{
    font-weight:100;
    font-size:4vh;
    color:#fff
}

A: If I understand your question correctly, you want to add an image that scales based on the height of the view-port. If so you just want to scale the image similarly to your text just add a normal img tag and use vh units like so:
HTML

CSS
.hero-unit img{
  height: 40vh;
  width: auto;
}

jsfiddle


text:
Q: How to work with Delaunay triangulation in Python like MatLab? I wanted to use Delaunay triangulation in Python, but I don't know if there is any way to do that. I searched the web, but it seems it is different. Thank you for your help.
These are the MATLAB code and input and output parameters (I just pasted some of the first lines):

% nodes = [3458 , 2]
% nodes :

#segs = [10178, 3]
%segs:

MatLab Output >
%Points: [3458×2 double]
%ConnectivityList: [6905×3 double]
%Constraints: [10178×2 double]
%Points:
-1.0000    1.0000
1.0000    1.0000
1.0000   -1.0000
-1.0000   -1.0000
-1.0000   -0.0032

%ConnectivityList:
1920 1923 1924
593 597 610
435 494 336
1086 1089 767
1587 3113 3114

%Constraints:
248 390
248 769
390 769
158 221
221 840
158 840
45 173


text:
Q: Filtering Filtered DataView I have a DataSet which will be filtered twice like the following.
How can I set the RowFilter property of the DataView twice?
Or is there any other better implementation than the one below?
DataView dv = new DataView(myDataSet.Tables[0]);
dv.RowFilter = "approved = 1";
dv.Sort = "BookingDate";
foreach row{
    //Filter by shiftTime in filtered DataView
    foreach column{
        //Find date in filtered DataView
    }
}

Thank you in advance for your help.
Thanks,
artsylar

A: I don't know if you've already found the solution. I assume you have but I will still post a possible solution if it helps someone. It's in VB.NET though.
Dim dv_docs As New DataView(ds_allDocsInfo.Tables(0))
Dim rowFilter As String = ""
rowFilter = "DocumentStatus='Published' And templateFrameID='2'
dv_docs.RowFilter = rowFilter
DLDocument.DataSource = dv_docs
DLDocument.DataBind()

Note: To have multiple filters I have used 'And' and built a row filter separately before applying it to the DataView.
Hope this helps.


text:
Q: CTS execution using junit categories CTS execution:
How can we trigger the test suite of Junit by using annotations and categories through command line?

A: You can run CTS individual test methods or the whole class using android instrumentation command.
For Example: Here in this example CTS test class with a specific method is mentioned to run, you can remove the test method from the below command to run all test methods within the class.
adb shell am instrument -w -e class android.animation.AnimatorSetEventsTest#testCancel
    \com.android.frameworks.coretests android.support.test.runner.AndroidJUnitRunner
For more details on running tests via instrumentation follow this link -
https://source.android.com/compatibility/tests/development/instrumentation


text:
Q: Yum autoremove removing packages that are standalone If I run sudo yum autoremove it outputs what it is going to remove for confirmation. However, some of these packages it is removing are things I want but are not dependencies of anything else...
What causes this and can it be prevented?

A: If you don't want packages to be deleted, as they were installed as dependency before, you must mark them as installed:
yum install #package

Now it will say somethink like "already installed, marked as manually installed".


text:
Q: datepicker not work in live method my datepicker is work in simple code. after using that in insert new row of
 not work in click. but i can get object of that in first click into <input/>.
thats work when clicking other input and try again to click for showing popup of datepicker.
My jQuery:
$('#myTable tr:last').after("
"+rowCount+
            "	<input style='width:300px !important;' name='onvan' />	"+
            "<input style='width:100px !important;' name='' id='startdate'/>	"+
            "<input style='width:100px !important;' name='' id='enddate'/>	"+
            "<input style='width:100px !important;' name='' id='' />	"+
            ""+
            "<select name='visible'>"+
            "<option></option>"+
            "<option></option>"+
            "<option></option>"+
            "<option></option>"+
            "<option></option>"+
            "<option></option>"+
            "</select>	"+
            "<select name='visible'><option value='1' >فعال</option><option value='0' >غیرفعال</option></select>"+
            "  ذخیره لفو	"+
            "
");

DATAPICKER:
$(function() {
    $('#startdate').live('click', function() {
        // alert( $(this));

             $(this).datepicker({
                changeMonth: true,
                changeYear: true,
                showButtonPanel: true,
                dateFormat: 'yy/mm/dd',
                minDate: '-3y',
                maxDate: '+3y',
                regional: 'fa',
                onSelect: function (dateText, inst) {
                         var date = new JalaliDate(inst['selectedYear'], inst['selectedMonth'], inst['selectedDay']).getGregorianDate();
                          var month= (date.getMonth()+1).toString();
                          if (month.length <2) month='0'+ month;

                          var day= date.getDate().toString();
                          if (day.length <2) day ='0'+ day;
                          $('#taTarikh').val(date.getFullYear() + '-' + month + '-' + day);
                          // alert($('#taTarikh').val());
                }
             });
          });
});

A: With .live('click',function(){}); you are implementing datepicker by your first click thats why it starts working at second click.
You should implement datepicker after you create the object..
$(function() {
    $('#myTable tr:last').after("
3	<input style='width:300px !important;' name='onvan' />	" + "<input style='width:100px !important;' name='' id='startdate'/>	" + "<input style='width:100px !important;' name='' id='enddate'/>	" + "<input style='width:100px !important;' name='' id='' />	" + "" + "<select name='visible'>" + "<option></option>" + "<option></option>" + "<option></option>" + "<option></option>" + "<option></option>" + "<option></option>" + "</select>	" + "<select name='visible'><option value='1' >فعال</option><option value='0' >غیرفعال</option></select>" + "  ذخیره لفو	" + "
");
    $("#startdate").datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'yy/mm/dd',
        minDate: '-3y',
        maxDate: '+3y',
        regional: 'fa',
        onSelect: function(dateText, inst) {
            var date = new JalaliDate(inst['selectedYear'], inst['selectedMonth'], inst['selectedDay']).getGregorianDate();
            var month = (date.getMonth() + 1).toString();
            if (month.length < 2) month = '0' + month;
            var day = date.getDate().toString();
            if (day.length < 2) day = '0' + day;
            $('#taTarikh').val(date.getFullYear() + '-' + month + '-' + day);
            // alert($('#taTarikh').val());
        }
    });
});

Demo: http://jsfiddle.net/BerkerYuceer/pBQFF/14/


text:
Q: Can we access redux in stateless component in React.js I want to access redux in the stateless components. How to do that. Please explain with an example!

A: Detailed docs for using react-redux hooks. https://react-redux.js.org/api/hooks
Here is sample code using the useSelector and useDispatch hooks.
import React from "react";
import { useSelector, useDispatch } from "react-redux";

export const Component = () => {
  const value = useSelector(state => state.value);
  const dispatch = useDispatch();

  return (
    <div
      onClick={() => dispatch({ type: "GET_VALUE", payload: {} })}
    >{`Value is ${value}`}</div>
  );
};

A: Yes. It doesn't matter if a component is stateless or not. Redux can be used in the same way on both, using the connect method provided by react-redux, which will pass the selected portion of the Redux managed state into your component as props:
import { connect } from 'react-redux'

const mapStateToProps = state => {asProp: state.someField}

function StatelessComponent({asProp}) {
  return <></>
}

export default connect(mapStateToProps)(StatelessComponent)


text:
Q: Why postfix doesn't follow From header from PHP mail(); I have installed postfix with no config option.
I am trying to send email with php mail(); it works but it sends email with the default email of my dedicated server.
Are there anyway to tell postfix to follow the header set by mail function?
Thanks
Code
$from='no-reply@mywebsite.com';
$fromname='my Website';
mail($mailto,$subject,$text,'From: ' . $fromname . ' <'.$from.'>');

A: Try using the -f and -r additional parameters to override the from header and return path respectively.
mail(
    $mailto,
    $subject,
    $text,
    "From: " . $fromname . " <".$from.">",
    "-f $from -r mybounceemail@example.com");

From the postfix sendmail man page:
   -f sender
     Set the envelope sender address. This is the address where delivery problems are sent to.  With  Postfix  versions  before  2.1,  the
     Errors-To: message header overrides the error return address.

   -r sender
     Set the envelope sender address. This is the address where delivery problems are sent to.  With  Postfix  versions  before  2.1,  the
     Errors-To: message header overrides the error return address.

A: If you have a million mail() and do not want to recode all your mail() functions... you can set in your php.ini the following... and it will universally set all you php mail() functions to use it.
sendmail_path = sendmail -t -f do_not_reply@your.com


text:
Q: WPF Пользовательский шаблон управления

Пробую работать с пользовательским шаблонам. Объяснить как сделать "атрибут" у моего элемента, который будет присваивать/возвращать, например Имя.
На картинках видно, что в LeftMenuItem у меня есть Labal, и я хочу задать для него текст в компонент LeftMenu где этот элемент используется. Как мне это сделать?

A: Это делается так:

*

*Заводим себе UserControl стандартным способом:
<UserControl x:Class="YourNamespace.LeftMenuItem"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <TextBlock Text="Lorem ipsum"/>
    </Grid>
</UserControl>

public partial class LeftMenuItem : UserControl
{
    public LeftMenuItem()
    {
        InitializeComponent();
    }
}

*Добавляем в UserControl нужное DependencyProperty стандартным образом:
public string Header
{
    get { return (string)GetValue(HeaderProperty); }
    set { SetValue(HeaderProperty, value); }
}

public static readonly DependencyProperty HeaderProperty =
    DependencyProperty.Register("Header", typeof(string), typeof(LeftMenuItem));

*Пользуемся им в XAML'е:
<TextBlock Text="{Binding Header, RelativeSource={RelativeSource FindAncestor,
                          AncestorType=UserControl}}"/>

*Пользуемся им в коде, который включает этот UserControl:
<local:LeftMenuItem Header="{Binding HeaderText}" .../>

Всё!

A: Прочитали бы документацию МС по этому вопросу - https://msdn.microsoft.com/ru-ru/library/ms751709(v=vs.110).aspx
Либо, если хотите комплексно изучать, то посмотрите видеоуроки - http://itvdn.com/ru/video/wpf


text:
Q: How to produce given number of quad in math We know that \qquad equals \quad\quad, then is there a way to define a command like \myquad{5} to produce five \quad?
I think there are two way:

*

*get the length of \quad, then
\newcommand{\myquad}[1]{\hspace{#1*lengthofquad}}

*define a function and load it recursively, but I don't know how to do this.

A: Here is version using a loop:
\documentclass{article}
\usepackage{pgffor}
\newcommand\Quad[1][1]{\foreach \Quaddy in {1,...,#1}{\quad}\ignorespaces}

\begin{document}

  x \quad x \par
  x \Quad[1] x

  x \quad\quad\qquad x \par
  x \Quad[4] x

  x \qquad\qquad\qquad\qquad\qquad x \par
  x \Quad[10] x

\end{document}

with output:

Personally, I prefer the more direct approach in Werner's answer.

A: You can look up how \quad and \qquad are defined, either in the LaTeX source or by asking LaTeX itself:

This is pdfTeX, Version 3.14159265-2.6-1.40.16 (TeX Live 2015/Debian) (preloaded format=latex)
 restricted \write18 enabled.
**\show\quad
entering extended mode
LaTeX2e <2016/02/01>
Babel <3.9q> and hyphenation patterns for 81 language(s) loaded.
> \quad=macro:
->\hskip 1em\relax .
 \show\quad

?

*\show\qquad
> \qquad=macro:
->\hskip 2em\relax .
 \show\qquad

?

*
! Emergency stop.
 \show\qquad

No pages of output.
Transcript written on texput.log.

In many cases this will place you in a maze of twisty commands, all subtly different, but here it's pretty straightforward. A quad is a horizontal space of 1em (the nominal width of a capital M in the current font).
\newcommand{\myquad}[1]{\hskip #1 em\relax}

or in a more LaTeXish way
\newcommand{\myquad}[1]{\hspace{#1 em}}

A: \quad sets a length of 1em, with multiples X of it being of length Xem. So we can define \myquad[<num>] with <num> being optional (default of 1), to produce a space of <num>em:

\documentclass{article}

\newcommand{\myquad}[1][1]{\hspace*{#1em}\ignorespaces}

\begin{document}

x \quad x \par
x \myquad[1] x

x \quad\quad\qquad x \par
x \myquad[4] x

x \qquad\qquad\qquad\qquad\qquad x \par
x \myquad[10] x

\end{document}

We use \hspace* to insert a space regardless of whether you're at the start, middle or end of a rule.


text:
Q: Construct grammar $\ a^i b^j c^{i+j} b^j a^i $ I've been going through old exams at my college and I found this problem that I haven't yet been able to solve.
Construct grammar defined on the alphabet $\ \{{a, b, c}\} $ which generates strings of the form $\ a^i\ b^j\ c^{i+j}\ b^j\ a^i\  where\ i, j \geq 0. $ It doesn't say anything which form the grammar should be; that is it can be context-free, restricted, unrestricted... anything goes.

A: $$\begin{align*}
&S\to TY\\
&T\to aTA\mid U\\
&U\to bUB\mid ZV\\
&VB\to Wb\\
&bW\to Wb\\
&ZW\to cZV\\
&Vb\to bV\\
&VA\to Xa\\
&aX\to Xa\\
&bX\to Xb\\
&ZX\to cZV\\
&VY\to C\\
&aC\to Ca\\
&bC\to Cb\\
&ZC\to\lambda
\end{align*}$$
$Y$ marks the end of the string. $T$ generates something of the form $a^nUA^n$; the $A$s will eventually become $a$s. The $U$ generates something of the form $b^mZVB^m$; the $Z$ marks where the $c$s will go, and the $B$s will eventually become $b$s. At this point we have $b^ma^nZVA^nB^mY$.
The $V$ runs across the string to the right until it encounters a $B$; it turns that into a $b$ and turns itself into $W$, which runs back to the left until it hits the $Z$. At that point it deposits a $c$ to the left of the $Z$ and turns back into a $V$. The $V$ runs to the right through any $b$s that have been produced until it hits either a $B$ or an $A$. In the former case it behaves as previously described. In the latter it turns the $A$ into an $a$ and itself into $X$. The $X$ then runs left through $a$s and $b$s until it hits the $Z$, at which point it deposits a $c$ to the left of the $Z$ and turns into a $V$.
Eventually the $V$ running to the right must hit the $Y$. We collapse the $VY$ to $C$, which runs left until it encounters the $Z$, and the $C$ and $Z$ undergo mutual annihilation.


text:
Q: How to get hidden field values and assign in to the data table I am implementing this JQuery UI multiselect from http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/
I have managed to get it to use in my asp.net page, but while i am submitting the button, the selected text shows only the last element checked.So i want to get all selected values in the hidden field.But how to assign the hidden field value to the data table?
Here i am giving my datatable.Previuosly i am trying to do the selected items to store in data table.
DataTable dtAssigners = new DataTable();
dtAssigners.Columns.Add("GIMID", typeof(int));
dtAssigners.Columns.Add("UserId", typeof(int));
dtAssigners.Columns.Add("MODE", typeof(char));
dtAssigners.Columns.Add("CreatedBy", typeof(int));
DataTable dt = null;

foreach (System.Web.UI.WebControls.ListItem list in ddlAssignedTo.Items)
{
    if (list.Selected)
    {
        DataRow drUsers = dtAssigners.NewRow();
        drUsers["GIMID"] = GIMID;
        drUsers["MODE"] = 'I';
        drUsers["UserId"] = Convert.ToInt32(list.Value);
        drUsers["CreatedBy"] = CurUsr.UserId;
        dtAssigners.Rows.Add(drUsers);
    }
}

But now how to assign the hidden field value in data table ?Can anyone help me?

A: Replace your code with these
DataTable dtAssigners = new DataTable();
dtAssigners.Columns.Add("GIMID", typeof(int));
dtAssigners.Columns.Add("UserId", typeof(int));
dtAssigners.Columns.Add("MODE", typeof(char));
dtAssigners.Columns.Add("CreatedBy", typeof(int));
DataTable dt = null;

string[] value = hdnFiledID.Value.Split(',');
foreach (string va in value) {
DataRow drUsers = dtAssigners.NewRow();
drUsers["GIMID"] = GIMID;
drUsers["MODE"] = 'I';
drUsers["UserId"] = Convert.ToInt32(va);
drUsers["CreatedBy"] = CurUsr.UserId;
dtAssigners.Rows.Add(drUsers);
}

A: Have you some HTML? Check if the options are selected before submit. If not the multiple is not set to true.
This is taken from http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/
Next construct a standard multiple select box. Do not forget the multiple attribute:
<select id="example" name="example" multiple="multiple">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
</select>

A: if You need Hiddenfield value to datatable..
first add the control
 <input id="Hidden1" type="hidden" name="hddclick" runat="server" />

  Hidden1.Value = dt        // datatable object name


text:
Q: Check if a (2d domain) function has root in specific (small) region I am a little confused that I couldn't find anything regarding this topic, sorry in case I was just too dumb for searching.
My Problem:
I have an array of 2d points/tuples path that describe a curve in the plane.
I want to get an array, same shape as path, that has boolean values for if a certain function has a root in proximity of the corresponding path point. By in proximity I mean somewhere in a disk with fixed radius around the point.
What I did: Basically nothing. I'm stuck at step one, directly after
import numpy as np

def func(x,y):
    res = 0
    ...some magic with res,x and y
    return res

has_roots = np.zeros_like(path, dtype = bool)

I thought I might use scipys fsolve to find all roots and then check if any roots are in proximity of my path points. My path is however very large (in total I will be considering several million points) so performance is crucial, and the comparison between path points and all roots would surely be a bottleneck.
Any suggestions welcome!


text:
Q: Class method to create new instance I am getting into some serious OOP with Python and am running into some issues.
I have a class with an initialiser, three private variables and set and get methods for each variable.
Additionally, it has an input method that lets the user enter a value for the variables when they are called, rather than requiring an input call in the main function that passes a value to the class set method. This way I can immediately validate the user entry within the method specific to the data requirements:
def input_first_name(self):
    done = 0

    while done == 0:
        print("Input First Name:",end='')
        first_name = input()
        if first_name.isalpha():
            self.__first_name = first_name
            done = 1
        else:
            print("Invalid Entry. Please use alphabetic characters only.")

Using these input methods, I have another method that uses them to create a new class instance (just wait, I already know what you're thinking):
@classmethod
def new(cls):
    cls.input_first_name(cls)
    cls.input_last_name(cls)
    cls.input_birthday(cls)

    return cls

So I know that using this, I won't have actually instantiated a new instance. However, using the methods doesn't immediately throw any errors. But when I refer to my newly created instance with the get method, that's where I get into trouble that I know is related to not instantiating.
new_relative = Relative.new()

print(new_relative.get_first_name())

results in:
TypeError: get_first_name() missing 1 required positional argument: 'self'

Is there away to a way to have a class method usable in my main function for instantiating a new instance that employs my idea of user input and validation in a simple and elegant manner?
For reference, a minimal sample of the class:
class Relative:
    __first_name = ""
    __last_name = ""
    __birthday = 0

    def __init__(self, first_name,last_name,birthday):
        self.__first_name = first_name
        self.__last_name = last_name
        self.__birthday = birthday

    def get_first_name(self):
        return self.__first_name

A: I would do this with properties (the Pythonic replacement for endless gets and sets, see e.g. Python @property versus getters and setters), and leave only the input to a class method. Here is a minimal example:
class Relative:

    def __init__(self, first_name=None):
        self.first_name = first_name

    @staticmethod
    def _valid_name(name):
        return name is None or name.isalpha()
        # this will choke if name isn't None or a string - maybe add more rules?

    @property
    def first_name(self):
        return self._first_name

    @first_name.setter
    def first_name(self, new_name):
        if not self._valid_name(new_name):
            raise ValueError('Invalid first name: {!r}'.format(new_name))
        self._first_name = new_name

    @classmethod
    def from_input(cls):
        relative = cls()
        while True:
            # you could alternatively use cls._valid_name directly here
            try:
                relative.first_name = input('Enter first name: ')
            except ValueError:
                print('Please try again.')
            else:
                break
        return relative

In use:
>>> uncle_bob = Relative.from_input()
Enter first name: 123
Please try again.
Enter first name: *
Please try again.
Enter first name: Robert
>>> uncle_bob.first_name
'Robert'
>>> uncle_bob.first_name = '123'
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    uncle_bob.first_name = '123'
  File "<pyshell#11>", line 17, in first_name
    raise ValueError('Invalid first name: {!r}'.format(new_name))
ValueError: Invalid first name: '123'

Note that:

*

*Abstracting out the name validation to Relative._valid_name makes it easy to validate first and last names with the same rules (you could also add a middle name, and easily make that the same too).

*Using a @property means that the user can't set an incorrect name at any point, without forcing them to call a specific method to get/set values.

*I have used a private-by-convention single-underscore name for the internal variable, rather than a name-mangled double-underscore one - see e.g. the style guide.


text:
Q: Using multiple integers with one operand in a C conditional statement possible? Is it possible in C to write something like?  and if so how is it done?
if ( x != 1, 2, 7, 8, 90)

A: You can't compare multiple values that way.  You need to check each individually combined with the proper logical operator:
if ((x != 1) && (x != 2) && (x != 7) && (x != 8) && (x != 90)

What you wrote is something entirely different.  This:
if ( x != 1, 2, 7, 8, 90)

Is a single comparison operator followed by several instances of the comma operator.  The comma operator evaluates the left operand, discards the value, then evaluates the right operand and takes its value.
So that expression first evaluates x != 1 which will result in either 0 or 1.  That value is discarded and the value 2 is evaluated.  That value is in turn discarded and the next value (7) is evaluated.  Then 8 is evaluated and discarded, then 90 is evaluated which becomes the value of the entire expression.

A: No you can't do that. You need to write it like this :
if (x != 1 && x != 2 && x!= 3)

The comma operator has another effects, I let you looking for it :)

A: My answer is paradoxical, but strictly correct.

Is it possible in C to write something like? and if so how is it done?

a) Yes, it is possible.
b) How is done? Here is comma operator, yes, C has comma operator.
Final value is last element, 90 here
c) The question author didn't ask about comparison
So this if has sense if(90). Interesting is that sub-expression x!=1 is evaluated, but result is lost, and has no effect on final
if ( x != 1, 2, 7, 8, 90)
{
  here, true
}
else
{
  not here, false
}

Adan didn't ask how to compare, but the question posed above.
Appendix: fully working code from MSVC. Everything I say, anyone can debug.
#include "stdafx.h"

int main()
{
    int x = 2;
    int k = (x != 1, 2, 7, 8, 90);
    if (x != 1, 2, 7, 8, 90)
    {
        int k1 = 1;
    }
    else
    {
        int k2 = 2;
    }
    return 0;
}


text:
Q: java on linux - Have to press CtrlD twice String str = "";
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
int tempint = 0;
try {
    //The program cannot get out from this while loop!
    while((tempint = bfr.read()) != -1){
        str += Character.toString((char)tempint);
    }
}
catch(IOException ioe) {
    System.out.println(ioe);
}
//Print the input
System.out.println(str);

This is the code I wrote for reading user's input from standard input. This piece of code is extracted as playinput.jar
And I have written a script play to run this jar. But after I run ./play in terminal(linux) and finish my input, which does not contain enter, I have to press Ctrl+D twice to get the input printed out.
The same problem occurred when I ran another script called check, which will simply invoke ./play and send some input via stdin. After I ran ./check, it just hanged there and the input cannot be printed out.
Could anyone help fix this problem? Thank you:)

A: That's just how the Linux terminal works. It has nothing to do with your Java code.
If you test it out with a command like cat > textfile, you will find that unless you are at the beginning of a line, ^D doesn't immediately end the file as you might expect it to. (I don't know all the details of this behavior, but that's the gist of it.)
The convention for Linux is that a text file always ends with a newline. You can run into problems like this if you don't follow the convention.
However, I'm not sure about your problem with the program hanging when you send it data using redirection. That part is more surprising to me, since it's not interactive so the terminal behavior shouldn't be an issue.


text:
Q: How dynamically change UITableViewCell size for the last cell I have a UITableView with 16-20 cells inside with dynamic cell size. When a cell expands it self it should also move itself to the top of the screen. I did that using "UITableView setContentOffset" method. It works well except for the last cell in table, it's not able to move itself to the top.
I tried altering the frame & content size of UITableView but none of those were working for me!
Any Idea?
[UPDATE]
Here is a part of code: (it's inside the UITableViewCell, so self is pointing to current cell)
HomeViewController *tempViewController = (HomeViewController *) delegate;
UIView *commentField;

/*Skipping lines of codes manipulating commentField */

//Adding a subview to current cell which needs more space
[self addSubview:commentField];

//Expanding cellSize to EXPANDED_CELL_HEIGHT
//ViewController has access to cell size property and using that to determine each cell size.
[self setCellSize:(EXPANDED_CELL_HEIGHT)];

//Reloading UITableView to reflect the cell size change with animation
[[tempViewController tableView] beginUpdates];
[[tempViewController tableView] endUpdates];

[[tempViewController tableView] setContentOffset:CGPointMake(0, self.frame.origin.y) animated:YES];

and in my view controller (as I said earlier) I'm getting cellSize form cell itself
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [(BaseTableViewCell *)[cellContainer objectAtIndex:indexPath.row] cellSize];
}

A: You can change the height of the cell using the tableview delegate method heightForRowAtIndexPath: When indexPath.row equals your last row, return the height you would like.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == i)//i being whatever row index you want to change
    {
      return 60.0;//or float size you want
    }
    else
    {
     return 30.0;
    }
}

Or you can just modify the bounds of the cell inside willDisplayCell:. If your using a custom tableview cell, just shrink the subviews to whatever frame you'd like and make the cell background clear etc.


text:
Q: Using For with time series in R for example i have this data frame name DATA
Date        A
22/02/2016  2
22/02/2016  6
23/02/2016  7
23/02/2016  9
24/02/2016  4
24/02/2016  8

First i make a time series by days to create a new data frame
require(zoo)
B <- as.POSIXct(strptime(DATA$Date, "%d/%m/%Y"))
Time_series <- seq.POSIXt(from=B[1],to=B[6],by="day")
DATA_2 <- data.frame(Time_series)

Time_series
22/02/2016
23/02/2016
24/02/2016

Now i want to put in each date the mean of variable A
A <- DATA$A

for (i in Time_series){
print(mean(A[which( B == i)]))
}

[1] 4
[1] 8
[1] 6

My problem start here, when i want to make a vector of the printed value.
The idea is add the vector to DATA_2

A: You can use this code:
DATA_2$MEAN <-sapply(Time_series, function(x){
  mean(A[which( B == x)])
})

This is the output:
> DATA_2
  Time_series MEAN
1  2016-02-22    4
2  2016-02-23    8
3  2016-02-24    6

A: require(zoo)
DATA <- data.frame(Date = seq(Sys.Date(),Sys.Date()+9,by=1), A=rnorm(10))

B <- as.POSIXct(strptime(DATA$Date, "%Y-%m-%d"))
Time_series <- seq.POSIXt(from=B[1],to=B[10],by="day")
DATA_2 <- data.frame(Time_series)

A <- aggregate(DATA,by=list(DATA$Date), mean)

DATA_2 <- cbind(DATA_2, A$A)
colnames(DATA_2) <- c("Date", "Mean of Response for this Date")
DATA_2

         Date Mean of Response for this Date
1  2016-06-27                    0.537861522
2  2016-06-28                   -0.872163819
3  2016-06-29                   -0.538401384
4  2016-06-30                    1.162449246
5  2016-07-01                   -1.490553854
6  2016-07-02                    0.220161925
7  2016-07-03                    0.057615735
8  2016-07-04                   -0.955184268
9  2016-07-05                    0.007144786
10 2016-07-06                   -0.157812297


text:
Q: Does gcc-8 on arm64 debian ignores friend operator I want to compare two sets of objects. For the same code I get 2 different outputs on different machines.
The code is compiled with two different compilers. On the x86-64 machine i used gcc-11, on the aarch64 (raspberry pi4) machine i used gcc-8. I have to use the gcc-8 on the raspberry because it's in the official repositories.
Has anyone an idea why this happens? Have I missed something?
#include <iostream>
#include <set>
#include <memory>

class ClassA {
private:
    ::std::string id;
public:
    explicit ClassA(::std::string id);

    [[nodiscard]] ::std::string getId() const;

    bool friend operator<(const ::std::shared_ptr<ClassA> &lhs, const ::std::shared_ptr<ClassA> &rhs);
};

ClassA::ClassA(::std::string id) : id{::std::move(id)} {}

::std::string ClassA::getId() const { return id; }

bool operator<(const ::std::shared_ptr<ClassA> &lhs, const ::std::shared_ptr<ClassA> &rhs) {
    auto r = (lhs->id < rhs->id);
    ::std::cout << ::std::boolalpha << "Comparing lhs->id " << lhs->id << ", with rhs->id " << rhs->id
                << ". The result is " << r << ::std::endl;
    return (lhs->id < rhs->id);
}

class ClassB {
public:
    ::std::set<::std::shared_ptr<ClassA>> members;

    void add(::std::shared_ptr<ClassA> a);
};

void ClassB::add(::std::shared_ptr<ClassA> a) {
    members.emplace(::std::move(a));
}

int main() {
    ::std::cout << "Create first set:" << ::std::endl;
    auto firstContainer = ::std::set<::std::shared_ptr<ClassA>>{::std::make_shared<ClassA>("_3"),
                                                                ::std::make_shared<ClassA>("_5")};
    ::std::cout << "Create second set:" << ::std::endl;
    auto secondContainer = ::std::set<::std::shared_ptr<ClassA>>{::std::make_shared<ClassA>("_5"),
                                                                 ::std::make_shared<ClassA>("_3")};
    auto b1 = ::std::make_shared<ClassB>();
    auto b2 = ::std::make_shared<ClassB>();
    ::std::cout << "Fill first ClassB instance:" << ::std::endl;
    for (const auto &r: firstContainer) {
        b1->add(r);
    }
    ::std::cout << "Fill second ClassB instance:" << ::std::endl;
    for (const auto &r: secondContainer) {
        b2->add(r);
    }
    auto result = ::std::equal(b1->members.begin(), b1->members.end(), b2->members.begin(),
                               [](const ::std::shared_ptr<ClassA> lhs, ::std::shared_ptr<ClassA> rhs) -> bool {
                                   return lhs->getId() == rhs->getId();
                               });
    ::std::cout << ::std::boolalpha << "The result is: " << result << ::std::endl;

    ::std::cout << "First ClassB members" << ::std::endl;
    for (const auto &r: b1->members) {
        ::std::cout << "Id " << r->getId() << ::std::endl;
    }

    ::std::cout << "Second ClassB members" << ::std::endl;
    for (const auto &r: b2->members) {
        ::std::cout << "Id " << r->getId() << ::std::endl;
    }
    return 0;
}

The x86-64 output.
Create first set:
Comparing lhs->id _3, with rhs->id _5. The result is true
Comparing lhs->id _5, with rhs->id _3. The result is false
Create second set:
Comparing lhs->id _5, with rhs->id _3. The result is false
Comparing lhs->id _3, with rhs->id _5. The result is true
Comparing lhs->id _3, with rhs->id _5. The result is true
Fill first ClassB instance:
Comparing lhs->id _5, with rhs->id _3. The result is false
Comparing lhs->id _3, with rhs->id _5. The result is true
Comparing lhs->id _5, with rhs->id _3. The result is false
Fill second ClassB instance:
Comparing lhs->id _5, with rhs->id _3. The result is false
Comparing lhs->id _3, with rhs->id _5. The result is true
Comparing lhs->id _5, with rhs->id _3. The result is false
The result is: true
First ClassB members
Id _3
Id _5
Second ClassB members
Id _3
Id _5

The aarch64 output:
Create first set:
Create second set:
Fill first ClassB instance:
Fill second ClassB instance:
The result is: false
First ClassB members
Id _3
Id _5
Second ClassB members
Id _5
Id _3

A: The problem is here:
bool operator<(const ::std::shared_ptr<ClassA> &lhs, const ::std::shared_ptr<ClassA> &rhs)

The shared pointer has its own comparison operators which compares stored pointers. There is also owner_less which compares owned pointers (a specially constructed shared pointer can own one object but point to another, e.g. it can point to a member of the owned object).
If you need to compare the pointed-to objects, you should write a comparator doing just that, and pass it to the set as second template argument. Like:
struct my_ClassA_id_less {
    bool operator() (const ::std::shared_ptr<ClassA> &lhs, const ::std::shared_ptr<ClassA> &rhs) {
        // your comparison code here, as for operator<
    }
};

::std::set<std::shared_ptr<ClassA>, my_ClassA_id_less> my_set;


text:
Q: How to create an assertion in JDBC? I'm using Postgresql and JDBC and I'm trying to figure out how to create an assertion.
I currently have two relations table A(url varchar(30)) and table B(url varchar(30)) and I would like to write an assertion so that it is impossible to insert into table B if that element already exists in table A. How do I do this in JDBC? If it's not possible to use assertions, how would I make something similar happen?
EDIT: Ok, so I've read that it's not possible to create an assertion using postgresql; thus, my question is now, how would I do something similar using the constraints of Postgresql and JDBC?

A: I am not sure there is not  typo, perhaps 'JDBM' should be 'JDBC'?
For MapDB (aka JDBM4) there is plan to implement   map modification listeners, which would handle similar situations. There is no functionality like this in JDBM3.
For now I would recommend not to use assertions and check it in your code.

A: What you want is effectively a negative foreign key constraint, which isn't directly supported. You can implement this constraint using a PL/PgSQL BEFORE INSERT OR UPDATE trigger function that tests the condition.
See PL/PgSQL trigger procedures in the Pg docs.
You'll probably need to use SERIALIZABLE isolation mode to handle races where one transaction inserts into B while the other inserts into A. You'll need the improved serializable isolation support in 9.1/9.2.


text:
Q: Is there a way to forcefully echo to the command-line from a bash function call? I've got a bash script where I define a bunch of functions in good programming style.  These functions "return" values by echo-ing them.  So, for example:
some_function() {
   echo "I like pie."
}

what_do_i_like=`some_function`

Now, I'd like to add in some debugging statements to my functions.  Unfortunately, anything I echo just gets caught by the caller in the variable.  e.g.,
some_function() {
    if [[ "${DEBUG}" = "${TRUE}" ]]; then
        echo "We're about to find out what we like."
    fi
    echo "I like pie."
}

what_do_i_like=`some_function`

... The debug statement gets caught in the what_do_i_like variable.
Is there any way I can bypass this and forcibly print to the command-line and have the output not be caught in the variable?

A: echo "We're about to find out what we like." >/dev/tty

A: Doesn't echo to stderr work? echo 1>&2 message

A: There is a shell command interface for syslog(3):
logger -p DEBUG Hi there


text:
Q: Gtk4 Video only plays audio I'm using Gtk4's Video widget to play the "me at the zoo" video. It's saved as an mp4 file. Here is my code:
#!/usr/bin/env python3

import sys

import gi
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk

class Player:
    def __init__(self, video: str):
        self._video = video

    def activate(self, app):
        window = Gtk.ApplicationWindow(application = app)
        player = Gtk.Video.new_for_filename(self._video)
        window.set_child(player)
        window.show()

def main():
    if len(sys.argv) < 2:
        sys.exit()

    player = Player(sys.argv[1])
    gtkApp = Gtk.Application()
    gtkApp.connect('activate', player.activate)
    gtkApp.run()

if __name__ == '__main__':
    main()

When I run this and press play, only the audio plays. All I can see besides the controls is a black background. Also, clicking on the large play button in the middle of the window doesn't work - only the controls at the bottom appear to be enabled.
The video works just fine when I play it with mpv.


text:
Q: which families of PDFs are closed under translation and multiplication? The product of two PDFs is not usually a PDF; but it is a (possibly zero) scalar multiple of another PDF.
I will call a set $S$ of PDFs over $\mathbb{R}$ closed under translation and multiplication if

*

*$f(x)\in F \Rightarrow f(x-a) \in F$ for all $a\in\mathbb{R}$;

*$f, g\in F \Rightarrow fg = \alpha h$ for some $h\in F$ and $\alpha \in \mathbb{R}$.

The set of all Gaussians is one notable nontrivial example of such an $S$. Are there any other notable examples? How rich is the space of such sets $S$?


text:
Q: Tree structure with  In this below image,

 is used for tree like structure.
But I want to do same with

.
Is there any possible way to achieve this?

A: [https://codepen.io/st-iv/pen/YzPpPYG]
you can use this link for your solution


text:
Q: JQuery - Disable draggable element based on data selector I have an appended draggable element which has a dynamic value for attribute data-pin:
var pin = 0;

$('#pins').append("

");

$('*[data-pin=' + pin + ']').draggable({
  stack: '#pins div',
  revert: false
});

When the element is dragged onto the droppable, a new draggable element is appended as before:
$('#drop_box').droppable({
  drop: function (event, ui) {
  pin ++;
  $('#pins').append("

");
  $('*[data-pin=' + pin + ']').draggable({
  stack: '#pins div',
  revert: false
});
}
});

Now, I want to disable draggable on the dropped element, and allow the newly appended element to be draggable, and so on.  How can I do this?
I would also like to have the newly appended elements to be in the same spot in the container div, rather than appearing after the previous elements space in the div.  Can this be done?
See fiddle at http://jsfiddle.net/h573y2wa/3/

A: Here is a solution that uses clones, and sets the data-pin attribute after dropping. You can see I'm only using the one pin as draggable and cloning what's needed.
var pin = 0;

$('

').appendTo('#pins').draggable({
    appendTo: '#drop_box',
    helper: 'clone',
    stack: '#drop_box .pin',
    revert: false
});

$('#drop_box').droppable({
    drop: function (event, ui) {
        ui.helper.clone().attr('data-pin', pin).appendTo(this);
        pin++;
    }
});

http://jsfiddle.net/snvsdkas/1/


text:
Q: XCode 4.4 how to permanently add files to project I just started with iOS development, so pardon if this is too simple
I have a project open in XCode, and when i created a new storyboard/xib/view.h/view.m file it shows up in xcode just fine from the folder hierarchy. However, whenever i quit xcode and start xcode up again, the files disappear from the folder hierarchy. I have to manually then right click on the parent folder and do "Add files to 'project'" each and every time. (which works just fine until i restart XCode)
What's wrong with my configuration? is my xcode.proj not being modified or something? (i think it's locked under version control) If so, where can i find this file?
or is it something else that i'm missing?
Thanks in advance!

A: Your project.pbxproj in your .xcodeproj directory is write protected.  Check it out with your source control system (or use a decent one like git which doesn't lock files :).


text:
Q: Ubuntu 22.04 LTS -- Dummy Output I have dual boot windows 11 and Ubuntu 22.04 LTS. In windows 11 speakers work fine but I can't hear anything on internal speakers on Ubuntu and also my microphone is not detected. If I connect my laptop with a HDMI cable, the speakers from the monitor works fine. But still there is no option to change to internal speakers.
Also alsamixer doesn't detect any internal speakers only nvidia. When I try to run alsamixer on termial it gives error, I managed to open it by using alsamixer -c 1 Screenshot from alsamixer
Can anyone help me?


text:
Q: Which algorithm to use for a clustering problem when we have numerical and categorical data? I'm almost new to clustering and a bit confused about the method to use.
I have a set of buildings that I want to cluster them according to their energy consumption, size, type, and neighborhood. I used k-means method and I used "get_dummies" method to deal with my categorical data.
I would like to ask if this is a correct way to deal with categorical data? (I also tried to simply map them to numbers like 1,2,3,etc and normalize them before clustering, but didn't received suitable results)
In case you suggest another algorithm (random forest, svm, or anything else) I appreciate it if you provide me a link or website to learn it.
Another question is, if I want one of my features have a more effect on this clustering, is it fine to multiply it by 2 after normalization and then run the clustering part?
Thanks.
** What I mean by "get_dummies"?

A: I think that's pretty much it!  Use label encoders or one-hot-encoding to convert non-numerics into numerics.
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder# creating initial dataframe
bridge_types = ('Arch','Beam','Truss','Cantilever','Tied Arch','Suspension','Cable')
bridge_df = pd.DataFrame(bridge_types, columns=['Bridge_Types'])# creating instance of labelencoder
labelencoder = LabelEncoder()# Assigning numerical values and storing in another column
bridge_df['Bridge_Types_Cat'] = labelencoder.fit_transform(bridge_df['Bridge_Types'])
bridge_df

Result:
  Bridge_Types  Bridge_Types_Cat
0         Arch                 0
1         Beam                 1
2        Truss                 6
3   Cantilever                 3
4    Tied Arch                 5
5   Suspension                 4
6        Cable                 2

Or...
import pandas as pd
import numpy as np# creating initial dataframe
bridge_types = ('Arch','Beam','Truss','Cantilever','Tied Arch','Suspension','Cable')
bridge_df = pd.DataFrame(bridge_types, columns=['Bridge_Types'])# generate binary values using get_dummies
dum_df = pd.get_dummies(bridge_df, columns=["Bridge_Types"], prefix=["Type_is"] )# merge with main df bridge_df on key values
bridge_df = bridge_df.join(dum_df)
bridge_df

Just keep in mind, if you have a whole lot of labels, your data is going to be pretty sparse after you make everything numeric.  Also, yes, you can 'game it' be doubling a feature.  Here is basic example.
import numpy as np
data = np.asarray([np.asarray(DF['Feature1']),np.asarray(DF['Feature1']),np.asarray(DF['Feature2'])])

It seems a little weird, and I've never done that in practice, but it should give you your desired results.  You know what...test it and see how you get along.  Finally, when you have some free time, read through the stuff on the link below.  You will learn a lot from that link.
https://scikit-learn.org/stable/modules/clustering.html


text:
Q: How to Get List/Reference Computers on a Domain, When My computer is Not a Part of that Domain This is a question I posted on Stack Overflow: https://stackoverflow.com/questions/15211175/how-to-get-list-reference-computers-on-a-domain-when-my-computer-is-not-a-part

I'm looking to get a list of computers on a domain, which my computer is not a part of. I would also like to know how to reference the computers of that domain by their names, not by their IP address.
Some background:
I've tried the net view command, which gives me a list of local computers, but not list of computers that are part of the remote domain. I have limited information on how our network is connect to the other office and found that others don't know either. I know there is a VPN connecting our two office locations. Our local network is not on a domain, where the other office is.
I've also tried netstat -a <<ipaddress>> which does not provide me all the info I desire.
The people at the other office have provided me with the IP address of the computer. However I'm hoping to be able to reference it by name instead of IP address (because the other office utilizes scripts which use computer names instead of IPs... I don't want to have to update all the scripts). Any help is appreciated.

A: If you have physical access to the network, then nslookup  should return the hostname. However this has nothing to do with a "domain", its basic DNS / networking.
Gathering domain information like a list of all machines is a HUGE security risk. Whatever they need they should be going through their IT or sysadmin. If they are delegating that to you, you should be allowed onto the domain.


text:
Q: sqlalchemy, bidirectional many to many with association object, parent and child classes In the documentation for sqlalchemy bidirectional many to many with association object
http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#association-object
class Association(Base):
    __tablename__ = 'association'
    left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
    right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
    extra_data = Column(String(50))
    child = relationship("Child", back_populates="parents")
    parent = relationship("Parent", back_populates="children")

class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship("Association", back_populates="parent")

class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)
    parents = relationship("Association", back_populates="child")

The names of the tables are parent and child.
In this orm scenario, does sqlalchemy still treat these tables as parent to child in the rdbms sense? Or is this portion of the documentation just holding over the names of the classes, Parent and Child, from above on the page? The code seems to create a symmetrical relationship.


text:
Q: Convert UTC Date to Local Timezone JSP I have variable that store data datetime UTC from database. I want to make it in Local datetime format, can i do that?
for example:

Date dateFromDB = getfromDB();
dateFromDB = UTCtoLocalTimezone(dateFromDB);

What the code in method UTCtoLocalTimezone?
Or do you have any better solution?
thankyou!

A: Personally I would use Joda Time:
DateTimeZone zone = ...;
DateTime dateTime = new DateTime(date.getTime(), zone);

Joda Time is a much better date and time API than the built-in one, but that would work too:
TimeZone zone = ...;
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(date);

I wouldn't use the (deprecated) Date constructor though. For one thing, it doesn't do what you appear to think it does... this:
 new Date(2012,03,02,11,30,0);

constructs a value representing the 2nd of February in the year 3912...
This won't be a problem if you're fetching the Date from the database, but obviously it will affect unit testing. You should really avoid all the deprecated members of Date - they're deprecated for good reason.


text:
Q: ERR_CONNECTION_REFUSED - Localhost:8080, firebaseID seems involved
I have a problem trying to connect my firebase with mongoDB, which I got the code right with connections working, tried using SwaggerUI to post and get and its fine. Firebase also stores the right information, however first I got a Cors error were Cors refused connection (I changed to http//:localhost/8080/ and it started working.) Now instead I get a ERR_CONNECTION_REFUSED in the chrome console and I can't seem to understand why it is refusing my connection. Tried using this is the Terminal: echo OK > /dev/tcp/localhost/8080 and got:

connect: Connection refused
/dev/tcp/localhost/8080: Connection refused

Edit: Ok so from network tab in console it seems I am getting some kind of firebaseID connection error:

GET http://localhost:8080//profiles/users/by-firebase-id/W4ucZtMTafPMBLxKur8m6C6h3gG2 net::ERR_CONNECTION_REFUSED

Here is some of the code with fetch and firebaseID:

async getById(id: string): Promise<UserDto> {
    const fetchedUser = await this.userModel.findById(id);
    if (fetchedUser == null) {
        return null;
    }

    return UserDto.fromDocument(fetchedUser);
}

async getByFirebaseId(firebaseId: string): Promise<UserDto> {
    const fetchedUser = await this.userModel.findOne({ firebaseId: firebaseId?.trim() });
    if (fetchedUser == null) {
        return null;
    }

    return UserDto.fromDocument(fetchedUser);
}

async create(createUserDto: CreateUserDto): Promise<UserDto> {
    const now = new Date();

    const userToCreate = UserDto.fromCreateUserDto(createUserDto);
    userToCreate.createdAt = now;
    userToCreate.personId = ""; //@TODO

    const createdUser = await new this.userModel(userToCreate).save();

    return UserDto.fromDocument(createdUser);
}

async delete(id: string): Promise<boolean> {
    try {
        const result = await this.userModel.findByIdAndDelete(id);
        return !!result;
    } catch (error) {
        return false;
    }
}

async joinOrganization(userId: string, joinOrganizationDto: JoinOrganizationDto): Promise<UserDto> {
    const updatedUser = await this.userModel.findByIdAndUpdate(
        userId,
        {
            $addToSet: { organizationIds: joinOrganizationDto.organizationId },
        },
        { new: true },
    );

    return updatedUser ? UserDto.fromDocument(updatedUser) : null;
}

}


text:
Q: How to allow all special characters in magento password field? I am trying to allow all special characters in register page in password field.
As of now it only allows /[$@$!%*?&#^ ]/
But I want to allow all. like: ^[@!#\$\^%&*()+=-[]\\';,./{}\|\":<>\? ]+$
So how can I customize validate.js for specific class validate-password.
Code:
    ['validate-password', 'Please enter 8 or more characters. Password must contain Numeric, Alphabetic and Special characters.', function(v) {
              var pass=v.strip(); /*strip leading and trailing spaces*/
                //alert(pass);
               // var fname =$(firstname).value;
               // alert(pass.indexOf(substring) !== -1);
               //var lname = $(lastname).value;
                if (0 == pass.length) {
                return true;
            }
            if (!(/[a-z]/i.test(v)) || !(/[0-9]/.test(v)) || !(/[$@$!%*?&#^]/.test(v))) {
                return false;
            }
/*            if((pass.indexOf(fname) > -1) ||(pass.indexOf(lname) > -1)){
                return false;
            } */
                return !(pass.length>0 && pass.length < 8);
            }],


text:
Q: Python subprocess with heredocs I was playing around with Python's subprocess module, trying a few examples but I can't seem to get heredoc statements to work.
Here is the trivial example I was playing with:
import subprocess
a = "A String of Text"
p = subprocess.Popen(["cat", "<<DATA\n" + a + "\nDATA"])

I get the following error when I run the code above:
cat: <<DATA\nA String of Text\nDATA: No such file or directory

Am I doing it wrong? Is this even possible? If so how would I go about doing it?

Update
Just wanted to say that this should never be performed in a real python program because there are better ways of doing this.

A: The shell "heredoc" support is a shell feature. subprocess.Popen does not run your command through the shell by default, so this syntax certainly won't work.
However, since you're using pipes anyway, there isn't any need to use the heredoc support of the shell. Just write your string a to the stdin pipe of the process you just started. This is exactly what the shell would do with the heredoc anyway.
You can do this with Popen.communicate():
p.communicate(a)

The return value of the communicate() function contains the output of the process (in two streams, see the docs).

A: You're passing shell syntax as an arguments to cat program. You can try to do it like that:
p = subprocess.Popen(["sh", "-c", "cat <<DATA\n" + a + "\nDATA"])

But the concept itself is wrong. You should use Python features instead of calling shell scripts inside your python scripts.
And in this particular case you should that shell's heredoc syntax interpolates variables, so you'll need to escape all the text inside a and make sure there's no DATA line in it.

For Python equivalent, I think the closest idea to this (assuming you don't want just print(a) ;-)) is passing the value of the variable to stdin of a spawned process:
p = subprocess.Popen(["program", ...], stdin=subprocess.PIPE)
p.communicate(a)

A: As others have pointed out, you need to run it in a shell. Popen makes this easy with a shell=True argument. I get the following output:
>>> import subprocess
>>> a = "A String of Text"
>>> p = subprocess.Popen("cat <<DATA\n" + a + "\nDATA", shell=True)
>>> A String of Text

>>> p.wait()
0

A: As of Python 3.5 you can use subrocess.run as in:
subprocess.run(['cat'], input=b"A String of Text")


text:
Q: Updating a jprogress-bar I'm running an AudioInputStream in a jframe. I have a progress bar on the jframe. I named the jproggressbar "bar". I am trying to get the progress bar to track how far the AudioInputStream is through a song. I'v tried a loop, but every way i try it, the loop ends up making the jframe freeze. Then I cant go about other tasks like closing the window or pausing the AudioInputStream until the song finishes. Could someone please help me?

A: In a way or another you need to update the progress bar in the EDT, and keep processing the stream outside the EDT. One way to do it is using a SwingWorker. You'd do the processing in doInBackground() and update the progress with publish(). Alternatively you can roll your own threading, and use SwingUtilities.invokeLater() when you need to update the progress bar.

A: I found out that the loop has to be implemented in a different thread from the JFrame. as in,
public class Window extends JFrame{
       public int getMusicPosition(){
                  //get the music positional value and return it
       }

       public Window(){
                  new Thread(new BarUpdater()).start();
       }

       public class BarUpdater implements Runnable{
                  public void run(){
                             while(true){
                                        bar.setValue(getMusicPosition());
                             }
                  }
       }
}


text:
Q: Minimum/maximum distance between points of $n$ disks Given $n$ disks with $n ≥ 2$, what's the minimum and maximum distance between any point within these disks?
For $n = 2$, the problem is fairly easy.
Consider two disks with $r_{1,2} = 1$ centered at $M_1(0|0)$ and $M_2(1, 0)$ respectively.
As they intersect, the minimum distance between any points within these disks is $d_{min} = 0$, and it's easy to see that the maximum distance is
$$d_{max} = \sqrt{({M_1}_x - {M_2}_x)^2 + ({M_1}_y - {M_2}_y})^2 + r_1 + r_2$$
In the example above, we have
$$d_{max} = \sqrt{(0-1)^2+(0-0)^2} + 1 + 1 = 3$$
If we shift $M_2$ to the right by two units, the disks don't intersect anymore:

We now compute the minimum distance to be
$$d_{min} = \sqrt{({M_1}_x - {M_2}_x)^2 + ({M_1}_y - {M_2}_y})^2 - r_1 - r_2$$
With $M_2(3, 0)$, we then get:
$$d_{min} = \sqrt{(0 - 3)^2 + (0 - 0})^2 - 1 - 1 = 1$$
Now consider $n > 2$ disks.

Clearly, $d_{min}$ and $d_{max}$ are not additive. Every neighboring disk has $d_{min} = 0$, but for the minimum distance from the leftmost disk to the rightmost, $d_{min} \neq 0$. A similar argument applies to $d_{max}$.
Question: In general, what's the minimum/maximum distance between $n$ disks where $n > 2$?
Update
This means: Given disks $D_1$ to $D_n$, I'm looking for the distances $d_{min}$ and $d_{max}$ for which there exists a set of points $P_1$ to $P_n$ where $P_i$ lies in $D_i$ and the length of the polygonal chain formed from $P_1$ to $P_n$ is minimal/maximal.


text:
Q: Get state name from drop down list after click submit button (part 3) Cont. on Pass city name from php to js (part 2)
State data json ($stateJsonObject):
Array (
    [0] => stdClass Object ( [stateId] => s1 [stateName] => Kuala Lumpur)
    [1] => stdClass Object ( [stateId] => s2 [stateName] => Selangor)
)

Code (stateName):
<html>
<head></head>

<body>
<form action="test3.php" method="post">
    State:
    <select name="state" id="state" onchange="showCity(this, 'city')">
        <option value ="">select one</option>
        <?php
        for($i = 0; $i < count($stateJsonObject); $i++)
        {
            echo '<option value = '.$stateJsonObject[$i] -> stateId.'>';
            echo $stateJsonObject[$i] -> stateName;
            echo '</option>';
        }
        ?>
    </select>
    <input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

My question is:
When I choose Selangor from drop down list, after I click submit button, how do I keep the Selangor name in the drop down list selected?

A: If this is submitted on the same page, you could add the currently submitted entry and put a checked attribute inside the loop:
<form action="test3.php" method="post">
    State:
    <select name="state" id="state" onchange="showCity(this, 'city')">
        <option value ="">select one</option>
        <?php
            for($i = 0; $i < count($stateJsonObject); $i++)
            {
                $selected = ($stateJsonObject[$i]->stateId == $_POST['state']) ? 'checked' : '';
                echo "<option value='".$stateJsonObject[$i]->stateId."' $selected>";
                echo $stateJsonObject[$i] -> stateName;
                echo '</option>';
            }
        ?>
    </select>
    <input type="submit" name="submit" value="Submit" />
</form>

Or with a foreach variant:
foreach($stateJsonObject as $state) {
    $stateId = $state->stateId;
    $stateName = $state->stateName;
    $selected = ($stateId == $_POST['state']) ? 'checked' : '';
    echo "<option value='$stateId' $selected>$stateName</option>";
}


text:
Q: Magento: Product collection filtered by two categories I am writing a module that loads for me a list of featured products. All featured products are seated in their own category + hidden category "featured". The script returns me an error.
On category view (list.phtml) I call for gettopproducts.phtml (which works fine):
<?php $currentCategory = Mage::registry('current_category'); ?>
<?php $_products = $this->getTopProducts($currentCategory); ?>
<?php echo $this->__('Available products: ').$_products->count(); ?>

From gettopproducts.phtml I call a function getTopProducts() of Gettopproducts.php passing a current category. In Gettopproducts.php I have this:
public function getTopProducts($currentCategory)
{
    $_productCollection = Mage::getResourceModel('reports/product_collection')
    ->addAttributeToSelect('*')
    ->addCategoryFilter($currentCategory)
    ->addAttributeToFilter('category_ids',array('finset'=>'87'));
    $_productCollection->load();
    return $_productCollection;
}

This row:->addAttributeToFilter('category_ids',array('finset'=>'87')); should add a second category filter (ID of the "featured" category). But when I use this, I get an error. When I remove this row: ->addAttributeToFilter('category_ids',array('finset'=>'87')); it works perfectly.
I am using Magento 1.7.2

A: I found out the reason. For Magento 1.4+, category IDs are not a member of the reports/product_collection.
This is the way how to get it:
replace ->addAttributeToFilter('category_ids',array('finset'=>'87'));
with:
$_productCollection->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left');
$_productCollection->addAttributeToFilter('category_id', array('in' => array('finset' => '87')));

So the code looks like this:
$_productCollection = Mage::getResourceModel('reports/product_collection');
$_productCollection->addAttributeToSelect('*');
$_productCollection->addCategoryFilter($currentCategory);
$_productCollection->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left');
$_productCollection->addAttributeToFilter('category_id', array('in' => array('finset' => '87')));
$_productCollection->load();
return $_productCollection;

A: For magento 1.7 this is what works for me:
$collection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('id')
    ->addAttributeToFilter('visibility', 4)
    ->addAttributeToFilter('home_slider', array('neq' => ''))
    ->addAttributeToFilter('home_slider_value', $slide_num)
    ->addStoreFilter();
    //here pass an array() of CATEGORY IDs
    $catids = array('id_1,id_2, etc..');

    $statements = array();
    foreach ($catids as $categoryId){
        if (is_numeric($categoryId)){
         $statements[] = "{{table}}.category_id = $categoryId";
        }
    }

    $collection->distinct(true)
    ->joinField('category_id','catalog/category_product', null,'product_id = entity_id', implode(" OR ",$statements),'inner');


text:
Q: Identity for expected value of a discrete random variable involving higher powers I want to prove the following identity:
$$
\sum^{\infty}_{i=1}i^2P(X\geq i)=\dfrac{E(X^3)}{3}+\dfrac{E(X^2)}{2}+\dfrac{E(X)}{6}
$$
where $X$ is a discrete random variable with positive integer values.
I tried to use $E(X^n)=\sum_i i^nP(X=i)$ and I also know that $E(X)=\sum_i P(X\geq i)$ but so far I got nothing.

A: The idea is similar to that of the proof of $\mathbb{E}[X]=\sum_{n=1}^\infty \mathbb{P}\{ X\geq n \}$ . Namely, the crux is to rewrite $\mathbb{P}\{ X\geq n \} = \sum_{\ell=n}^\infty \mathbb{P}\{X=\ell\}$, and then to swap the inner and outer sums in $\sum_{n=1}^\infty\sum_{\ell=n}^\infty$.
Specifically: rewrite
$$\begin{align}
\sum_{n=1}^{\infty}n^2\mathbb{P}\{X\geq n\}
&= \sum_{n=1}^{\infty}\sum_{\ell=n}^\infty n^2\mathbb{P}\{X=\ell\}
= \sum_{\ell=1}^\infty\sum_{n=1}^{\ell} n^2 \mathbb{P}\{X=\ell\}
\\
&= \sum_{\ell=1}^\infty \mathbb{P}\{X=\ell\}  \sum_{n=1}^{\ell} n^2
= \sum_{\ell=1}^\infty \mathbb{P}\{X=\ell\}\cdot \frac{\ell(\ell+1)(2\ell+1)}{6} \\
&= \mathbb{E}\left[ \frac{X(X+1)(2X+1)}{6} \right]
\end{align}$$
where we used the known identity $\sum_{n=1}^N n^2 = \frac{N(N+1)(2N+1)}{6}$.
Now, expand $\frac{X(X+1)(2X+1)}{6}$ and use linearity of expectation:
$$\begin{align}
\mathbb{E}\left[ \frac{X(X+1)(2X+1)}{6} \right]
&= \mathbb{E}\left[ \frac{2X^3+3X^2+X}{6} \right]
= \mathbb{E}\left[ \frac{X^3}{3}+\frac{X^2}{2}+\frac{X}{6} \right]
\\
&=  \frac{\mathbb{E}[X^3]}{3}+\frac{\mathbb{E}[X^2]}{2}+\frac{\mathbb{E}[X]}{6}
\end{align}$$


text:
Q: Accessing files from a path in batch scripts I have a batch script, where I want to list out the folders from a path. I am executing the batch script from a different location.
I have the script as below, but it fails:
@echo off
set PATH = C:\Users\XXX\Downloads\CmdLine;
for /d %%D in (%PATH%) do (
    echo %%~nxD
    echo.
)

It prints out :
\Common was unexpected at this time

I want the list of folder names to be printed. Any suggestions?
PS: A starter in batch scripting

A: There are three main issues with your script.
First and foremost, %PATH% is already a system variable, and it tells Windows where important things are located on your system. Please do not change its value unless you know what you're doing.
Second, variable names in batch are allowed to have spaces in them, so you've actually created a variable called %PATH % and given it the value  C:\Users\XXX\Downloads\CmdLine; (note the leading space).
Third, for /D only iterates over folders if the set contains a wildcard.

If you correct the three issues, your code will look like this:
@echo off
set "parent_dir=%USERPROFILE%\Downloads\CmdLine"
for /d %%D in (%parent_dir%\*) do (
    echo %%~nxD
    echo.
)

Other optional changes are putting quotes around the set statement to prevent hidden trailing spaces and using %USERPROFILE% instead of C:\Users\xxxx to make the script more portable.


text:
Q: Как указать версию composer-пакета при публикации? Доброго дня, сделал небольшой пакет для composer и пытаюсь подключить его для проверки в другой проект. но composer require не скачивает пакет ссылаясь на то, что нет стабильной версии пакета.
" Could not find package xtfkpi/image-loader at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability "
На самом сервисе packagist для пакета показывается только версия dev-master, хотя в других пакетах на сайте можно найти разные версии пакета. Подскажите, как все же указать версию пакета, чтобы его потом можно было нормально инсталлировать?
 composer.json сейчас выглядит так:

{
    "name": "xtfkpi/img-loader",
    "description": "package for image download",
    "stability":"stable",
    "version":"1.0.1",
    "type": "package",
    "minimum-stability":"dev",
    "require": {
        "php": ">=5.3"
    },
    "require-dev": {
        "phpunit/phpunit": "^6.0"
    },
    "license": "MIT",
    "authors": [
        {
            "name": "xtfkpi",
            "email": "xtfkpi@yopmail.com"
        }
    ],
    "autoload": {
    "psr-4": {
      "xtfkpi\\Imgloader\\": "src"
    }
  }
}

A: "minimum-stability":"dev"
Ваша библиотека не имеет стабильных(stable) версий, поэтому не может быть подключена в stable проект.
Нужно либо зарелизить stable версию без dev-зависимостей, либо понизить требования проекта до dev

Лучше всего вообще удалить version из composer.json
Для версионирования же просто использовать имена веток и теги в репозитории
Они неплохо поддерживаются packagist
git tag v0.0.1


text:
Q: Distance using disparity map(opencv) I am working on a project in OpenCV(c++).Basically my aim is to estimate the real-world distance through disparity map.
Now I have already calculated disparity ( max disparity--as my object of interest is the one nearest to the camera ),so now how do I go about calculating the distance.The value of disparity that I got is 1264 and my focal length is around 28 mm.
Using the formula D=b*f/d { b=60 mm,f=28 mm,d=1264 pixels }
'D' comes out to be 1.38 units,whereas my actual distance is 150 cm.The numerical value regardless the units is wrong! :/ .
Where exactly am I going wrong?
Any help is appreciated.
The code that I wrote :
( C++ & Opencv 3.1 )
#include<iostream>

#include<opencv2/opencv.hpp>

using namespace std;

using namespace cv;

int main() {

Mat left, right, dis;

float b = 6, f = 2.8, d, pd = 104;
left = imread("leftm.jpg", IMREAD_GRAYSCALE);

right = imread("rightm.jpg", IMREAD_GRAYSCALE);
imshow("or", right);

blur(left, left, Size(5, 5), Point(-1, -1));
blur(right, right, Size(5, 5), Point(-1, -1));

Ptr<StereoBM> sbm = StereoBM::create(16 * 5, 21);

sbm->compute(left, right, dis);
double min, max;
erode(dis, dis, Mat(), Point(-1, -1), 3);

//dilate(dis, dis, Mat(), Point(-1, -1), 1);

minMaxLoc(dis, &min, &max);
dis.convertTo(dis, CV_8UC1, .45);

imshow("disparity", dis);
cout << "disparity beaches!!!!"<<endl;
cout << "max disparity :" << max << endl;
d = max;
cout << " => distance = " << (((b*f) / d)*pd)*100<<" cm"<<endl;
waitKey(0);
return 0;
}


text:
Q: Tool for measuring html-rendering time I have speed problems with my Website (1.3MB).
The problem is particularly relevant in the Internet Explorer (7,8).
Now I'am searching a tool for measuring the rendering time (HTML, JavaScript, CSS).
Thanks for help !
best regards

A: I believe you want a profiling tool for IE. Knowing how popular IE is with web designers/developers, I am not surprised that there are not many tools. I used to use YSlow from Yahoo in Mozilla browsers. When I had to test only in IE, (when my client insisted on it), I came across MSFAST.

A: One tool I found interesting is called Speed Tracer. It can be used to figure out, why your page loads that long. It differs from YSlow in the way that you see, what the Browser actually is doing. When it starts drawing the website on your screen, CSS evaluation, JavaScript execution and so on.
https://developers.google.com/web-toolkit/speedtracer/
Here's a list of more useful developer tools provided by google:
https://developers.google.com/speed/tools

A: If you use Google chrome, it has some excellent profiling tools.
See here for more info:
http://google-chrome-browser.com/google-chrome-developer-tools-profiling-and-optimizing

A: Chrome, Safari (basically all WebKit-based browsers) do provide the Inspector which you can open by right-clicking on any place on a web site and choose "Inspect Element".


text:
Q: Creating database without filename? Is it possible to create a database only by giving it the logical name without the filename -> which should result in creating the database in the default path with the database name.mdf?
CREATE DATABASE A
ON PRIMARY (
name = Z)

I found this from Microsoft documentation:

If data file name is not specified, SQL Server uses database_name as both the logical_file_name and as the os_file_name. The default path is obtained from the registry. The default path can be changed by using the Server Properties (Database Settings Page) in Management Studio. Changing the default path requires restarting SQL Server.

How come that when I try the query above I get an error:

File option FILENAME is required in this CREATE/ALTER DATABASE statement.

Unless I misunderstood what data file name refers to here.

A: Just use
CREATE DATABASE A
it should work.

A: This is a restriction of the SQL Server CREATE DATABASE syntax. According to the documentation, the <filespec> clause is optional. However, when specified (to include a non-default logical name), both NAME and FILENAME must be specified. The <filespec> clause syntax is:
{
(
    NAME = logical_file_name ,
    FILENAME = { 'os_file_name' | 'filestream_path' }
    [ , SIZE = size [ KB | MB | GB | TB ] ]
    [ , MAXSIZE = { max_size [ KB | MB | GB | TB ] | UNLIMITED } ]
    [ , FILEGROWTH = growth_increment [ KB | MB | GB | TB | % ] ]
)
}


text:
Q: Display '⤭' in iOS safari through CSS content property The html looks like this:

Sample Text

So, I've already converted the '⤭' character to ASCII which shows fine in my desktop's browser; however, on iPhone, it's blank!

A: The problem could be with content: '\292d'; even though they say content is supported with safari 1.0 and up it still does not work properly.
i used it for displaying images and it used to show up in inspect element but not in browser window, the entity '\292d' is infact supported
instead Try putting it directly inside the tag, or use javascipt if you want it to be dynamically inserted


text:
Q: OptionButton Property Disable I have an option group or "frame", and inside I have 4 buttons (Option Buttons).
They are called:
opt_mtto
opt_elec
opt_qlty
opt_complete
So I was selecting the property of each button to Enable = False, so when my form load they will be Disabled. But, I didn't to be coding each button to enable each of the buttons, I though.. why wouldn't be better to say to the frame to be disable, so all inside would be disable.
So instead of going for each button, I return to my properties and enabled them again, but I disable my frame, so this made the same way, but only with 1 click .
But I got a problem, when I click a button I want my frame get enabled so I code:
frame01.enabled = True

(This enabled all my buttons..)
But I only want 1 button Disable, in this case:
opt_mtto.enabled = false

so my code is:
frame01.enabled = true
opt_mtto.enabled = false

and this get me an error: 2101: "The setting you entered isn't valid for this property".
So I made this the other way, I enabled my frame, and then call the option button to be disable, and it works...
I only want to know why, I can't do this, the first way I mention.
I repeat is:

*

*When Form_Load the property are already set to the frame as False (no CODE, is set manually, in properties)

*When click button, enable Frame,

*Just after of enable the frame, disable one of the buttons inside.

*ERROR...

Why

A: Solution:
The frame was getting focus before disabled the button.
You can't disable controls if they are focus, this wasn't the same case, because the focus was on the frame, not in the button, but it happened the same way, I just needed to re-focus in other place.


text:
Q: What is the group structure behind quark color charge? Suppose you take the free $\mathbb Z$-module with two generators $\{P,N\}$ and quotient out by the relation $P+N = 0$. You get a one-dimensional module that has two additively independent elements $P$ and $-P$. By additive independence I mean you cannot write any one element as a linear combination of the others with positive coefficients.
The two independent elements correspond to the two types of electromagnetic charge, positive and negative.
If instead we start with three generators $\{R,B,G\}$ and quotient out by $R+B+G$ we get a structure that models the three types of color charge and their negatives for quarks. Like everyone knows, each quark can have red, blue, green, antired, antiblue, or antigreen charge. But they only occur in pairs of three, one of each color, which compose a particle with neutral color charge.
Here the elements $-R,-B,-G$ are the antired, antiblue, and antigreen charges. The relation red + blue = antigreen comes out of the relation $R+B+G= 0$ when we subtract $G$ from both sides. This time there are six additively independent elements.
In general suppose we start with the module generated by $\{g_1,\ldots, g_n\}$ and quotient out by $g_1+\ldots+ g_n=0$. What is the additive dimension of the quotient module?


text:
Q: Generic type parameter marked as covariant with "out" keyword is not rendered correctly by doxygen I have an interface with a type parameter marked as covariant with the "out" keyword:
    public interface IMultiLineResponseParser<out TResponse>

This is rendered by doxygen into:
IMultiLineResponseParser< out out TResponse > Interface Template
The "out" keyword is rendered two times. Can I prevent this with some configuration setting or is this a bug?