text:
Q: Powershell parenthesis in pattern I need to search for a pattern in a file and change the value of the version. Here's the pattern :
[file: FileVersion("1.2.3.$VAR$")]

In my Powershell script, I have a variable with the Pattern inside :
$FileVersionPattern   = '[file: FileVersion("[0-9]*.[0-9]*.[0-9]*.$VAR$")]'

(Get-Content "$filePath")    -replace($FileVersionPattern, ('[file: FileVersion("' + $Major + '.' + $Minor + '.' + $Release + '.$VAR$")]'))   | Set-Content  "$filePath"

So the return should be ($Major = 5 $Minor = 5 $Release = 5) :
[file: FileVersion("5.5.5.$VAR$")]

It seems that the $VAR$ and the parenthesis is causing my script to fail.


text:
Q: How to implement user-defined function from c in stan I am trying to use HMC to do MCMC sampling with a self-defined target function. I had my HMC code, but it doesn't work well. I recently knew "stan" which has a more powerful HMC model. So I want to implement my code with "stan".
I have already coded the target function as well as the derivative function in C. It involves for-loop, and functions needed for Cholesky decomposition and other linear algebras from Lapack. I really don't want to recode it in stan. Is there any way to use my functions directly? I would also appreciate it if anyone can give some clues about how to modify my code, or teach me how to modify "stan" code. The following is part of my code:
void get_V(double phi, double sigmasq, double k, double *neardist,
double *neardistM, int *nearind, double *w, int n, int m, double *V){

double one = 1.0, var;
int i, j, dim ,info, int_one = 1;
double *u, *temp_neardistM;
char UPLO = 'L';
char SIDE = 'L', DIAG = 'N';
char TRANS = 'N', TRANS2 = 'T';

var = (double)(1/k) * sigmasq;

V[0] = var;

for (i = 1; i < n ; i++){
    if(i < m) {
        dim = i;
    }
    else {
        dim = m;
    }

    ...

    // Cholesky decomposition of temp_neardistM
    info = -1;
    dpotrf_(&UPLO, &dim, temp_neardistM, &dim, &info);
    if (info != 0) {free(temp_neardistM); return ;}

    ...

    // get Vi
    dtrsm_(&SIDE, &UPLO, &TRANS, &DIAG, &dim, &int_one, &one, temp_neardistM, &dim, u, &dim);
    V[i] = (var - sigmasq * (sq_sum(u, dim)) );

    ...

    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django admin many to many recursive field widget shows identical objects I have a scheduling app with a backend managed via Django Admin. The Members table for managing people and their role includes two recursive fields that indicate whether a particular person has an employer (ForeignKey) or is associated with one or more customers (ManyToMany).
The problem is that when adding or editing a Member via Django Admin, the employer picklist and customers picklist display "Member object" for each row instead of the desired list of various company names.
Same problem in Python2.7.3 with Django1.7.1 and in Python3.4.3 with Django1.10.3.
# models.py
class Member(models.Model):
    first_name = models.CharField(max_length = 30)
    last_name = models.CharField(max_length = 30)

    role_choices = (
        ('Attendee', 'Attendee'),
        ('Customer', 'Customer'),
        ('Registrar', 'Registrar'),
          )

    now = timezone.now()

    role = models.CharField(choices=role_choices, max_length=50)
    created_date = models.DateTimeField(default=now)
    employer = models.ForeignKey('self', null=True, blank=True,
                     limit_choices_to={'role': "Customer"})
    customers = models.ManyToManyField('self', limit_choices_to=
        {'role': "Customer"}, related_name="registrar_customers",
        null=True, blank=True)
    company_name = models.CharField(max_length=100, null=True, blank=True)

    def __unicode__(self):
        if self.role == "Customer":
            name = self.company_name
        elif self.role == "Attendee":
            name = "{} - {}{}".format(self.employer.company_name,
                self.first_name, self.last_name)
        else:
            name = self.first_name + " " + self.last_name

        return name

# admin.py
class MemberAdminForm(forms.ModelForm):
    class Meta:
        model = Member

    # Form override to force company names into picklists
        customers = forms.MultipleChoiceField(required=False)

        def __init__(self, *args, **kwargs):
            super(MemberAdminForm, self).__init__(*args, **kwargs)
            cust_choices = ((obj.id, obj.company_name) for obj
                            in Member.objects.filter(role = 'Customer'))

            self.fields['employer'].choices = cust_choices
            self.fields['customers'].choices = cust_choices

        fields = ['first_name', 'last_name', 'role',
                    'created_date', 'employer', 'customers', 'company_name']

class MemberAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'role',
            'created_date', 'employer', 'company_name')

    form = MemberAdminForm

admin.site.register(Member, MemberAdmin)

A: Per https://docs.djangoproject.com/en/1.11/topics/python3/ the following code works properly. With thanks to Darius at Djangoproject for the solution.
# models.py

from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Member(models.Model):
    first_name = models.CharField(max_length = 30)
    last_name = models.CharField(max_length = 30)

    role_choices = (
        ('Attendee', 'Attendee'),
        ('Customer', 'Customer'),
        ('Registrar', 'Registrar'),
          )

    now = timezone.now()

    role = models.CharField(choices=role_choices, max_length=50)
    created_date = models.DateTimeField(default=now)
    employer = models.ForeignKey('self', null=True, blank=True,
                     limit_choices_to={'role': "Customer"})
    customers = models.ManyToManyField('self', limit_choices_to=
        {'role': "Customer"}, related_name="registrar_customers",
        null=True, blank=True)
    company_name = models.CharField(max_length=100, null=True, blank=True)

    def __str__(self):
        if self.role == "Customer":
            name = self.company_name
        elif self.role == "Attendee":
            name = "{} - {}{}".format(self.employer.company_name,
                self.first_name, self.last_name)
        else:
            name = self.first_name + " " + self.last_name

        return name


text:
Q: Aruco Marker World Coordinates I've been working with Python's OpenCV library, using ArUco for object tracking.
The goal is to get the x/y/z coordinates at the center of the ArUco marker, and the angle in relation to the calibrated camera.
I am able to display axes on the aruco marker with the code I have so far, but cannot find how to get x/y/z coordinates from the rotation and translation vectors (if that's even the right way to go about it).
This is the line of code which defines the rotation/translation vectors:
rvec, tvec, _ = aruco.estimatePoseSingleMarkers(corners, markerLength, camera_matrix, dist_coeffs) # For a single marker

Any ideas on how to get angle/marker position in the camera world?
Thanks!

A: After some tribulation, I found that the x and y coordinates in aruco can be determined by the average of the corners:
x = (corners[i-1][0][0][0] + corners[i-1][0][1][0] + corners[i-1][0][2][0] + corners[i-1][0][3][0]) / 4
y = (corners[i-1][0][0][1] + corners[i-1][0][1][1] + corners[i-1][0][2][1] + corners[i-1][0][3][1]) / 4

And the angle relative to the camera can be determined by the Rodrigues of the rotation vector, the matrix must be filled prior
rotM = np.zeros(shape=(3,3))
cv2.Rodrigues(rvec[i-1], rotM, jacobian = 0)

Finally, yaw pitch and roll can be obtained by taking the RQ Decompose of the rotation matrix
ypr = cv2.RQDecomp3x3(rotM)

A: As said by chungzuwalla, tvec represents the position of marker center in camera coordinate system and it doesn't change with the rotation of marker at a position. If you want to know about location of corners in camera coordinate system then one needs both rvec and tvec.
Here is a perfect explanation
Aruco markers with openCv, get the 3d corner coordinates?


text:
Q: how to retrieve data from database in struts 2 I want to display one of the data tables in my JSP page. My problem is that I have a form that is I have an action sending me to the JSP page I want to display my table in. I thought I would use another action to connect to the database and obtain all my information, but I'm not sure if that makes sense anymore, should I just use the same action?
Here are bits of my code:
Action to get the data:
import RegisterDao.*;

public class ProductAction {

    private String name,price,godown,product_type, description ;
    private int product_id;

    public int getProduct_id() {
        return product_id;
    }

    public void setProduct_id(int product_id) {
        this.product_id = product_id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGodown() {
        return godown;
    }

    public void setGodown(String godown) {
        this.godown = godown;
    }

    public String getProduct_type() {
        return product_type;
    }

    public void setProduct_type(String product_type) {
        this.product_type = product_type;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

JSP page:
<%@ taglib uri="/struts-tags" prefix="s" %>

            Product Id
            Godown
            Name
            Product Type
            MRP
            Description

        <s:iterator value="list">

            <s:property value="product_id"/>
            <s:property value="name"/>
            <s:property value="price"/>
            <s:property value="godown"/>
            <s:property value="product_type"></s:property>
            <s:property value="description"></s:property>

        </s:iterator>

Struts.xml:

<package name="default" extends="struts-default,json-default">
    <action name="product"  class="Action.ProductAction">
        <result type="json">
            <param name="excludeNullProperties">true</param>
            <param name="noCache">true</param>
        </result>
    </action>
</package>


text:
Q: Select columns as rows select * from emp14;

Output:
EMPLOYEE_ID FIRST_NAME  LAST_NAME   EMAIL
100          Steven            King         SKING

I want to display the output in column wise as follows:
EMPLOYEE_ID  100
FIRST_NAME   Steven
LAST_NAME    King
EMAIL        SKING

A: Try this
SELECT col, val
FROM
(
  SELECT to_char(EMPLOYEE_ID) AS EMPLOYEE_ID,FIRST_NAME,LAST_NAME, EMAIL FROM emp14
)t
UNPIVOT INCLUDE NULLS
(
  VAL FOR col IN (EMPLOYEE_ID,FIRST_NAME,LAST_NAME, EMAIL)
);

SQL FIDDLE DEMO

A: It appears you want each column displayed on a separate line.  The results of running a SELECT statement will be displayed in whatever manner the particular tool used to run the query chooses.  If you really want each column displayed on a separate line you can use a little PL/SQL:
BEGIN
  FOR aRow IN (SELECT * FROM EMP14) LOOP
    DBMS_OUTPUT.PUT_LINE('EMPLOYEE_ID  ' || aRow.EMPLOYEE_ID);
    DBMS_OUTPUT.PUT_LINE('FIRST_NAME   ' || aRow.FIRST_NAME);
    DBMS_OUTPUT.PUT_LINE('LAST_NAME    ' || aRow.LAST_NAME);
    DBMS_OUTPUT.PUT_LINE('EMAIL        ' || aRow.EMAIL);
  END LOOP;
END;

Share and enjoy.

A: Another approach:
-- this type is going to contain value's name and the value itself
SQL> create type t_data is object(
  2    col1 varchar2(31),
  3    col2 varchar2(31)
  4  );
  5  /

Type created

SQL> create type t_table is table of t_data;
  2  /

Type created

After that, the query can be constructed the following way:
-- sample of data from the question + some extra  data
-- just for the sake of demonstration.
SQL> with t1(EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL) as
  2  (  select 100, 'Steven', 'King', 'SKING' from dual union all
  3     select 101, 'Steven1', 'King1', 'SKING1' from dual
  4   )
  5  select col1
  6       , col2
  7    from t1 t
  8    cross join table(
  9                     t_table( t_data('Employee_id', t.employee_id)
 10                             , t_data('First_name', t.first_name)
 11                             , t_data('Last_Name' , t.last_name)
 12                             , t_data('e-mail'    , t.email)
 13                             )
 14                     )
 15  ;

Result:
COL1                            COL2
------------------------------- -------------------------------
Employee_id                     100
First_name                      Steven
Last_Name                       King
e-mail                          SKING
Employee_id                     101
First_name                      Steven1
Last_Name                       King1
e-mail                          SKING1

8 rows selected

A: select concat('EMPLOYEE_ID ', EMPLOYEE_ID) as EMPLOYEE_ID,
       concat( 'FIRST_NAME ' ,   FIRST_NAME) as FIRST_NAME,
       concat('LAST_NAME ' ,  LAST_NAME) as LAST_NAME,
       concat('EMAIL ' , EMAIL)  as EMAIL
from email


text:
Q: How to export selected columns of list in react admin? I have a list view in react admin.
I want to export the data that this list view contains with the export button.
However, I don't want to include one of the columns in the exported file.
Is there a way to customise the columns that you want to export in react admin?

A: Yes, you can pass a custom component to the exporter prop on your List
(React-Admin docs) https://marmelab.com/react-admin/List.html#exporter


text:
Q: How I got this answer Well i am new to this forum but old to stack exchange but i don't know much about mathmatics tags so sorry for the wrong tags if any.
I have a question, but i want to know how i got its answer as 'D'

Aslam has $4$ times as many books as Salman and $5$ times as many as Javed. If Javed has more than $40$ books, what is the least number of books that Aslam could have?

(A) $200$
(B) $205$
(C) $210$
(D) $220$
(E) $24$
Answer: $(D)$
Well I don't know how the answer is '$220$'. I am new to this field as well but according to me its answer should be $200$. Any ideas?
Thanks...

A: Since Javes has more than $40$ books, he has at least $41$ books. Thus, Aslam has at least $5\cdot 41=205$ books. Since his number of books is a multiple of $4$ and $5$, it is a multiple of $20$. Thus, he has at least $220$ books.
Say that $a$ is the number of books Aslam has. We know that $4|a$ ($4$ divides $a$) and that $5|a$. In general, if $k|x$ and $l|x$, it follows that $\text{lcm}(k,l)|x$, where $\text{lcm}(k,l)$ is the least common multiple of $k$ and $l$. Since the smallest number that is a multiple of both $4$ and $5$ is $20$, it follows that $20|a$.


text:
Q: Elasticsearch GeoMapping with PHP not working I have the following mapping in Elasticsearch 2.2
  "clinics" : {
    "mappings" : {
      "clinic" : {
        "properties" : {
          "address_1" : {
            "type" : "string",
            "analyzer" : "standard"
          },
          "city" : {
            "type" : "string"
          },
          "country" : {
            "type" : "string"
          },
          "id" : {
            "type" : "long"
          },
          "location" : {
            "type" : "geo_point"
          },
          "name" : {
            "type" : "string",
            "analyzer" : "standard"
          },
          "state" : {
            "type" : "string"
          },
          "zipcode" : {
            "type" : "string",
            "analyzer" : "standard"
          }
        }
      }
    }
  },

I am using PHP to add to the index with Elastiquent5. my toArray() is:
public function toArray()
{
    $array = parent::toArray();
    $object = new \stdClass();
    $object->lat = $array['latitude'];
    $object->lon = $array['longitude'];
    $array['location'] = $object;
    return $array;
}

When I try to add the item to the index i get the following error:
{"error":{"root_cause":[{"type":"remote_transport_exception","reason":"[Solarman][10.0.2.15:9300][indices:data/write/index[p]]"}],"type":"illegal_argument_exception","reason":"[location] is defined as an object in mapping [clinics] but this name is already used for a field in other types"},"status":400}

In json format it yields correctly, in php array it is:
array:10 [
  "name" => "Clinic A"
  "address_1" => "123 Main St"
  "city" => "NY"
  "state" => "NY"
  "zipcode" => "11111"
  "country" => "US"
  "id" => 6968
  "location" => {#526
    +"lat": 45.2116373
    +"lon": -72.1891546
  }
]

If I manually json_encode this and use the curl -XPUT 'http://localhost:9200' -d ''
it goes through - however the PHP doesnt. Any idea where I went wrong?
clarification
My goal is to insert the coordinate that my model data is extracting to map to the location field inside the index since I already designed as a geo_point type as defined by my mapping
I do not want to designate a new field in order to solve this. Secondary note: as I mentioned doing a put with the json will yield successfully however not as a php object out with the php drivers for elastic search which yielded the error when it tried to create the document

A: As mentioned in the error message, [location] is defined as an object in mapping [clinics] but this name is already used for a field in properties. Changing the variable name like the following might work.
public function toArray()
{
    $array = parent::toArray();
    $object = new \stdClass();
    $object->lat = $array['latitude'];
    $object->lon = $array['longitude'];
    $array['location_ob'] = $object;
    return $array;
}


text:
Q: Select the correct input field Maybe I'm working for too long now but I can't figure this one out or maybe I dn't see it anymore ;)
I have multiple forms on one page. Within these forms there is an input field with + and - arrows to update the quantity.
The problem I'm facing is that I can't select the correct input field so when I update quantity in any input field then the script updates all fields instead of the one selected.
So what I have is this:
<form class="formProduct" name="form 1234" action=""/>
.... some fields.....

   <input type="text" name="quantity" value="1" />

      +
      -

</form>

<form class="formProduct" name="form 4321" action=""/>
.... some fields.....

   <input type="text" name="quantity" value="1" />

      +
      -

</form>

The Jquery
  function updateQuantity(way){

    var quantity = parseInt($('.quantity input').val());

    if (way == 'up'){
      if (quantity < 10){
        quantity++;
          } else {
          quantity = 10;
      }
    } else {
      if (quantity > 2){
        quantity--;
          } else {
          quantity = 2;
      }
    }

    $('.quantity input').val(quantity);
  }

I know I have to use one of the classes like "1234" and "4321" to select the correct input field. But I really can't get that to work. I constantly get an [ object object ] error.
Have I missed something?

A: place 'this' keyword in onclick function as a parameter and find closest input based on keyword

        <form class="formProduct" name="form 1234" action=""/>

           <input type="text" name="quantity" value="1" />

              +
              -

        </form>

        <form class="formProduct" name="form 4321" action=""/>

           <input type="text" name="quantity" value="1" />

              +
              -

        </form>

A: *

*Mixing inline JavaScript with jQuery isn't a great idea, try to avoid it.

*Your logic has a few flaws, and is targeting all input elements deriving from class .quantity.

*Always use a radix when using parseInt.

Modify HTML to make it cleaner:
<input type="text" name="quantity" value="1" />
... etc
+
-

Then just use the following:
$(".up, .down").click(function(e){
  e.preventDefault();
  var input = $(this).parent().prev("input");
  if(this.className === 'up') {
    input.val() < 10 ? input.val(parseInt(input.val(), 10) + 1) : input.val(10);
  }
  else {
    input.val() >= 1 ? input.val(parseInt(input.val(), 10) - 1) : input.val(0);
  }
});

jsFiddle here

A: Use jquery closest() to find nearest parent div and find the input element whose value has to be updated..
Ex:
    function updateQuantity(item,way){
        var nearest = $(item).closest('.quantity').find('input');
        var quantity = parseInt(nearest.val(),10);

        if (way == 'up'){
          if (quantity < 10){
            quantity++;
              } else {
              quantity = 10;
          }
        } else {
          if (quantity > 2){
            quantity--;
              } else {
              quantity = 2;
          }
        }
        nearest.val(quantity);
    }

see working demo jsfiddle


text:
Q: Can information relevance axioms be proved using probabilistic manipulations? Disclaimer: The question would be bit long, in order to present properly. I request the reader's patience.
I was going through the book Probabilistic Reasoning In Intelligent Systems by Judea Pearl. There, the author presents a set of axioms - equations 3.6(a) through 3.6(e) - which I will present later. These, the author claims, can be verified using basic probabilistic manipulation. I tried these proofs and it seems that they depend on vital assumptions, which are indirectly implied by the axioms themselves. I want to understand if something is wrong with my observation. I will present the short proofs one by one and point out the assumptions.
Decomposition
To prove $I(X,Z,Y∪W)⇒I(X,Z,Y)\text{  and  }I(X,Z,W)$
$P(x│y,w,z)=P(x│z)$
$⇒P(x│y,w,z)P(w│y,z)=P(x│z)P(w│y,z)$
$⇒P(x,w│y,z)=P(x│z)P(w│y,z)$
$⇒\sum_w{P(x,w|y,z)}=\sum_w{P(x|z)P(w|y,z)}$
$⇒P(x|y,z)=P(x|z)\sum_w{P(w|y,z)}=P(x|z)$
The important step here is taking $P(x|z)$ out of the summation w.r.t $w$. Does this step not assume that $P(x|z)$ is independent of the value of $w$? Similarly, in the attempt to prove $I(X,Z,W)$ the assumption, $P(x|z)$ independent of $y$, will be there. When we write the first line $P(x│y,w,z)=P(x|z)$ we are already assuming that $P(x|z)$ is independent of $y$ and $w$, taken together or individually.
Weak union
To prove $I(X,Z,Y∪W)⇒I(X,Z∪Y,W)$
$P(x│(y,w),z)=P(x│z)$ …….the parenthesis around $y,w$ is to differentiate the fixed knowledge-base $z$ from the additional knowledge $(y,w)$ whose impact we are evaluating – no impact here as $I(X,Z,Y∪W)$.
$⇒P(x│w,(y,z) )=P(x|z)$………probability of $x$ when $z$ is fixed knowledge-base and $y,w$ is additional knowledge is the same as when $y,z$ is fixed knowledge-base and $w$ is additional knowledge.
$⇒P(x│w,(y,z) )=P(x│y,z)$……..because $I(X,Z,Y∪W)⇒I(X,Z,Y)$ by decomposition.
Hence $I(X,Z∪Y,W)$.
The statement given beside the second step – "probability of $x$ when $z$ is fixed knowledge-base and $y,w$ is additional knowledge is the same as when $y,z$ is fixed knowledge-base and $w$ is additional knowledge" - is something that is an inherent property of the way we deal with conditional probabilities; it is sort of like the associative rule of algebraic addition or multiplication. That such an increment in the fixed knowledge-base would not change relevance status of $W$, uses the independence of $Y$ (a by-product of decomposition rule which we already showed to be a fundamental assumption in conditional probability manipulations).
Contraction
To prove $I(X,Z,Y)\text{ and }I(X,Z∪Y,W)⇒I(X,Z,W)$
$P(x│y,z)=P(x|z)$ …………because $I(X,Z,Y)$ given.
$P(x│w,(y,z))=P(x|y,z)$ ……………because $I(X,Z∪Y,W)$ given
Therefore,
$P(x│w,(y,z) )=P(x│z)$
$⇒P(x│(w,y),z)=P(x|z)$…………i.e., probability when $y,z$ is fixed knowledge-base and $w$ is additional knowledge is the same as when $z$ is fixed knowledge-base and $w,y$ is additional knowledge. This is a contraction of the fixed knowledge-base and just opposite to what was shown in weak union.
$⇒I(X,Z,Y∪W)⇒I(X,Z,W)$
Thus, the movement of knowledge elements from fixed knowledge-base to additional knowledge bucket is something that is assumed to be allowed in conditional probability manipulations. Added to this the independence assumptions - $I(X,Z,Y)$  and $I(X,Z∪Y,W)$ - gives us the result $I(X,Z,W)$.
Intersection
In the proof of intersection, I could not see any particular aspect that was not already covered under decomposition, weak union and contraction. Below is the proof for reference –
To prove $I(X,Z∪Y,W)\text{ and }I(X,Z∪W,Y)⇒I(X,Z,Y∪W)$
$I(X,Z∪Y,W)$
$⇒P(x│w,(y,z) )=P(x│y,z)$
$⇒P(x│(w,y),z)=P(x│y,z)$………………$(i)$
$I(X,Z∪W,Y)$
$⇒P(x│y,(w,z) )=P(x│w,z)$
$⇒P(x│(y,w),z)= P(x│w,z)$…………………….$(ii)$
Therefore,
$P(x│y,z)=P(x│w,z)$
$⇒P(x│y,z)P(w│z)=P(x│z,w)P(w│z)$
$⇒\sum_w{P(x│y,z)P(w│z)}=\sum_w{P(x│z,w)P(w│z)}$
$⇒P(x│y,z)=P(x│z)$
$⇒I(X,Z,Y)$
$I(X,Z,Y)\text{ and }I(X,Z∪Y,W)⇒I(X,Z,Y∪W)$ by contraction.
Hence, is it not true that, these axioms, rather than being proven, are supposed to be assumed true for the way we expect conditional probabilities to behave?


text:
Q: Can you keep the 0s when parsing a string from an int? c# I'm making a 2d array of buttons, and want its tag to be its array position, including the starting 0s and ending 0s (e.g 01 or 2002)... is this possible?
Button[,] buttonGrid = new Button[11, 21];

Button gridButton = new Button
{
    Tag = int.Parse(yIndex.ToString() + xIndex.ToString()),
    BackColor = Color.LightGray,
    Enabled = true,
    Size = new Size(size, size),
    Location = new Point(25, 25)
};

I used a for loop to loop through each element in the array thats where the x and y index come from.
this will return 1,2,3 - 9 in the first row then 10, 11, 12, so on. but I want it to be 01, 02, 03 or 020.

A: You should probably not rely on string concatenation to create the tags. since you have no idea if "111" means x=1, y=11 or x=11, y=1 Tags are used internally to distinguish UI objects. Normally when converting two coordinates to a single index you would do a calculation like
var i = yIndex * width + xIndex;

and this can be reversed:
var yIndex = i / width;
var xIndex = i - yIndex * width;

If you want the number to be in the format XXYY, then you can simply use 100 as the width. If you want to convert this to a text-label you can use a format specifier when converting it to string, i.e. i.ToString("0000")

A: If you need preceding zeros in your int, I would suggest you keep the position as a string. When you need to calculate it, just convert it to int temporarily and perform the calculations. You can assign anything in the Tag.


text:
Q: Loading fsx files dynamically in an FSX script We are sharing a build script for FAKE across a set of projects. We want to keep this one build script the same but make it possible to extend with other targets. One way I could think of doing this is by loading .fsx files if they fit a specific naming pattern like al files that matches build-*.fsx however I can't seem to think of a way to load these files dynamically. Any suggestions on how to do this or how to accomplish the desired result are all good as answers
if I could I would have done something like
#load "build-*.fsx"

A: It's not completely clear to me why you want to do this but maybe this will help. Refer to a single script in each project:
#load "load-build-scripts.fsx"

And then in single load-build-scripts.fsx:
#load "build-1.fsx"
#load "build-2.fsx"
#load "build-3.fsx"
...

This second file you will need to change whenever you add a new script.

It's not generally recommended to do this. Because now if these separate scripts refer to each other then some scripts will be loaded more than once. Scripts aren't really meant to be used for cases this complex.
Another option is to use FAKE as a console project instead of using scripts and the fake-cli tool. Then you can use normal .NET project dependencies.


text:
Q: What is the simplest way to make scheduled XML parsing into an SQL database? So, ok, I'm using PHP for my website, and suppose I know quite a bit of MySQL and a little bit of MS SQL.
Now, I want to parse some XML with PHP/USD exchange rate and store it in the database.
The simplest way one could think of would be, perhaps this:
$XMLContent=file("http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency=PHP");

foreach($XMLContent as $line){
$a=&strip_tags($line);
if (is_numeric($a))
{
    // output the exchange rate
    echo $a;
    // THen I would probably go like this:
    mssql_query('update table set xchange_rate='.(float)floatval($a));
    // break cycle once found;
    break;
}
}

That would perfectly do... if it didn't take 0.8 seconds to run this script, due to external XML GET request.
So I suppose I should use Windows Scheduler, and make a task to run, let's say every hour to update the records. Now the question is, I've no idea what script I would use. I mean, I can't just simply run browser with a PHP script - that would be rediculous.
So, what would be the easiest way to make a script/ application to run it outside PHP, without a need to actually open a browser.
Thanks!
EDIT
Good point, right now I'm testing it on Win7, but later it is going to be implemented on Windows Server (2008?).

A: php has a binary executable interpretor too. On win, its called php.exe
http://php.net/manual/en/features.commandline.php
get it working first from a shell prompt, then make a scheduled task for it.
keep in mind, it is not the same php as you get when running a script through a webserver. Some settings are different, and the version may be different, and may use a different php.ini file(and so may have different extensions loaded).
consider using absolute file paths to start until you get things working.

A: You don't need a browser to run a PHP script.  PHP can happily run as a console application.  Without knowing what system you're deploying this on (i.e. which OS), it's hard to give you more directions. For example, on a unix-like system (UN*X, linux, OS X, etc.) you can create your PHP file:
somefile.php
<?php

.....

?>

save this file into some pre-defined directory, for example, /opt/myproject and then schedule it in /etc/crontab (assuming your php is installed in /usr/bin):
7 * * * *    /usr/bin/php /opt/myproject/somefile.php

This would run your script with PHP, without any browser, once an hour, at 7 minutes past each hour.
EDIT If you're to deploy this on a windows server, you can either use at command on the command prompt or use the Task Scheduler snap-in in Server Manager to configure your job.  The PHP script would be saved where you like it to be (e.g. D:\Projects\MyProject\myfile.php) and the command you would schedule to run would be C:\WAMP\bin\php.exe - or whereve your php.exe is located).


text:
Q: Issue with Zalando Postgres operator configuration for logical backup The vaule-crd.yaml has the pod_environment_configmap option which injects a configmap data into every database pod as environment variables.
Does this option also work for all cron jobs managed by the operator?
For now, I have to hardcode the S3 credentials in configLogicalBackup section, like logical_backup_s3_access_key_id, logical_backup_s3_secret_access_key. Do the logical backup pods share the environments defined in pod_environment_configmap?


text:
Q: Erlang wxWidgets app - Closing the beam.smp file once app finished got a weird question which I haven't been able to find an answer to online so I'm trying my luck here.
I have a normal erlang application using wxWidgets, once I try to shut down my application I get the event that the wxServer has indeed entered the event which is connected to the window closing, I get a message that it is in the process of exiting, and my window does indeed close, but as shown in the picture below, the beam.smp on my toolbar doesn't close at all, I have to manually force the closing of the beam.smp file which sends a SIGTERM to the erlang terminal which also shuts down my erlang VM (which I have to reboot it later).
long story short, what am I missing on my close window event so that everything shuts down nicely without it crashing my erlang VM? I was able to read that wxWidgets behaves differently on macOS but I haven't been able to find how to correctly close the application.
handle_event(#wx{event = #wxClose{}},State = #state{frame = Frame,panel = Panel}) ->
  io:format("Exiting~n"),
  wxFrame:close(Frame),
  wxFrame:destroy(Frame),
  wx:destroy(),
  {stop,normal,State};

A: You can close the emulator from code with init:stop/0,1
Also, if your application is started as permanent, it should suffice with terminating that application. Check the behaviour in erlang:application


text:
Q: How to create a new Rails application from existing source code I've been tasked to get a Ruby-on-Rails application working on a dev machine. We have the actual source code (after generation) on a DVD.
I've installed Ruby and Rails, and confirmed both to work. I've copied the source code into C:\Sites.
I'm completely new to the whole stack and googling has given me no help.
Update: took the equivalent of a working day spread over two days. thanks for the answer. got it done in the end. o_O

A: If you already have the code than fire following commands and you are ready to go
cd "your project"
bundle install
rake db:migrate
rails server

and goto http://localhost:3000


text:
Q: Transform glTF skeleton So there is this website, that I try to understand better, that's using three.js. It loads a skeleton of an Object and how to transform it, and then applies it. I'm trying to understand how the numbers work.
The skeleton looks like this:
     ... {
     "matrix":[
        0.17487109608203796,
        0.9808429390531989,
        0.08583256179649638,
        0,
        -0.9845913364208861,
        0.17420535149137226,
        0.015244532026296892,
        0,
        6.245004513516506e-17,
        -0.08717582475233696,
        0.9961929409400319,
        0,
        -17.293407120040825,
        -7.498166526363107,
        -3.414154659862163,
        1
     ],
     "name":"skirtLS_R0_0_jnt",
     "children":[
        216
     ]
  }, ...

and the transform data looks like this:
"skirtLS_R0_0_jnt":{
"rx":-0.46968024327475905,
"ry":0.6625494135134524,
"rz":0.8307740847876909,
"sx":1,
"sy":1,
"sz":1,
"tx":-19.287387631947865,
"ty":-4.734764859948513,
"tz":-3.072137856350322,
"name":"skirtLS_R0_0_jnt",
"parent":null
},

so the Skeleton contains the default ("T-Pose") Skeleton of that object and the transform data gives the object its specific pose.
My guess is that rx, ry and rz are for rotation, tx, ty, tz for translation and sx, sy, sz for scale.
But I don't know how to verify my guesses and how to apply rx - sz onto the gltf file.


text:
Q: Cant Get Input.GetButton("Jump") I am making a FPS game in Unity. I followed a tutorial by Brackeys to create FPS movement in your game. I have all the movement working fine (forward, back, left/right), but for some reason the part of the code that involves jumping is not working. I googled different ways to get the input of the space bar, but none have worked.
Here is my code
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

    public CharacterController controller;
    public float speed = 12f;
    public float gravity = -9.81f;
    public float jumpHeight = 3f;

    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;

    Vector3 velocity;
    bool isGrounded;

    // Update is called once per frame
    void Update()
    {

        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if(isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;

        controller.Move(move * speed * Time.deltaTime);

        if(Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
    }
}

Hope anyone can help!
:)


text:
Q: Unable to retrieve point where i rendered listview but still in button click event I am  having a listview which has header as button and ( 3 textboxes as row in listview)
Now i want to render the row when i click on button.
So i made an adapter which renders the data in textboxes, now my onCreate() method initially renders the button, then i have button click event in onCreate() so that when i click, it again renders the data in textboxes .
It is doing fine, but i want the data to be flipped with some other data , so i want a position where button renders the listview but do not get out of the click event.
But i am unable to get that point
The point where myviewholder will get the value so that i can change it, that point makes me irritate, its been whole night i am unable to figure out where.
my main activity onclick()
onheadbutton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub

                    int t = randInt(2, 3);

                    ItemBean bean = new ItemBean();

                    bean.setTitle1(Integer.toString(randInt(2, 10)));
                    // bean.setId("1");
                    t--;

                    bean.setTitle2(Integer.toString(randInt(2, 10)));
                    t--;

                    if (t != 0) {
                        bean.setTitle3(Integer.toString(randInt(2, 10)));
                        t--;
                    }
                    if (t != 0) {

                    itemList.add(0, bean);

                    adapter = new ListViewCustomAdapter(MainActivity.this,
                            itemList);

                    listviewwithbutton.setAdapter(adapter);

                }

            });

my adapter
public class ListViewCustomAdapter extends BaseAdapter {

    ArrayList<Object> itemList;
    public ViewHolder holder0;

    public Activity context;
    public LayoutInflater inflater;

    public ListViewCustomAdapter(Activity context, ArrayList<Object> itemList) {
        super();

        this.context = context;
        this.itemList = itemList;

        this.inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return itemList.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return itemList.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.simplerow, null);

            /*
             * holder.imgViewLogo = (ImageView) convertView
             * .findViewById(R.id.imgViewLogo);
             */
            holder.txtViewTitle1 = (TextView) convertView
                    .findViewById(R.id.textView1);

            holder.txtViewTitle2 = (TextView) convertView
                    .findViewById(R.id.textView2);
            holder.txtViewTitle3 = (TextView) convertView
                    .findViewById(R.id.textView3);

            convertView.setTag(holder);
        } else
            holder = (ViewHolder) convertView.getTag();

        ItemBean bean = (ItemBean) itemList.get(position);

        holder.txtViewTitle1.setText(bean.getTitle1());
        holder.txtViewTitle2.setText(bean.getTitle2());
        holder.txtViewTitle3.setText(bean.getTitle3());

        return convertView;

    }

}

A: If I am understanding your question correctly:

i want a position where button renders the listview but do not get out of the click event. But i am unable to get that point

So you are saying you want to have something execute while the button is maintaining a clicked state and then have something else happen ("the data to be flipped with some other data") upon exiting the click event?
If so, I would set an OnTouchListener on the button rather than an OnClickListener, since that will supply your callbacks with a MotionEvent.
So you could have:
onheadbutton.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // Do some stuff while in the clicked state
                return true;
            case MotionEvent.ACTION_UP:
                // Do some other stuff while exiting the clicked state
                return true;
            default:
                return false;
            }
        }

    });


text:
Q: Navigate URLs using WebBrowser DocumentCompleted This is the scenario
1-Navigate to admin page.
2-Enter username and password
3-Navigate to new page
4-Fill some text in textareas etc and post .
5-Repeat Step 3 and 4 until loop ends
The Code Below successfully does step 1 and 2. But it reaches step 3 before new page is loaded and generates the error "Object reference not set to an instance of an object" on this line doc.GetElementById("title").SetAttribute("value", "check1");
I am trying to achieve this from last 3 days but can't reached step 3 until now. Any help will be appreciated
bool AdminPagework  =false;
bool postnavigationdone =false;
public Form1()
    {
        InitializeComponent();
        webBrowser1.DocumentCompleted +=
  new WebBrowserDocumentCompletedEventHandler(AdminPageCredentials);
        webBrowser1.Navigate("www.website.com/admin");

    }
    private void AdminPageCredentials(object sender, WebBrowserDocumentCompletedEventArgs e)
    {

        if (AdminPagework == false && (webBrowser1.ReadyState ==        WebBrowserReadyState.Complete))
        {
            HtmlDocument doc = webBrowser1.Document;
            doc.GetElementById("login").SetAttribute("value", "ADMIN");
            doc.GetElementById("pass").SetAttribute("value", "123");
            doc.GetElementById("submit").InvokeMember("click");

            AdminPagework = true;

           webBrowser1.DocumentCompleted +=
      new WebBrowserDocumentCompletedEventHandler(RedirectToPostPage);

            webBrowser1.Navigate("http://www.website.com/admin/post.php");
        }

    }
    public void RedirectToPostPage(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        if ((postnavigationdone == false)  && (webBrowser1.ReadyState == WebBrowserReadyState.Complete))

        {
            HtmlDocument doc = webBrowser1.Document;
            doc.GetElementById("title").SetAttribute("value", "check1");
            doc.GetElementById("content").SetAttribute("value", textBox2.Text);
            doc.GetElementById("post-format-video").InvokeMember("click");
            doc.GetElementById("in-category-64").InvokeMember("click");
            webBrowser1.Document.GetElementById("mm").SetAttribute("value", "01");
            webBrowser1.Document.GetElementById("jj").SetAttribute("value", "01");
            webBrowser1.Document.GetElementById("aa").SetAttribute("value", "2013");
            webBrowser1.Document.GetElementById("hh").SetAttribute("value", "01");
            webBrowser1.Document.GetElementById("mm").SetAttribute("value", "01");

            doc.GetElementById("publish").InvokeMember("click");

            postnavigationdone = true;
        }
    }

A: var titleElement = doc.GetElementById("title");
titleElement.SetAttribute("value","check1");

Try that and see if the title element is found after all, since the most likely reason it fails is: There is no element with the name "title".
I like using ScrapySharp framework (you'll find it on NuGet) for web automation.
var titleNodes = doc.DocumentNode.CssSelect("div#title").ToList();
foreach(var titleNode in titleNodes)
{
   titleNode.SetAttribute("value","check1");
}

btw. why would you do that anyway, changing this attribute? Just curious...


text:
Q: HTML Pagination for Editable Docs I want to write a HTML application which has a div
contenteditable=true
height: 200px;
width: 200px;
word-wrap: break-word;

While the user is typing content in this div, and he runs out of space (height) - i want the content should move to the next div (another div below this one)
How can this be achieved? I could listen to events on the div and keep checking the height (whether it has grown above 200px), and then what?
I could find many solutions for non-editable documents, but none for my problem.
Any pointers appreciated. Thanks.

A: You can check the height of the content of your div, and if it's overflow a certain height, move the content in another div.
To do that, you have to use some javascript, which will check the content size at every keydown() and create your new divs if the content is too big for your div. The key here is to listen and execute this scenario at each keydown :

*

*Check if the height of the content is bigger than 200px

*If it's true, create a new div and put the content in it

*Append a new item to the pagination (and possibly a way to show the div created)

*Clean the editable div

Be careful that your user doesn't lost inputs (one or two key inputs for example) during this process...


text:
Q: Apache gettext - cache persisting after restart Running apache2 through Plesk. When I update the .mo files via subversion, and then restart apache (either through commandline or through Plesk interface), the translations do not update. Modified timestamps on the files are correct.
Is there any way to manually reset the cache?
Thanks!

A: Turns out it wasn't a caching problem.
I had two languages en_US and de_DE. Gettext was only showing the key and not the translation for en_US, which wasn't noticeable because the keys are in English anyway.
So gettext was working for one language, and not for another...
Solution:

*

*Add the en_US.UTF-8 locale using locale-gen en_US.UTF-8 (I'm on ubuntu).

*Restart apache.

(You can check which locales are installed using locale -a.)


text:
Q: MultichoiceField in ModelForm for Django with DB relations This is my first post ever on Stackoverflow so please ignore mistakes. Before posting I had tried a dozen solutions bun none worked. I have table relations in models for users. I need to create a ModelForm to let customer select multiple users for any project from the frontend. I am having hard time implementing it in code. Also for another field I need to limit the choice to one user. Following is the code.
Models:
class Project(models.Model):
   project_name = models.CharField(max_length=100)
   assigned_to = models.ManyToManyField(User)
   project_url = models.URLField()

def __init__(self):
    return str(self.project_name)

Form.
class ProjectForm(forms.ModelForm)
     class Meta:
       fields = ['project_name', 'assigned_to ', 'project_url']

View:
def projects(request):
   template = 'projects/projects.html'
   if request.method == 'POST':
       form = ProjectForm(request.POST)
       if form.is_valid():
         form.save()
   else:
     form = ProjectForm()
   return render(request, template, {'form': form})

HTML:
<form action='' method='post'>
 {% csrf_token %}
 {{ form }}
 <button type='submit' class='btn btn-primary'>Submit</button>
 </form>

Some help is highly appreciated.

A: forms.py:
from django import forms
from .models import Project
class ProjectForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        assigned_users = kwargs.pop('assigned_to', [])
        super(ProjectForm, self).__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs = {"class": "form-control"}
        self.fields['project_name'].required = True
        self.fields['project_url'].required = True

        if assigned_users:
            self.fields['assigned_to'].queryset = assigned_users
        self.fields['assigned_to'].required = True

        self.fields['project_name'].widget.attrs.update({
            'placeholder': 'Project Name'})
        self.fields['project_url'].widget.attrs.update({
            'placeholder': 'Project URL'})
    class Meta:
        model = Project
        fields = ('project_name', 'project_url', 'assigned_to')

views.py
def create_project(request):
    template_name = "create.html"
    users = []

    form = ProjectForm(assigned_to=users)

    if request.method == 'POST':
        form = ProjectForm(request.POST, request.FILES, assigned_to=users)
        if form.is_valid():
            proj_obj = form.save(commit=False)
            proj_obj.created_by = request.user
            proj_obj.save()

            if request.POST.getlist('assigned_to', []):
                proj_obj.assigned_to.add(*request.POST.getlist('assigned_to'))
                assigned_to_list = request.POST.getlist('assigned_to')
            success_url = reverse('projects:list')
            if request.POST.get("savenewform"):
                success_url = reverse("leads:add_lead")
            return JsonResponse({'error': False, 'success_url': success_url})
        return JsonResponse({'error': True, 'errors': form.errors})
    context = {}
    context["proj_form"] = form
    context["users"] = users

    context["assignedto_list"] = [
        int(i) for i in request.POST.getlist('assigned_to', []) if i]

    return render(request, template_name, context)

create.html:
<div class="form-control">
    {{ proj_form.project_name }}
    {{ proj_form.assigned_to }}
    {{ proj_form.project_url }}

</div>


text:
Q: Android How to refresh items in ExpandableListView SQLController dbcon;
@Override
public View getChildView(int groupPosition, final int childPosition,
                     boolean isLastChild, View convertView, ViewGroup parent) {
final String children = (String) getChild(groupPosition, childPosition);
TextView text;
if (convertView == null) {
    convertView = inflater.inflate(R.layout.listrow_details, null);
}
text = (TextView) convertView.findViewById(R.id.textView1);
text.setText(children);
convertView.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(activity, children,Toast.LENGTH_SHORT).show();
    }
});

convertView.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View view) {

        AlertDialog.Builder Delete=new AlertDialog.Builder(activity);
        Delete.setTitle("Show Linups Or Delete");
        Delete.setMessage("Press Delete For Remove "+children+" or Press Show Lineups to get Lineups.");
        Delete.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
               dbcon=new SQLController(activity);
                dbcon.open();
                Cursor c=dbcon.returnData();
                if(c.moveToFirst())
                {
                    do{
                        if(children.equals(c.getString(0))){
                            dbcon.deleteData(children);
                            notifyDataSetChanged();
                            Toast.makeText(activity,"Successfully Deleted",Toast.LENGTH_LONG).show();
                            break;
                        }
                    }while(c.moveToNext());
                }
                dbcon.close();
            }
        }).show();
        return false;
    }
});
return convertView;
}

This is my Expandable list adapter's getChildView Method, I am using Sqlite database and I store data to database and need to delete some items also so i use onLongClickListener for Deleting items, when I long click on the item I want to delete a popup appears having delete button, when I click on that button the item from database deleted but the item still appears on that activity until I reopen the application, what I want is when I click on delete button it should be disappear from that list also immediately, Thanks in Advance,

A: You need to update the adapter for the view. Most adapter have the notifyDataSetChanged() method, which updates the data set it is displaying


text:
Q: Passing many variables vs. passing struct When passing several pointers to a function, in terms of performance only:
is is better to pass a pointer to a struct with all the pointers inside and then do something like code 1 or passing the pointers to variables directly?
I think that for small number of variables, the option two outperforms option 1 for sure, but is that the case when we have, say, 100 variables?
I found some questions about this, but none very conclusive in terms of performance only.
What is better practise in high-performance computing: passing a struct of data into a function or a set of variables?
Efficiency of passing a struct to a function without instantiating a local variable
Declaring/passing structs vs. declaring/passing individual values
OPTION 1
void myFunctionOne(void *pointerToStruct){
    struct myTypeOfStruct *localPointerToStruct;
    localPointerToStruct = (struct myTypeOfStruct *)pointerToStruct;

    for(i=0;i<n;++i){
        *(localPointerToStruct->a+i) = sth;
        *(localPointerToStruct->b+i) = sthElse;
        ...
        *(localPointerToStruct->z+i) = sthElsez;
    }
}

OPTION 2
void myFunctionOne(double *a, double *b,...,double *z){
    for(i=0;i<n;++i){
        *(a+i) = sth;
        *(b+i) = sthElse;
        ...
        *(z+i) = sthElsex;
    }
}

OPTION 3
A third option that might seem a bit weird would be doing the first case but instead of iterating over the pointers inside the struct, copy them to local pointer variables.
void myFunctionOne(void *pointerToStruct){
    struct myTypeOfStruct *localPointerToStruct;
    localPointerToStruct = (struct myTypeOfStruct *)pointerToStruct;

        double *a = localPointerToStruct->a;
        double *b = localPointerToStruct->b;
        ...
        double *z = localPointerToStruct->z;

    for(i=0;i<n;++i){
        *(a+i) = sth;
        *(b+i) = sthElse;
        ...
        *(z+i) = sthElsex;
    }
}

A: It depends on the compiler which does a lot of background optimization and environment. Generally don't try to outsmart the compiler, but if you really, really need it make a test with some million calls to each of the options, in 3 different programs of course and after rebooting your pc after each test. Then you know for what it's worth what was more performant on that exact moment in time with your exact setup.

A: In general, use a struct to aggregate variables that belong together and pass a pointer to that struct to your functions. That will be the fastest way. But of course in that case, the function can modify the struct and those modifications will be reflected in the caller. You can obviate this using const.
But in general, trust the compiler to make the optimisations for you, and only worry about micro-optimising if that area of code has been identified as a bottleneck.

A: In order to evaluate the overall efficiency of the approach you need to consider the way the function call is made, because the efficiency of the first approach depends a great deal on where does the struct come from.
If you have to perform the same struct set-up before each call, the first approach becomes identical to the second approach, except now you are in charge of preparing the stack frame for the function.
If, on the other hand, you can set up your struct once, and then make multiple calls with it, you will end up with less copying.
For the sake of completeness, if you have to allocate your struct dynamically, the performance is going to be significantly worse.
One important advantage of the struct approach is maintenance. If you decide to add another field to a struct, you just add another field to the struct, and everything continues to compile. However, adding an extra parameter to a function would force you to revisit all places in code where you make the call, and add a new argument expression for the newly added parameter.
I would modify the first approach to take myTypeOfStruct instead of void*, because there is no point to hide parameter type. After all, the alternative passes arrays of double directly, without void* cast. I would also prefer array syntax to pointer manipulation:
void myFunctionOne(struct myTypeOfStruct *pointerToStruct){
    for(i=0;i<n;++i){
        pointerToStruct->a[i] = sth;
        pointerToStruct->b[i] = sthElse;
        ...
        pointerToStruct->z[i] = sthElsez;
    }
}

A: Performance (of arguments & results passing) depends upon the calling conventions and the ABI used by your C implementation.
BTW, an optimizing C compiler will often inline a function call (even for functions not declared inline, as long as it knows the definition of the called function). And some compilers are able of link-time optimizations (with a recent GCC, compile and link with gcc -flto -O2)
Notice that on Linux/x86-64 the ABI specification dictates that the first 6 scalar arguments are generally passed by registers, and that a result which is a struct of two scalars is passed thru two registers. This is generally much faster than passing thru memory (e.g. on the call stack).
At last, the CPU cache matters a lot for performance. So the only way to really know is to benchmark your application.


text:
Q: Open GL ES 2, matrix OrthoM and translation I have a problem with my translation and rotation .
When i want rotate like this it work
 http://i.stack.imgur.com/UyeOn.png
 textureProgram.useProgram();

for ( i =0; i < 5; i ++)
{
     Matrix.setLookAtM(modelMatrix, 0, 0, 0, 1.0f, 0.0f, 0f, 0f, 0f, 1.0f, 0.0f);
     Matrix.multiplyMM(modelViewProjectionMatrix, 0, projectionMatrix, 0, modelMatrix, 0);
     Matrix.setRotateM(RotationMatrix, 0, 12f, 0, 0,  1.0f);
     Matrix.multiplyMM( projectionMatrix, 0, modelViewProjectionMatrix, 0,    RotationMatrix,     0);
    textureProgram.setUniforms(projectionMatrix, mur1texture);
     this.bindData(textureProgram);
     glDrawArrays(GL_TRIANGLE_FAN, 0, 6);
     }

But i can't rotate more than my far number in my OrthoM projection i dont understand at all.
For instance if my number is 3 like this one:
     Matrix.orthoM(projectionMatrix, 0, 0, 1280, 800, 0, -1, 3);

i will be able to rotate it 3 times not more even if i have to rotate 5 times.
I have to increase the number to be able to rotate it 5 times for example.
Can someone help me please , i don't really understand the problem.
EDIT : with this, it rotate just one time and the object get distortion when it rotate .
http://i.stack.imgur.com/jEfID.png
      for ( i =0; i < 5; i ++)
    {
    Matrix.setLookAtM(modelMatrix, 0, 0, 0, 1.0f, 0.0f, 0f, 0f, 0f, 1.0f, 0.0f);
    Matrix.setRotateM(RotationMatrix, 0, 12f, 0, 0,  1.0f);
    Matrix.multiplyMM(modelMatrix, 0, modelMatrix, 0, RotationMatrix, 0);
    Matrix.multiplyMM(modelViewProjectionMatrix, 0, projectionMatrix, 0, modelMatrix, 0);

     textureProgram.setUniforms(modelViewProjectionMatrix, mur1texture);
     this.bindData(textureProgram);
     glDrawArrays(GL_TRIANGLE_FAN, 0, 6);

}

EDIT 2:
This way it rotate normally but just once :S .
  for ( i =0; i < 5; i ++)
   {
     Matrix.setLookAtM(modelMatrix, 0, 0, 0, 1.0f, 0.0f, 0f, 0f, 0f, 1.0f, 0.0f);
     Matrix.multiplyMM(modelViewProjectionMatrix, 0, projectionMatrix, 0, modelMatrix, 0);
     Matrix.setRotateM(RotationMatrix, 0, 45f, 0, 0,  1.0f);
     Matrix.multiplyMM(modelViewProjectionMatrix, 0,  projectionMatrix, 0,       RotationMatrix, 0);

     textureProgram.setUniforms(modelViewProjectionMatrix, mur1texture);
     this.bindData(textureProgram);
     glDrawArrays(GL_TRIANGLE_FAN, 0, 6);

}

Edit 3 : Still rotate only one time .
int u , i ;
textureProgram.useProgram();

Matrix.setLookAtM(modelmatrix, 0, 0, 0, 1.0f, 0.0f, 0f, 0f, 0f, 1.0f, 0.0f);
Matrix.multiplyMM(modelViewProjectionMatrix, 0, projectionMatrix, 0, modelmatrix, 0);

 for ( i =0; i < 5; i ++)
 {

      Matrix.setRotateM(RotationMatrix, 0, 12f, 0, 0,  1.0f);
      Matrix.multiplyMM( modelViewProjectionMatrix, 0, projectionMatrix, 0,RotationMatrix,     0);
     textureProgram.setUniforms(modelViewProjectionMatrix, mur1texture);
     this.bindData(textureProgram);
     glDrawArrays(GL_TRIANGLE_FAN, 0, 6);
    }


text:
Q: Different versions of Mercer's theorem I am reviewing materials on reproducing kernel Hilbert space (RKHS) and I've found various versions of Mercer's theorem:

*

*About the positive-definiteness conditions.
In the Wikipedia pages on RKHS above or on the theorem itself, the condition is
$$\sum_{i,j =1}^n c_i c_j K(x_i, x_j) \ge  0 , \forall  n \in \mathbb{N},\ x_1, \dots, x_n \in X,\ \mbox{and}\ c_1, \dots, c_n \in \mathbb{R},$$
while in some other materials (for example this, page 16), the condition becomes an integral:

In T. Hofmann et. al there is a short comment on this:

So according to the text they are different. Thus my first question is, what is the connection between these two conditions?

*About the function space of $K$.
Again in the Wikipedia pages on Mercer's theorem, it mentions that $K$ is a Hilbert–Schmidt integral operator, which is like saying $K\in\mathcal{L}^2(\mathcal{X}^2)$ if I understand correctly. But in the attached slide above, it requires $K\in\mathcal{L}^\infty(\mathcal{X}^2)$, and gives $(\lambda_j)\in\ell_1$. This conclusion seems not covered by the spectral theory of compact and self-adjoint operators on Hilbert space, which only states a weaker result $\lambda_j\to 0$. It looks to me that $K\in\mathcal{L}^\infty(\mathcal{X}^2)$ helps give $(\lambda_j)\in\ell_1$. So my second question is, what is the general requirement of the function space for $K$, and how will the choice of spaces affect the properties of $(\lambda_j)$?


text:
Q: Cannot post Json array to web core api With this code I am trying to post a Json array to a method in my web core API. However the array arrives as null.
importProperties = function (url, callback, data) {
        var properties = JSON.stringify(data);
        $.ajax({
            url: url,
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            data: { "": properties }
        })
            .done(callback)
            .fail(errorMessage);
    }

Once the data is JSON.stringified, it looks like;
[{"UPRN":"12345","StreetName":"COMPORT GREEN","AddressLine2":"NEW ADDINGTON","AddressLine3":"Croydon","AddressLine4":"Surrey","Postcode":"CR0 0BY","Latitude":null,"Longitude":null,"BlockUPRN":"B12345","PropertyNo":"1","BlockName":"Block Court","Comments":null,"PropertyTypeId":6,"NumberOfBathrooms":1,"NumberOfBedrooms":2,"NumberOfKitchens":1,"PropertyContractId":0,"PropertyType":null},
{"UPRN":"67890","StreetName":"COMPORT GREEN","AddressLine2":"NEW ADDINGTON","AddressLine3":"Croydon","AddressLine4":"Surrey","Postcode":"CR0 0BY","Latitude":null,"Longitude":null,"BlockUPRN":"B67890","PropertyNo":"2","BlockName":"Block Court","Comments":null,"PropertyTypeId":6,"NumberOfBathrooms":null,"NumberOfBedrooms":null,"NumberOfKitchens":null,"PropertyContractId":0,"PropertyType":null}]

The method signature on my web core API is;
[HttpPost("{contractId}/import")]
public async Task<IActionResult> Import(int contractId, [FromBody] IEnumerable<PropertyAndContractDto> properties)
{
   this.NLogger.Info($"api/property/contractId = {contractId}/saveproperties".ToPrefix());
   if (properties == null)
   {
      return BadRequest();
   }
...
}

The DTO is
    public class PropertyAndContractDto
    {
        public string UPRN { get; set; }
        public string StreetName { get; set; }
        public string AddressLine2 { get; set; }
        public string AddressLine3 { get; set; }
        public string AddressLine4 { get; set; }
        public string Postcode { get; set; }
        public string Latitude { get; set; }
        public string Longitude { get; set; }
        public string BlockUPRN { get; set; }
        public string PropertyNo { get; set; }
        public string BlockName { get; set; }
        public string Comments { get; set; }
        public int? PropertyTypeId { get; set; }
        public int? NumberOfBathrooms { get; set; }
        public int? NumberOfBedrooms { get; set; }
        public int? NumberOfKitchens { get; set; }
        public int PropertyContractId { get; set; }
        public string PropertyType { get; set; }
    }
}

When I run in Postman it works;

So why is the properties parameter coming in as null?

A: Try setting the processData property of the ajax call to false, like this:
$.ajax({
            url: url,
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            data: { "": properties },
            processData: false
        })

According to the docs:

By default, data passed in to the data option as an object
  (technically, anything other than a string) will be processed and
  transformed into a query string, fitting to the default content-type
  "application/x-www-form-urlencoded". If you want to send a
  DOMDocument, or other non-processed data, set this option to false.

Alternatively, just set the data property to your stringified json:
$.ajax({
            url: url,
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            data: properties
        })


text:
Q: How to extract and plot only minimal and maximal peaks of an array , -graph analysis- With Matlab or excel I'm doing video analysis.
The end result array I get is something like:
signal =

    Columns 1 through 7

       73960       73960       73960       73960       68102       68102       68102

  Columns 8 through 14

       68102       19187       19187       19187       19187       14664       14664

  Columns 15 through 21

       14664       14664       13715       13715       13715       13715       30832

  Columns 22 through 28

       30832       30832       30832       53031       53031       53031       53031

  Columns 29 through 35

       56897       56897       56897       16104       16104       16104       16104

  Columns 36 through 42

       15188       15188       15188       15188       13973       13973       13973

Note: actual array I get is usually 600+
So when I plot this I get very bad looking graph, so I want to filter this array and only keep the ** maximal and minimal peaks** local maxima and minima so that the graph would have nicer waves
Is there a way I can do it with MATLAB?
if not then can I do it with excel?
as I usually save this array to excel sheet Like this
0.1 68102
0.15    19187
0.2 14664
0.25    13715
0.3 30832
0.35    53031
0.4 56897
0.45    16104
0.5 15188
0.55    13973
0.6 21437
0.65    66950
0.7 65356
0.75    22562
0.8 14154
0.85    13938
0.9 20692
0.95    72823
1   69975
1.05    15328
1.1 14494
1.15    13681
1.2 14205
1.25    65278
1.3 63055
1.35    16999
1.4 14050
1.45    14245

In which the 1st column is the time(y-axis) and 2nd column is the amplitude.(x-axis)
I use this formula to count local maxima (Thanks to brettdj from stackoverflow.com)
=SUMPRODUCT(--(B2:B149>B1:B148),--(B2:B149>B3:B150))

And this formula to count local minima
=SUMPRODUCT(--(B2:B149<B1:B148),--(B2:B149<B3:B150))

But what I need is to filter the array to only keep local maxima and local minima so I can get nicely drawn curve without noise.

A: This VBA

*

*Reads the data from column A and B into a variant arrays

*Find the local minima and maxima and extracts that to second array

*Creates a brand new chart of the minima/maximia (see image)

     Sub NewGraph()
    Dim X
    Dim Y
    Dim lngRow As Long
    Dim lngCnt As Long
    Dim Chr As ChartObject

    X = Range([a1], Cells(Rows.Count, "b").End(xlUp))
    Y = Application.Transpose(X)

    For lngRow = 2 To UBound(X, 1) - 1
        If X(lngRow, 2) > X(lngRow - 1, 2) Then
            If X(lngRow, 2) > X(lngRow + 1, 2) Then
                lngCnt = lngCnt + 1
                Y(1, lngCnt) = X(lngRow, 1)
                Y(2, lngCnt) = X(lngRow, 2)
            End If
        Else
            If X(lngRow, 2) < X(lngRow + 1, 2) Then
                lngCnt = lngCnt + 1
                Y(1, lngCnt) = X(lngRow, 1)
                Y(2, lngCnt) = X(lngRow, 2)
            End If
        End If
    Next lngRow

    ReDim Preserve Y(1 To 2, 1 To lngCnt)

    Set Chr = ActiveSheet.ChartObjects.Add(250, 175, 275, 200)
    With Chr.Chart

        With .SeriesCollection.NewSeries
            .XValues = Application.Index(Application.Transpose(Y), 0, 1)
            .Values = Application.Index(Application.Transpose(Y), 0, 2)
        End With
        .ChartType = xlXYScatter
    End With

End Sub

A: I would just write a simple loop over the array in Matlab to achieve this. I don't see any fundamental problems there?
If you don't want loops in Matlab, you can do it with some array operations. If you have two equallly long arrays a and b, you can do something like c = a>b, which gives you a list with ones and zeros. You1 can use this as a oneliner for selecting the maxima/minima.
Zo suppose you have an upshifted and downshifted array b, c. Such that (except at endpoints)
b(n-1)=a(n)=c(n+1). You can get an array containing only the extrema and zeros by q=a.*( (a>b).*(a>c) + (a<b).*(a<c) )
One advise: If you signal has noise, than also this selection will be noisy. To smoothen the function, you should apply some kind of moving averaging with a kernel you like.

A: If you want the maximum and minimum values just use:
[sig_min, idx_min] = min(signal);
[sig_max, idx_max] = max(signal);

But I couldnt understand exactly what you want… since my account is new, I cant comment on your question to try to understand it better.
— edit 1:
Ok, now I understand what you want. I don't know why you have this array with repetitive numbers, but supposing you don't want them, or, at least, that is better to remove them to find local maxima and minima, you should do:
sinal_norep = signal(find(diff(sinal)));

where signal_norep will be your new array containing only values that differs from the last one:

Now we can search for the index where occurs local maxima and minima on this array, by doing:
minimas_idx = find(signal_norep(2:end-1)<signal_norep(1:end-2) & signal_norep(2:end-1)<signal_norep(3:end))+1;
maximas_idx = find(signal_norep(2:end-1)>signal_norep(1:end-2) & signal_norep(2:end-1)>signal_norep(3:end))+1;

And their values:
signal_maximas = signal_norep(maximas_idx);
signal_minimas = signal_norep(minimas_idx);

Thats it x)


text:
Q: Fixed stretching background image I have drafted up a brief example of what I have so far, and what I'm trying to achieve.
See my demo here
In my jsfiddle you will see a wrapping div named "content-wrap". Within this div I want an image that can stretch to window size and content.
I have done background image stretching before: See example here
But this is a bit more complicated because it is for a specific region within the site.
I have tried having a play so far with my existing code from the link above and I think I may need to take a different approach. As when you scroll down the images doesn't stay in position it moves with the scroll bar (as it should).
Any ideas?

A: If you don't mind using CSS3's background-size property, then the following additions to your #content-wrap { CSS statements will achieve a responsive background image that will expand to fit the size of the container.
#content-wrap {
    height: 1000px;
    background: #ccc;
    color: #fff;

    /* Added CSS */

    display: block;
    max-width: 100%;
    clear: both;
    background: transparent url("http://placekitten.com/900/900") top right no-repeat;
    background-size: cover;
}

Here is an updated version of your jsfiddle with my added CSS and some lovely placekittens:
http://jsfiddle.net/kztGj/22/
The downsides to this are of course that it will not work in Internet Explorer < 9, Firefox 3.6, or any browser that doesn't support CSS3. But then your asking for a responsive image, and as such you'll be hard pushed to find an elegant solution that supports older browsers.
For more information on the background-size property and its uses, I recommend checking out this article, its quite informative.

A: In your image, add a css like this
.custom-image {
    width:100%;
}

and your html


text:
Q: How do you add the installation screen for your an electron app like atom, WhatsApp and others? I Have created my first app with electron but I am down with the question How do you add the installation screen for your an electron app like atom, WhatsApp and others?
I have seen this in several apps built with electron and I just don't see in the documentation

A: Take a look at this NPM package that creates Windows installers for Electron applications. https://github.com/Electron/Windows-Installer

A: you can use one of electron builder like electron builder and as per configuration you have to mention icon property in your package.json like
"win": {
  "icon": "../icons/icon"
}


text:
Q: Anyone can explain this Java code for transposing a matrix? I have in front of me a java code but I do not understand what happen in the toString method and the transpose method .
I mean what happen in the for loop ?
I will be appreciating if anyone can help me with this.
this is the other method
public static int[][] transpose(int[][]m){

    int[][] temp = new int[m[0].length][m.length];
    for (int i = 0; i < m.length; i++){
        for (int j = 0; j < m[0].length; j++){
            temp[j][i] = m[i][j];
        }

    }
        return temp;
}

this is the code
package question5;

import java.util.Arrays;
import java.util.Scanner;

public class Matrix {

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);

        int[][] multarray = new int[4][4];

        System.out.print("Enter your Numbers between 1 and 16");
        for(int i = 0 ; i < multarray.length; i++){
            for(int j = 0 ;j < multarray.length; j++){

                multarray[i][j] = sc.nextInt();
            }
        }

        for(int row = 0 ; row<multarray.length; row++){
            for(int col = 0; col< multarray.length; col++){
                System.out.print(multarray[row][col] + " ");
            }
            System.out.println();

        }
        System.out.println();
        System.out.println();
        System.out.println("Transpose Array is : ");

        System.out.println(toString(transpose(multarray)));
    }

    public static int[][] transpose(int[][]m){

        int rows = m.length;
        int cols = m[0].length;

        int t[][] = new int [cols][];
        for(int trow = 0 ; trow < cols; trow++){
            t[trow] = new int[rows];
        }

        for(int row = 0; row< rows;row++){
            for(int col = 0; col<cols; col++){
                int tcol = rows-row-1;
                int trow = cols-col-1;
                t[trow][tcol] = m[row][col];
            }
        }
        return t;
    }

    public static String toString(int[][] m) {
        StringBuilder text = new StringBuilder();
        for (int row = 0; row < m.length; row++) {
            int r[] = m[row];
            for (int col = 0; col < r.length; col++) {
                if (col > 0) text.append(", ");
                text.append(r[col]);
            }
            text.append("\n");
        }
        return text.toString();
    }
}

A: These two lines are the "heart" of the transpose method:
int tcol = rows-row-1;
int trow = cols-col-1;

Given a pair (row, column) which represents a coordinate of a cell in a square matrix, they compute its destination coordinate in the transposed matrix, which is simply a reflection over the main diagonal of the matrix.
Here is an illustration of this:

(0, 0)


text:
Q: Laravel 5 - validator for current user password I have password change form and there's two fields in it: old_password and new_password.
I'm stuck with validator for old password, here's what I done:
Validator::extend('old_password', function($attribute, $value) use ($user) {
    return $user->password === Hash::make($value);
});

But Hash::make($value) always generates different result with the same $value.
How can I make validator to match current user password?

A: You should use Hash::check( $plaintext, $hashed ) instead:
return Hash::check( $value, $user->password );


text:
Q: How to add next & prev buttons with table in reactJs? I have a table where data is inserted from a JSON. Using React.Component, the table creation is below:

  {DATA.map(x => (

    {x.date}
    {x.name}
    {x.language}
    Click to Listen

  ))}

Data displaying properly but I have to add next & prev buttons with the table. How can I do that?
At least 5
 should display simultaneously.
[![enter image description here][1]][1]

A: Since you show so little code, i assume you are using react, and using functional component.
const [ page, setPage ] = useState(0); //create page state

const pageData = useMemo(() => { //use useMemo to memorize the page

     return DATA.slice(page*5, (page*5)+5)
},[page])

const nextPage = () => setPage(prev => prev+1) //next page
const prevPage = () => setPage(prev => prev > 0 ? prev-1 : prev) //prev page - need to add condition here so it doesn't go below 0

Reference to Slice method
in your rendering, use pageData instead of DATA, example

  {pageData.map(x =>

      {x.date}
      {x.name}
      {x.language}
      Click to Listen

  )}

You may then create buttons to call nextPage and prevPage e.g.
<button onClick={nextPage}>Next</button>

You have to add your own codes to check for maximum number of pages, and minimum number of pages so it doesn't throw error.
CodeSandBox


text:
Q: find files older than x days then output names and size before deleting them I'm trying to find the files that are older than x days then print their names and the total size to a text file before deleting them, the problem is when I combine more than (-exec) option I got errors.
Here is my sh file
#!/bin/bash
cache_location=$1
age=$2
date=`date +%d-%m-%Y`
find $cache_location -mtime $2 -path '*keyword*' -fprint deleted_cache_$date.log -exec du -k {} \; | awk '{total+=$1}END{print "TOTAL SIZE " total/1024/1024 "GB"}' >> deleted_cache_$date.log \;
-exec echo {} | wc -l>> deleted_cache_$date.log \;
-exec rm -r {} \;

Then I call the script like:
.\myscript.sh location +30

The script stops with an error
awk: fatal: cannot open file `;' for reading (No such file or directory)
find: 'du' terminated by signal 13

In the log file, I can see all results of find command.


text:
Q: Unable to run Bash script from Octopus I have been trying to trigger Jenkins Job from Octopus. One way that I found - Remote Access API.
But when I trigger the command from Octopus, I get an error.
Command:
curl -X POST -s "https://jenkins.jenkins.dev/job/MyService/buildWithParameters" -u user:xxx-F dstenv=p1-qa version=from-qa

Error:
The remote script failed with exit code 6
April 21st 2021 07:51:35 Fatal
The action step1 on a Worker failed

I ran the command on the slave machine directly - runs fine.  When I run other commands from octopus, it runs fine, just when I run the curl command it gives the error.

So what gives!

A: I found that Octopus is unable to understand the responses coming from the Bash commands, so we have to handle the status messages ourselves.
So after triggering the command, I print out the status message, that lets otopus know that the error message is handled:
curl -X POST -s "https://jenkins.jenkins.dev/job/MyService/buildWithParameters" -u user:xxx-F dstenv=p1-qa version=from-qa
echo $?

This way i was able to execute my bash scripts from octopus. There are bunch of bash commands that show up as errors in octopus deplyments in UI. If we dont handle the status code in this manner, the deployment in octopus is marked as failed.


text:
Q: Why is the Javascript operator "&&" so weird? a = 1;
b = "1";
if (a == b && a = 1) {
    console.log("a==b");
}

The Javascript code above will result in an error in the if statement in Google Chrome 26.0.1410.43:

Uncaught ReferenceError: Invalid left-hand side in assignment

I think this is because the variable a in the second part of the statement &&, a=1 cannot be assigned. However, when I try the code below, I'm totally confused!
a = 1;
b = "1";
if (a = 1 && a == b) {
    console.log("a==b");
}

Why is the one statement right but the other statement wrong?

A: = has lower operator precendence than both && and ==, which means that your first assignment turns into
if ((a == b && a) = 1) {

Since you can't assign to an expression in this way, this will give you an error.

A: Because the order of operations is not what you expect. a == b && a = 1 is equivalent to (a == b && a) = 1 which is equivalent to false = 1.
If you really want to do the assignment, you need to use parentheses around it: a == b && (a = 1).

A: The second version is parsed as a = (1 && a == b); that is, the result of the expression 1 && a == b is assigned to a.
The first version does not work because the lefthand side of the assignment is not parsed as you expected. It parses the expression as if you're trying to assign a value to everything on the righthand side--(a == b && a) = 1.
This is all based on the precedence of the various operators. The problem here stems from the fact that = has a lower precedence than the other operators.

A: In if (a = 1 && a == b),
The operations to be first performed is 1 && a == b. 1 && the result of a == b  is performed. The result of this && operation is assigned to a.


text:
Q: MonoDroid DialogFragment setStyle I'm currentyly trying to convert a DialogFragment from Java to C#.
In Java I can use setStyle( STYLE_NO_TITLE, Theme ); to set the style and the theme of the dialog. But in MonoDroid I can't find a way of doing this. I can find the type DialogFragmentStyle.NoTitle but I can't find anyway to use it to set the style or anyway to set the theme.
Does anybody have any idea of how to do this?
Thanks in advance.
Terry

A: You can use Android.Ressource.Style and select the style you wish, so your SetStyle could look like:
SetStyle(DialogFragmentStyle.Normal, Android.Resource.Style.ThemeHoloLight);

A: When using AndroidX, you should use the following:
SetStyle(AndroidX.Fragment.App.DialogFragment.StyleNormal, Android.Resource.Style.ThemeHoloLight);


text:
Q: VMware clone as backup Having a couple of ESXi and a vCenter 6.5. I'd like to backup some of the production VMs i.e. have a "photo" of a known working state with all programs installed and configured for the purpose of restore operations (not data, of course) in case the VM gets corrupted or stops working for some reasons.
I was thinking about:

*

*Clone the Virtual Machine. VM will be powered of for a consistent clone

*I'd clone it on a separate datastore sitting on a different virtual disk

*Remove the clone from the Inventory (because it's not supposed to be powered on / managed)

*In case the original VM gets corrupted, browser the datastore to the cloned vmx and then Register VM, to restore the VM to the known state

Of course I'm not referring to data backup, which will be treated separately.
Is this solution ok or am I missing something?
And by the way, what's the difference between cloning, and simply copying the entire VM folder from one datastore to another?


text:
Q: Are  tags depreciated, CSS accordion not working? I have an accordion I built that uses some JS to trigger the open and close. It works fine in my JSFiddle, but on the site it does not open. Also it does not throw any errors.
Any Idea on what is causing this? Is the <dt> <dd> tags depreciated for Google Chrome?
Javascript:
(function(){
    var d = document,
    accordionToggles = d.querySelectorAll('.js-accordionTrigger'),
    setAria,
    setAccordionAria,
    switchAccordion,
  touchSupported = ('ontouchstart' in window),
  pointerSupported = ('pointerdown' in window);

  skipClickDelay = function(e){
    e.preventDefault();
    e.target.click();
  }

        setAriaAttr = function(el, ariaType, newProperty){
        el.setAttribute(ariaType, newProperty);
    };
    setAccordionAria = function(el1, el2, expanded){
        switch(expanded) {
      case "true":
        setAriaAttr(el1, 'aria-expanded', 'true');
        setAriaAttr(el2, 'aria-hidden', 'false');
        break;
      case "false":
        setAriaAttr(el1, 'aria-expanded', 'false');
        setAriaAttr(el2, 'aria-hidden', 'true');
        break;
      default:
                break;
        }
    };
//function
switchAccordion = function(e) {
    e.preventDefault();
    var thisAnswer = e.target.parentNode.nextElementSibling;
    var thisQuestion = e.target;
    if(thisAnswer.classList.contains('is-collapsed')) {
        setAccordionAria(thisQuestion, thisAnswer, 'true');
    } else {
        setAccordionAria(thisQuestion, thisAnswer, 'false');
    }
    thisQuestion.classList.toggle('is-collapsed');
    thisQuestion.classList.toggle('is-expanded');
        thisAnswer.classList.toggle('is-collapsed');
        thisAnswer.classList.toggle('is-expanded');

    thisAnswer.classList.toggle('animateIn');
    };
    for (var i=0,len=accordionToggles.length; i<len; i++) {
        if(touchSupported) {
      accordionToggles[i].addEventListener('touchstart', skipClickDelay, false);
    }
    if(pointerSupported){
      accordionToggles[i].addEventListener('pointerdown', skipClickDelay, false);
    }
    accordionToggles[i].addEventListener('click', switchAccordion, false);
  }
})();

Also a linke to the live-site, you can see the accordion on screensizes smaller than 1069px.
It seems to register my click, but doesn't open the accordion.
Thanks for the help everyone!


text:
Q: Create an automatic farm in Minecraft PE? I play Minecraft PE on my iPad, and PE doesn't have pistons. So I was wondering if there was any way to create an automatically irrigating farm(using iron doors, maybe?)

A: In my world I've built two different farms. The square farm and the sloped farm. Both of these are semi-automatic, that is you'll have to plant them manually, but they gather up the produce using water. Both farm types has loads of videos example available, but I've tried to explain them textually here.
Square farm
The main idea is that one single water block placed in the center can irrigate an entirely 9x9 area. So I fenced in an area of 11x11, left one grass block inside the fence to collect the produce, and replaced the center block with a water block, and a block of your choice on top of it.
Then I hoed the area, planted some seed and waited for it to grow. When it came to harvesting, I sneaked into the center jumped on top of the block and put down a water bucket. This harvest everything getting it ready for the next round.
The sloped farm
The sloped farm is also a common variant of wheat farm, and it uses some of the same principles, but it can be extended to even larger fields (which does take some time to plant).
The idea here is to have long rows of harvest, interleaved with rows of water for irrigation. The same rule as above still applies, that a water block can be used to irrigate rows up until 4 away.
One layout of this in beautiful ascii art:
222222222211111111
ssssssssssssssssss      s  stonewall
sWDfffffffFFFFFFFH      W  Water
sWDfffffffFFFFFFFH      D  Dirt
sWDfffffffFFFFFFFH      f  Farmland
sWDfffffffFFFFFFFH      F  Farmland
sWDhbhbhbhbhbhbhhH      h  halfslab on water
sWDfffffffFFFFFFFH      b  block on water
sWDfffffffFFFFFFFH      H  Halfblock
sWDfffffffFFFFFFFH
sWDfffffffFFFFFFFH      2  Level of all blocks in column
ssssssssssssssssss      1  Level of all blocks in column

This scheme can be extended both column-wise and row-wise, if you are so inclined. Replace the last row with the last four rows, and/or the last column with the last 8 rows at a lower level.
I tend to use the water row for traversing the field to avoid stamping on the farmland, and for seeding. When the times comes to harvest, I temporarily remove the dirt allowing the water to flow down (i.e. from left to right) collecting all the produce and seeds on the last column of half slabs. Give the water a few seconds before replacing the dirt to stop the water flow.
Automating the water flow
One common variant of the sloped farm is to use pistons to raise/lower the dirt block I've suggested for holding the water. This is as indicated not available in MCPE ver 0.14, but I've been contemplating whether the water/dirt column can be replaced with a column of redstone dispensers (with a water bucket inside) hooked to a lever.
Final notes
There are two vital notes related to farming, and the first is that you need to be somewhat close to the farm for it to grow. The exact distances I'm not quite sure of, and have heard different numbers. But I once tried growing sugar canes around 40 blocks away from my home (as there was sand and water), and they didn't grow. After moving that field next to my main house, they grow like crazy.
The second note is that if you add sufficient light it will keep on growing through the night (unless you are sleeping). And the lights also has the added benefit of keeping most of the mobs away.
So in my current setup I have made a sloped wheat farm on top of my house which was built in a hill. North of it I've made a moot to keep mobs floating away, and then five rows of sugar canes, and then north of that a square farm for ransom produce. (On the south side I've made a fenced area for cows and one for sheep.)

A: There is some videos out there on how to make these.  For instance the Youtuber NebsGaming created an efficient one.  This might just be what you had in mind.
Minecraft Pocket Edition - Automatic Farm!

This tutorial shows you how to build an automatic farm for wheat, potatoes, carrots or beetroot in Minecraft PE. (If you were looking for another way to do this I'll edit this post)


text:
Q: Issue with @Inject for Constructor I am new to robojuice, but i need to work on a piece of code which was already built by someone else. I am facing issue if I add an extra parameter to the constructor of a class which already has @Inject. My android application crashes giving the below error with no detail description about the issue:
"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.my.app.envTest/com.my.app.navigation.NavigActivity}: com.google.inject.ConfigurationException: Guice configuration errors:"

I am sure this error is not with the activity, but with the new parameter i added to the constructor. If i remove that param it works fine.
Previously:
 @Inject
public PlotRepo(RuntimeExceptionDao<Plot, String> plotDao, RuntimeExceptionDao<LocalPlotData, Long> localPlotDataDao) {
    this.plotDao = plotDao;
    this.localPlotDataDao = localPlotDataDao;
   }

Facing issue for:
 @Inject
public PlotRepo(RuntimeExceptionDao<Plot, String> plotDao, RuntimeExceptionDao<LocalPlotData, Long> localPlotDataDao, RuntimeExceptionDao<LocalSelPlotData, Long> localSelPlotDataDao) {
    this.plotDao = plotDao;
    this.localPlotDataDao = localPlotDataDao;
    this.localSelPlotDataDao = localSelPlotDataDao;
   }

After Debugging i got this error:
1) Could not find a suitable constructor in     com.j256.ormlite.dao.RuntimeExceptionDao. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.
  at com.j256.ormlite.dao.RuntimeExceptionDao.class(Unknown Source)
  while locating     com.j256.ormlite.dao.RuntimeExceptionDao<com.myapp.s.b.sets.domain.LocalSelPlotData, java.lang.Long>
  for parameter 2 at com.tp.my.sets.PlotRepo.<init>(Unknown Source)
  while locating com.myapp.s.b.sets.PlotRepo
  for parameter 1 at com.myapp.s.b.GroupingManager.<init>(Unknown Source)
  while locating com.myapp.s.b.GroupingManager
  for field at com.myapp.s.b.navigation.NavigActivity.groupingManager(Unknown    Source)
   while locating com.myapp.s.b.navigation.NavigActivity

Not sure where I am going wrong, also could not find much help on this.
Can someone help me figure out the issue.
Thanks

A: There were two things that missed in my code. My database classes were missing default constructors. Ormlite needs default constructors, which were missing in some of my classes. After that, I had missed the bindings for the Db annotated dependency like this:
    bind(new TypeLiteral<RuntimeExceptionDao<MyTable, Long>>() {}).toProvider(new DaoProvider<MyTable, Long>(MyTable.class));

After these changes the issue got fixed.
Thanks all for the help!

A: Firstly - though this does not explicitly answer your question, but cannot have those two constructors - after Type Erasure they are identical and indistinguishable.
You'd need to explicitly define classes such as
RuntimePlotExceptionDao extends RuntimeExceptionDao<Plot, String>
RuntimeLocalPlotDateExceptionDao extends RuntimeExceptionDao<LocalPlotData, Long>

Secondly - why do you want to have two @Inject constructors? Which one should the container pick when creating the object?


text:
Q: Text to speech playing automatically I have a text to speech function in my android app that works to an onClick event, there is an issue  when the activity starts, the text to speech starts without clicking the button, is there a line of code I can put in to stop this happening, thank you.
package com.androidhive.texttospeech;

import java.util.Locale;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AndroidTextToSpeechActivity extends Activity implements
    TextToSpeech.OnInitListener {
/** Called when the activity is first created. */

    private TextToSpeech tts;
    private Button button1;
    private TextView txtText;

 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tts = new TextToSpeech(this, this);

    button1 = (Button) findViewById(R.id.button1);

    txtText = (TextView) findViewById(R.id.txtText);

    // button on click event
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            speakOut();
        }

    });
 }

@Override
public void onDestroy() {
    // Don't forget to shutdown!
    if (tts != null) {
        tts.stop();
        tts.shutdown();
    }
    super.onDestroy();
 }

@Override
public void onInit(int status) {
    // TODO Auto-generated method stub

    if (status == TextToSpeech.SUCCESS) {

        int result = tts.setLanguage(Locale.US);

        // tts.setPitch(5); // set pitch level

        // tts.setSpeechRate(2); // set speech speed rate

        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "Language is not supported");
        } else {
            button1.setEnabled(true);
            speakOut();
        }

    } else {
        Log.e("TTS", "Initilization Failed");
    }

    }

 private void speakOut() {

    String text = txtText.getText().toString();

    tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
   }
}

A: I saw these codes in onInit(), which will be called after the TextToSpeech is instantiated and initialized successfully. See the speakOut() here? That's what causes your problem.
if (result == TextToSpeech.LANG_MISSING_DATA
            || result == TextToSpeech.LANG_NOT_SUPPORTED) {
        Log.e("TTS", "Language is not supported");
} else {
    button1.setEnabled(true);
    speakOut();
}

A: The reason why this happens is because you invoke speakOut# In the onInit() method, remove speakOut():
 if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "Language is not supported");
        } else {
            button1.setEnabled(true);
          //  speakOut();
        }


text:
Q: Use quickCheck tests with Cabal? What's the current state of test suites in cabal, and, more importantly, where can I keep atop them?
I've done some poking around, and the latest information that I can find implies that I can't trust the documentation, and I haven't been able to find anyone talking about it for the better part of a year. I've heard rumor of a cabal-test-quickcheck library but can't seem to find one on hackage and can find no examples of how to set it up.
What's the standard way to hook up quickCheck tests into a cabal test suite these days?

A: Cabal-1.14.0.0 has come out since then and the detailed test suite seems to be available.
The cabal-test-quickcheck package doesn't seem to have been released yet though, maybe you can get similar functionality from test-framework-quickcheck2?
Alternatively, you can ignore the inbuilt test support in Cabal and just use a flag to determine whether or not to build a test executable.