text:
Q: The scrollview doesn't scroll I'm trying to use Scrollview but it is not working for me whatsoever.
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/top"
    android:orientation="vertical"
    tools:context=".ui.home.HomeFragment">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:animateLayoutChanges="true"
        android:layout_marginTop="?attr/actionBarSize"
        android:fillViewport="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:orientation="vertical"
        android:weightSum="10">

        <GridLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="20"
            android:columnCount="2"
            android:rowCount="3"
            android:alignmentMode="alignMargins"
            android:columnOrderPreserved="false"
            android:padding="15dp"
            >
            <androidx.cardview.widget.CardView
                .....
                >
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_horizontal|center_vertical"
                    android:layout_marginTop="15dp"
                    android:orientation="vertical"
                    >
                    <TextView
                      ...>

                    </TextView>
                    <ImageView
                       ...>
                    </ImageView>
                </LinearLayout>
            </androidx.cardview.widget.CardView>

</GridLayout>

    </LinearLayout>
    </ScrollView>
</LinearLayout>

I tried every solution I found online, but nothing worked.
I tried to add this :
android:orientation="vertical"
to the linearLayout, but it changed nothing. I still can't scroll
How can I get the scrollView to work?

A: Put your layout under the ScrollView Like this
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ScrollActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="wrap_content">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/> <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    </LinearLayout>

  </ScrollView>

Make sure that your Child layout has enough views so that can scrollable.
I hope this can helps you out from your problem ):

A: Try replacing like this
android:layout_width="fill_parent"
android:layout_height="fill_parent"


text:
Q: Display HTMLInputElement in console of chrome I want to display the HTMLInputElement object of an HTML input :
 <div>
  <input type="text" id="name" name="toto" value="test" />
</div>

JS script :
<script>
  const inputEl = document.getElementById("name");
  console.log(inputEl);
</script>

In the chrome console, I get this :

But I want to display it as an HTMLInputElement object.
In stackblitz console I get the object :

Thank you :)
But locally I dont get the object !!

A: Not 100% sure what you mean by 'display as an HTMLInputElement'.
If you want to see all its fields, you might want to use console.dir(inputEl).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add coordinates to google-maps-react on a user click event? I'm trying to add a marker on based on a user clicking on the map for the google-maps-react npm. Currently the code below will generate markers and add them to the this.state = { markers:[ ] } and I would like to map them out on the map component. However, the position:event.latLng, will not register the lat and lng and the marker will only be created and inserted into the state with the key: Date.now() and defaultAnimation: 2. Below the code:
import React, { Component } from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';

export class MapContainer2 extends Component {
  constructor(props){
    super(props);

    this.state={
      lat:null,
      lng:null,
      markers:[]
    }
  }

  componentDidMount(){
    navigator.geolocation.getCurrentPosition(position=>
      this.setState({
        lat:position.coords.latitude,
        lng:position.coords.longitude,
      }));
   }

   mapClicked = (event) =>{
     const { markers } = this.state;
     this.setState({
       markers:[
         {
           position:event.latLng,
           key: Date.now(),
           defaultAnimation: 2,
         },
         ...markers
       ]

     })
   }

  render() {
    if (!this.props.loaded) {
      return
Loading...

    }
    const style = {
    width: '100%',
    height: '100vh'
  }
    return (
      <Map
       google={this.props.google}
       zoom={11}
       style={style}
       initialCenter={{
          lat: this.state.lat,
          lng: this.state.lng
       }}
       center={{
          lat: this.state.lat,
          lng: this.state.lng
       }}
       onClick={this.mapClicked}
       >
       <Marker
         title={'Geolocation'}
         position={{
           lat:this.state.lat,
           lng:this.state.lng,
         }}
       />

      </Map>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: ('AIzaSyCZ7rgMN34kWkGvr8Pzkf_8nkT7W6gowBA')
})(MapContainer2)

A: I resolved it by updating the function mapClicked with the following:
mapClicked = (mapProps, map, event) => {
    const { markers } = this.state;
    const lat = event.latLng.lat();
    const lng = event.latLng.lng();
    let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=myapikey`
    axios.get(url).then(response => {
        this.setState({
          googleReverseGeolocation:response.data.results[0].formatted_address,
          markers:[{position:{lat:event.latLng.lat(),lng:event.latLng.lng()}}, ...markers],
          latClick:lat,
          lngClick:lng
        });
       this.props.onMapClickChange(lat, lng, response.data.results[0].formatted_address);
    });
  }


text:
Q: JQuery image transition. swipe up I have searched online but am failing to find anyhting that quite matches what I am after.
I want to have my images changing using a swipe transition. Like can be seen on the Windows 8 preview release video ( http://windows.microsoft.com/en-US/windows-8/release-preview ) in the first few seconds, where the tile image changes to text then to something else.
Can this be accomplished in JQuery? Or is there a better way?
Thanks.
EDIT: I have found the desired effect here: http://malsup.com/jquery/cycle/browser.html Under the "scrollUp" option on the left. But I cant for the life of me get it to work on my page!
Could anyone direct me as to where to provided code should go within the following script?
<img id="img" src="link here">
<script>
function changeImage()
{
    var img = document.getElementById("img");
    img.src = images[x];
    x++;

    if(x >= images.length){
        x = 0;
    }

    //fadeImg(img, 100, true);
    setTimeout("changeImage()", 3000);
}

var images = new Array(),
x = 0;

images[0] = "link here";
images[1] = "link here";
images[2] = "link here";
setTimeout("changeImage()", 3000);
</script>

A: To my knowledge this is not achievable through JQuery alone, JQuery provides the slideUp and slideDown plugins which will achieve similar, but it's not a swipe action.


text:
Q: Angular 8: Use HostListener to Find DOM Element after a Mouse Click event How do I find the current DOM element anywhere in the page, after a mouse click?
Currently trying to use HostListener in Angular 8.
@HostListener('click') onClick(){
    window.alert('Current DOM element is');
}

A: Set second parameter with $event.target
@HostListener('click', ['$event.target']) onClick(e){
  window.alert('Current DOM element is');
  console.log(e);
}

A: You can also use ElementRef
import { ElementRef } from '@angular/core';

constructor(private elementRef: ElementRef) {}

@HostListener('click') onClick(){
    console.log(this.elementRef.nativeElement);
}

A: Here is the link that explains that you can use a directive to detect a dom element and when it is present only then host listener should work.
Refer this:


text:
Q: convert java class to vb 2008 application I wrote a Java class that parses a bpel text file and then returns a count of the number of occurences of certain words. I wanted to convert it to VB2008 Forms application, so that its results are displayed in a TextBox and not on the console. The problem is that VB2008 lacks Scanner and StringTokenizer classes, which are in my current Java class. Am not sure how to get the same functionality (or better) in VB2008. Can someone out there help to convert this class. Thank you.
The Java class is as follows:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;

public class StringParser
{
private int ctrlFlowStructures;
private String filePath;
private ArrayList<String> activities;
final String[] ctrlFlowsArray={"sequence","if","while","repeatUntil","forEach", "pick","flow"};

public StringParser(String path)
{
    filePath=path;
    ctrlFlowStructures =0;
    activities=new ArrayList<String>();
}

//count number of occurences of words in ctrlFlowStructureArray
public int countCtrlFlowStructures ()
{
    Scanner input=null;
    StringTokenizer st;
    String line=null;
    String openingComment="!--";
    String closingComment="--";
    int c=0;

    try
    {
        input=new Scanner( new FileInputStream(filePath));
    }

    catch(FileNotFoundException e)
    {
        System.out.println("Problem opening files.");
        System.exit(0);
    }

    while(input.hasNextLine())
    {
        line=input.nextLine();
        line.trim();
        st= new StringTokenizer(line, " <,>\"",false);
        String temp=null;
        while (st.hasMoreTokens())
        {
            temp=st.nextToken();

            //eliminate comments
            if(temp.equals(openingComment)||temp.equalsIgnoreCase("documentation"))
            {
                c=1;
            }
            if(temp.equals(closingComment)||temp.equalsIgnoreCase("/documentation"))
            {
                c=2;
            }
            if(c==0||c==2)
            {
                for(int i=0;i< ctrlFlowsArray.length;i++)
                if(temp.equalsIgnoreCase(ctrlFlowsArray [i]))
                {
                    ctrlFlowStructures ++;
                }
            }
        }
    }
    input.close();
    return ctrlFlowStructures;
}

//display control flow structures
public void display()
{
    int openingComment=0; //number of occurrence of an activity
    for(int i=0;i< ctrlFlowsArray.length;i++)
    {
        for (int j=0;j<activities.size();j++)
        {
            if(ctrlFlowsArray [i].equalsIgnoreCase(activities.get(j)))
            {
                openingComment++;
            }
        }
        if(openingComment>0)
        {
            System.out.println(ctrlFlowsArray [i]+" = "+openingComment);
            openingComment=0;
        }
    }
}
public static void main(String[] args)
{
    StringParser sp=new StringParser("c:\\MyFile1.bpel");
    int a = sp.countCtrlFlowStructures();
    System.out.println(" The number of control-flow structure(s) = " + a);
}
}

And this is the code snippet of the MyFile1.bpel file that was parsed:
    <sequence>
    <documentation>
        The sequence includes several activities which are executed in lexical order.
    </documentation>

    <receive
        name="start"
        partnerLink="MyProcess"
        operation="operation1"
        portType="ns1:portType1"
        variable="inputVar"
        createInstance="yes">

        <documentation>
            The Receive activity makes the process to wait for the incoming message to arrive.
        </documentation>
    </receive>

    <assign name="Assign1">
        <documentation>
            The Assign activity copies data from the input variable to the output variable.
        </documentation>

        <copy>
            <from>$inputVar.inputType/ns2:paramA</from>
            <to>$outputVar.resultType/ns2:paramA</to>
        </copy>
    </assign>

    <reply
        name="end"
        partnerLink="MyProcess"
        operation="operation1"
        portType="ns1:portType1"
        variable="outputVar">

        <documentation>
            The Reply activity returns a message from the process to the  partner which initiated the communication.
        </documentation>
    </reply>
</sequence>

Result:
The number of control-flow structure(s) = 1.

A: You can use String.Split instead of StringTokenizer. For your use of Scanner, System.IO.StreamReader should be a suitable replacement.
Since what you are parsing looks like an XML file, you might consider using the XML parsing features of .NET instead of string operations.


text:
Q: 95% confidence interval To determine whether a prep course improved ACT scores, researchers collected a random sample of ACT scores from 1500 U.S. high school juniors who completed a prep course prior to taking the ACT exam.  They also collected a random sample of ACT test scores from 1500 U.S. high school students who did not complete a prep course prior to taking the ACT exam.  Those who completed the prep course had a mean score of 22.1 with a standard deviation of 3.9 and those who did not take the prep course had a mean score of 21.3 with a standard deviation of 4.3.
a.  Determine the 95% confidence interval for both population means.
b.  Is the difference between the 2 population means statistically significant?
I used s.d. = $s/sqrt(n)$ to find the sample standard deviation, but this didn't seem to produce reasonable results.  0.1 for first group and 0.11 for second group.  Lost as to the approach on this problem.  Is this really math?
I understand that IF I could find the standard deviation I'd look at 2 std deviations to either side of the mean for the 95% interval.  Not sure what to do next.


text:
Q: Creating a horizontal navigation with different colours I am trying to create a simple navigation menu with different background colours for each option, and which is horizontal. So far I have my navigation as shown.

Session 1

Session 2

Session 3

But I am confused on how to do this with CSS.
I would like this menu to look like the image shown.

Many thanks,
Jonny.

A: You'll want to do the following with your code:
CSS:
#session-nav { list-style: none; }
#session-nav li { display: inline-block; padding: 5px 10px; }
#session-nav li.session1 { background: green;  }

EDIT: Here is a jsfiddle http://jsfiddle.net/hgJ68/

A: I won't make the whole thing, but here's the basic idea:
* { margin: 0; padding: 0;}
#session-nav {
    width: 100%;
    background: #bdc3c7;
}
/* make the li's display inline */
#session-nav li {
    display: inline-block;
}

/* remove the underline from the links */
#session-nav li a {
    text-decoration: none;
}

/* add a background */
.session1 {
    background: #2ecc71;
}

.session2 {
    background: #e67e22;
}

.session3 {
    background: #f1c40f
}

DEMO


text:
Q: std::vector init with braces call copy constructor twice Why when I init std::vector with braces
std::vector<TS> vec {ts1, ts2};

Compiler call twice copy constructor operator? On the other hand - with push_back it called only once.
#include <iostream>
#include <vector>
using namespace std;

struct TS{
    TS(){
        cout<<"default constructor\n";
    }

    TS(const TS &other) {
        cout<<"Copy constructor\n";
    }

    TS(TS &&other) noexcept{
        cout<<"Move constructor\n";
    }

    TS& operator=(TS const& other)
    {
        cout<<"Copy assigment\n";
        return *this;
    }

    TS& operator=(TS const&& other) noexcept
    {
        cout<<"Move assigment\n";
        return *this;
    }

    ~TS(){
        cout<<"destructor\n";
    }

};

int main() {
    TS ts1;
    TS ts2;
    cout<<"-----------------------------------------\n";
    std::vector<TS> vec {ts1, ts2};
    //vec.push_back(ts1);
    //vec = {ts1, ts2};
    cout<<"-----------------------------------------\n";

    return 0;
}

http://ideone.com/qcPG7X

A: From what I understand, initializer_lists pass everything by const-reference. It is probably not safe to move from one. The initializer_list constructor of a vector will copy each of the elements.
Here are some links:
initializer_list and move semantics

No, that won't work as intended; you will still get copies. I'm pretty
  surprised by this, as I'd thought that initializer_list existed to
  keep an array of temporaries until they were move'd.
begin and end for initializer_list return const T *, so the result of
  move in your code is T const && — an immutable rvalue reference. Such
  an expression can't meaningfully be moved from. It will bind to an
  function parameter of type T const & because rvalues do bind to const
  lvalue references, and you will still see copy semantics.

Is it safe to move elements of a initializer list?

initializer_list only provides const access to its elements. You could
  use const_cast to make that code compile, but then the moves might end
  up with undefined behaviour (if the elements of the initializer_list
  are truly const). So, no it is not safe to do this moving. There are
  workarounds for this, if you truly need it.

Can I list-initialize a vector of move-only type?

The synopsis of  in 18.9 makes it reasonably clear
  that elements of an initializer list are always passed via
  const-reference. Unfortunately, there does not appear to be any way of
  using move-semantic in initializer list elements in the current
  revision of the language.

questions regarding the design of std::initializer_list

From section 18.9 of the C++ Standard:
An object of type initializer_list provides access to an array of objects of type const E. [ Note: A pair of pointers or a pointer plus
  a length would be obvious representations for initializer_list.
  initializer_list is used to implement initializer lists as specified
  in 8.5.4. Copying an initializer list does not copy the underlying
  elements. — end note ]
I think the reason for most of these things is that
  std::initializer_list isn't actually a container. It doesn't have
  value semantics, it has pointer semantics. Which is made obvious by
  the last portion of the quote: Copying an initializer list does not
  copy the underlying elements. Seeing as they were intended solely for
  the purpose of initializing things, I don't think it's that surprising
  that you don't get all the niceties of more robust containers such as
  tuples.

If I understand the last part correctly, it means that two sets of copies are needed since initializer_list does not copy the underlying elements. (The previous quote is only relevant if you attempt to use an initializer_list without copying out the elements.)
What is the underlying structure of std::initializer_list?

No, you can't move from the elements of an initializer_list, since
  elements of an initializer_list are supposed to be immutable (see the
  first sentence of the paragraph quoted above). That's also the reason
  why only const-qualified member functions give you access to the
  elements.

If you want, you can use emplace_back:
vec.emplace_back(TS());
vec.emplace_back(TS());
vec.push_back(std::move(ts1));
vec.push_back(std::move(ts2));

A: Because you have two elements there.


text:
Q: Inserts and Updates getting blocked on a table in postgres We have lately been encountering a situation where DMLs(we only use inserts and updates) on one specific table in Postgres get blocked from time to time. Queries on all other table run just fine, albeit with some added latency because of added load.
We have noticed that autovacuum was active during some of those periods on the toasts table related to the table in question.
During one of those times, we tried to see all the queries which were stuck and we could see all updates and inserts on that particular table to be waiting for each other:
SELECT blocked_locks.pid         AS blocked_pid,
       blocked_activity.usename  AS blocked_user,
       blocking_locks.pid        AS blocking_pid,
       blocking_activity.usename AS blocking_user,
       blocked_activity.query    AS blocked_statement,
       blocking_activity.query   AS current_statement_in_blocking_process
FROM pg_catalog.pg_locks blocked_locks
JOIN pg_catalog.pg_stat_activity blocked_activity  ON blocked_activity.pid = blocked_locks.pid
JOIN pg_catalog.pg_locks blocking_locks            ON blocking_locks.locktype = blocked_locks.locktype
     AND blocking_locks.DATABASE      IS NOT DISTINCT FROM blocked_locks.DATABASE
     AND blocking_locks.relation      IS NOT DISTINCT FROM blocked_locks.relation
     AND blocking_locks.page          IS NOT DISTINCT FROM blocked_locks.page
     AND blocking_locks.tuple         IS NOT DISTINCT FROM blocked_locks.tuple
     AND blocking_locks.virtualxid    IS NOT DISTINCT FROM blocked_locks.virtualxid
     AND blocking_locks.transactionid IS NOT DISTINCT FROM blocked_locks.transactionid
     AND blocking_locks.classid       IS NOT DISTINCT FROM blocked_locks.classid
     AND blocking_locks.objid         IS NOT DISTINCT FROM blocked_locks.objid
     AND blocking_locks.objsubid      IS NOT DISTINCT FROM blocked_locks.objsubid
     AND blocking_locks.pid != blocked_locks.pid
JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid
WHERE NOT blocked_locks.GRANTED;

Result:
-[ RECORD 1 ]-------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
blocked_pid                           | 28526
blocked_user                          | user
blocking_pid                          | 29151
blocking_user                         | user
blocked_statement                     | UPDATE "table_in_question" SET "response" = $1, "status_id" = $2, "updated_at" = $3 WHERE "table_in_question"."id" = $4 current_statement_in_blocking_process | INSERT INTO "table_in_question" ("params_json", "test_email", "callback_url", "mail_templates_version_id", "template_name", "queue_time", "send_time", "email_ids", "status_id", "created_at", "updated_at", "uuid") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING "id"
-[ RECORD 2 ]-------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
blocked_pid                           | 28526
blocked_user                          | user
blocking_pid                          | 31778
blocking_user                         | user
blocked_statement                     | UPDATE "table_in_question" SET "response" = $1, "status_id" = $2, "updated_at" = $3 WHERE "table_in_question"."id" = $4 current_statement_in_blocking_process | UPDATE "table_in_question" SET "params_json" = $1, "updated_at" = $2 WHERE "table_in_question"."id" = $3

Queries seemed to be getting blocked by each other rather than autovacuum. Although, I didn't see anything cyclic in nature here.
The table in question is one of the larger tables on the database. Although this isn't too large considering today's standards.
SELECT relname as "Table",
       pg_size_pretty(pg_total_relation_size(relid)) As "Size",
       pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid)) as "External Size"
FROM pg_catalog.pg_statio_user_tables
ORDER BY pg_total_relation_size(relid) DESC;

Result:
Table              |  Size   | External Size
---------------------------------+---------+---------------
table_in_question  | 37 GB   | 10 GB

Postgres version:
select version();
     version
------------------------
PostgreSQL 9.6.6 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-16), 64-bit


text:
Q: How to copy 2d String array? I'm having difficulty copying string array values into a new string array.
For example:
String[][] array = new String[3][2];
array[0][0] = "hello";
array[0][1] = "1";
array[1][0] = "guys";
array[1][1] = "2";
array[2][0] = "good ";
array[2][1] = "3";

array = new String [5][2];
all the value in the first array to be copied
array[3][0] = "";
array........;

I tried this method but it keeps me giving null pointer issues whenever I want to insert a new value.
String[][] array = new String[3][2];
array[0][0] = "olo";
array[0][1] = "ada ";
array[1][0] = "apa";
array[1][1] = "dengan";
array[2][0] = "si ";
array[2][1] = "carlo";

String[][] newArray = new String[5][2];
newArray = Arrays.copyOf(array, 5);
array = new String[5][2];
array = Arrays.copyOf(newArray, 5);
array[3][0] = "lo";
array[3][1] = "gw";
array[4][0] = "end";
array[4][1] = "ennnnnd";

for (int r = 0; r < array.length; r++) {
    for (int c = 0; c < array[r].length; c++) {
        System.out.print(" " + array[r][c]);
    }
    System.out.println("");
}

How can I copy this 2d string array?

A: Java has a built in function called arraycopy that can do this for you without a double for loop.  Much more efficient.

A: First of all the newer array has more elements that source array so decide what you want to do about it. Also if old array is called array call the new array by a different name say newarray.
for ( int i = 0; i < 3; ++i )
{
  for( int j = 0; j < 2; ++i )
  {
      newarray[i][j] = array[i][j];
  }
}

A: You can use Arrays.copyOfRange(String param, fromIndex, toIndex)


text:
Q: depth first search with javascript: cannot get the record I want I have some difficulty to understand how recursion works. I have this literal object:
let obj = {
    pizze:{
        type:"pizze",
        typeOne:{
            title: "Pizze Rosse",
            data:[
                {id:1,type:"pizza",name:"Margherita",price:4,ingredients:["pomodoro","mozzarella"],quantity:0,inventory:100},
                {id:2,type:"pizza",name:"Marinara",price:3.5,ingredients:["aglio","pomodoro"],quantity:0,inventory:100},
                {id:3,type:"pizza",name:"Salsiccia e funghi",price:6,ingredients:["salsiccia","funghi","mozzarella","pomodoro"],quantity:0,inventory:100},
                {id:4,type:"pizza",name:"Carciofi",price:4,ingredients:["mozzarella","carciofi","pomodoro"],quantity:0,inventory:100},
            ]
        },
        typeTwo:{
            title:"Pizze Bianche",
            data:[
                {id:5,type:"pizza",name:"Gorgonzola e noci",price:5.50,ingredients:["gorgonzola","noci","mozzarella"],quantity:0,inventory:100},
                {id:6,type:"pizza",name:"Stracchino e rucola",price:4.50,ingredients:["stracchino","rucola","basilico"],quantity:0,inventory:100},
                {id:7,type:"pizza",name:"Tartufo e salsiccia",price:8,ingredients:["tartufo","salsiccia","mozzarella"],quantity:0,inventory:100},
                {id:8,type:"pizza",name:"Zucchine e Gamberi",price:5,ingredients:["zucchine","gamberi","pomodorini"],quantity:0,inventory:100},
            ]

        }
    },
    primiPiatti:{
        type:"primiPiatti",
        typeOne:{
            title: "Primi di carne",
            data:[
                {id:12,type:"primiPiatti",name:"Lasagne alla Bolognese",price:9,quantity:0,inventory:100},
                {id:13,type:"primiPiatti",name:"Spaghetti alla carbonara",price:14,quantity:0,inventory:100},
                {id:14,type:"primiPiatti",name:"pennette all'amatriciana",price:10,quantity:0,inventory:100},
                {id:15,type:"primiPiatti",name:"paccheri salsiccia e funghi",price:12,quantity:0,inventory:100},
            ]
        },
        typeTwo:{
            title:"Primi di pesce",
            data:[
                {id:16,type:"primiPiatti",name:"spaghetti allo scoglio",price:8.50,quantity:0,inventory:100},
                {id:17,type:"primiPiatti",name:"zuppa di cozze",price:14.50,quantity:0,inventory:100},
                {id:18,type:"primiPiatti",name:"pappardelle asparagi e gamberi",price:18,quantity:0,inventory:100},
                {id:19,type:"primiPiatti",name:"lasagne al salmone",price:15,quantity:0,inventory:100},
            ]

        },
        typeThree:{
            title:"Primi vegetariani",
            data:[
                {id:20,type:"primiPiatti",name:"Potage di cavolfiori e porri",price:15.50,quantity:0,inventory:100},
                {id:21,type:"primiPiatti",name:"lasagne con patate e taleggio",price:14.50,quantity:0,inventory:100},
                {id:22,type:"primiPiatti",name:"crespelle formaggio e zucca",price:12,quantity:0,inventory:100},
                {id:23,type:"primiPiatti",name:"cannelloni coste e noci",price:15,quantity:0,inventory:100},
            ]

        },
    },
    secondiPiatti:{
        type:"secondiPiatti",
        typeOne:{
            title: "secondi di carne",
            data:[
                {id:24,type:"secondiPiatti",name:"agnello al forno con patate",price:9,quantity:0,inventory:100},
                {id:25,type:"secondiPiatti",name:"arrosto di vitello",price:12.5,quantity:0,inventory:100},
                {id:26,type:"secondiPiatti",name:"coniglio al forno",price:11,quantity:0,inventory:100},
                {id:27,type:"secondiPiatti",name:"vitello al tonno",price:12.5,quantity:0,inventory:100},
            ]
        },
        typeTwo:{
            title:"secondi di pesce",
            data:[
                {id:28,type:"secondiPiatti",name:"seppie con piselli",price:8.5,quantity:0,inventory:100},
                {id:29,type:"secondiPiatti",name:"orata al forno",price:14.5,quantity:0,inventory:100},
                {id:30,type:"secondiPiatti",name:"filetto di merluzzo al forno",price:18.5,quantity:0,inventory:100},
                {id:31,type:"secondiPiatti",name:"calamari ripieni",price:16,quantity:0,inventory:100},
            ]

        },
        typeThree:{
            title:"secondi vegetariani",
            data:[
                {id:32,type:"secondiPiatti",name:"parmigiana di melanzane",price:9.50,quantity:0,inventory:100},
                {id:33,type:"secondiPiatti",name:"polpette di verdure",price:7.50,quantity:0,inventory:100},
                {id:34,type:"secondiPiatti",name:"frittata di asparagi",price:7,quantity:0,inventory:100},
                {id:35,type:"secondiPiatti",name:"burger di patate",price:12,quantity:0,inventory:100},
            ]

        },

    },

}

And I want to implement a system that returns to me a specific record stored in the data array, retrieving by his ID.
Now, since the data arrays are stored at the end of the tree, I have thought to use deepth first search
I not use much recursion, so I'm having some trouble with that.
My first attempt was this, I put a counter so I can see what happens and seems that yes, is a deepth first search:
let i = 0;

let search = (where, haystack,id,record=null) =>{
        Object.keys(haystack).forEach(key=>{ // loop over the key of the main object
        console.log("point",i,key)
        if(key === where){ //if key === data
          console.log("inside the data",i)
                    let record = haystack[key].find(rec => rec.id === id ); //find the record I want
                    if(record){ // if exist
                        return record   //return it
                    }
                  }
       else if(typeof haystack[key] === 'object'){ // else repeat the procedure with subobject
                    return search(where, haystack[key],id,record);
                  }
      })
      i++
      return false
    }

console.log(search('data',obj,23))

I start from 'pizze' object and I go down until the data stored in typeOne object, then I go to the data stored in typeTwo and so on...
But this method not works, I get false everytime... I think I'm not understand yet what happens there, how works the call stack in a recursion function..
Also my goal is: when you find the record, return it and exit. This is not possible with ForEach, so I opted for a classic for loop with a different strategy:
    let record;

    let search2 = (where, haystack,id) =>{
    let keys = Object.keys(haystack);
    for(let i=0; i<keys.length;i++){
        if(keys[i] === where){
            record = haystack[keys[i]].find(rec => rec.id === id );
            if(record){
                console.log(record) // I have the record assigned
                break
            }
        }
       if(typeof haystack[keys[i]] === 'object'){
        search2(where, haystack[keys[i]],id,record)
        }
    }
    return false
}

    console.log(search2('data',obj,24)) // return false but is ok
    console.log("record: ",record) //undefined

As you can see, I tried with declaring a variable in the outer scope, when I found the object I want inside the loop, I assign it to the record and then I I exit from the loop, but record is still undefined.
If I do a console.log() inside the most inner if, I actually have the value I want printed out on the console. But then seems the break not working
What am I missing? Can someone explain me why my two methods are not working and, most important, what happens during recursion?
many thanks

A: Maybe use an iterator to simplify it:
  function* flatPizza() {
     for(const type of ["typeOne", "typeTwo", "typeThree"])
       yield* obj.pizze[type].data.values();
  }

 for(const el of flatPizza())
   if(el.id === 23) return el;

Or in a more general case:
   function* flatIterate(sth) {
     if(Array.isArray(sth)) {
          for(const el of sth)
             yield* flatIterate(el);
     } else if(typeof prop === "object") {
           yield obj;
           yield* flatIterate(Object.values(obj));
     }
  }

  for(const el of flatIterate(obj))
    if(el.id === 23) return el;

A: OK, finally I think I get what was the problem, in the first function:
if(key === where){

     let record = haystack[key].find(rec => rec.id === id );
                    if(record){
                        return record
                    }
                  }

Record is constantly reassigned I think, so what I need is something that keep track the result, for example an array:
let search = (where, haystack,id,found=[]) =>{
        Object.keys(haystack).forEach(key=>{
        if(key === where){
                    let record = haystack[key].find(rec => rec.id === id );
                    if(record){
                        found.push(record)
                        return found    //return found to the next caller
                    }
                  }
       else if(typeof haystack[key] === 'object'){
                    return search(where, haystack[key],id,found);
                  }
      })

      return found[0] //finally return the record I want
    }

If the record exist inside the collection, is pushed into the found array, that is passed as argument to the next caller, but the next caller doesn't reassign it, simply upgrade the found array and return it to the next caller.
I hope I understood was what the problem in the first case. Someone can confirm?
Of course in this case I have to iterate over the entire collection, but at least I think I understand why the first search function was not working


text:
Q: How to end an IF block when there is no ELSE clause and continue with the indent levels While iterating through a list, I keep count and if it's an even item, I would like my output to be:
.row
  .col-md-6
     ...xxx...
       ...yyy...

else it should just be:
  .col-md-6  //note the indent is to be same as above, ie child of .row
     ...xxx...
       ...yyy...

The output should be repeating blocks of:

     ..

     ..

My intended script is:
if even
  .row
end if  //is there such a statement?
    .col-md-6
      ...xxx...
        ...yyy...

What is the proper way of writing it without resorting to an else block and repeating its contents in the even block as well?

A: You can render 2 items on each loop, only rendering at all when it is even. Something like
for foo, i in bar
    if i % 2 === 0
        .row
            .col-md-6
                // whatever you want to do with foo

             - var foo2 = bar[i+1]
             if foo2
                .col-md-6
                    // whatever you want to do with foo2

A: To break out of an if statement, just resume the indentation at the same level as the if statement in question. That will let the code proceed after the if statement.
- var even = true;
if even
    .row
.col-md-6
    ...xxx...
        ...yyy...

Produces:

</row>

    <xxx>
        <yyy></yyy>
    </xxx>

If even is false,
</row> is omitted from the output, but the rest of it still outputs.

A: Although Joe Lissner's answer is correct it does contain code duplication because you have to specify what you want to do with the item, twice per row. His answer also doesn't scale well for situations where you need more than two items per row.
Instead of using the [i+1] structure by Joe Lissner's I would suggest using a second loop to find all the items that have to fall into this row. This can be done using the following pattern:
- var itemsPerRow = 2; // This can be any positive number
each unused, i in list
  if (i % itemsPerRow == 0)
    .row
      each item, j in list
        if (j - i >= 0 && j -i < itemsPerRow)
          .col-md-6
             .. What you want to do with -item- ..

The line if (j - i >= 0 && j -i < itemsPerRow) makes sure that only the items that actually fall into that row get render.
This avoids code duplication because you only have to type .. What you want to do with -item- .. once.
The result looks like this
.row
  .col-md-6
  .col-md-6
.row
  .col-md-6
  .col-md-6
.row
  .col-md-6
  .col-md-6


text:
Q: How to differentiate AnyObject (or Int) type in XCode 9 - new Swift compiler I need to check the type of AnyObject that was given an Int (or Int16 or UInt8) value, i.e.
In Xcode 8 - switching over the object, using cases:
is Uint8, is Int16, is Int works pefrect.
In Xcode 9 - It always enter the first case that is possibly true.
Here is a code sample for Playground:
var t1: AnyObject?
var t2: AnyObject?

t1 = 30 as AnyObject
t2 = Int16(30) as AnyObject

if let obj1 = t1 {
    switch obj1 {
    case is UInt8:
        print("UInt8")
    case is Int16:
        print("Int16")
    case is Int:
        print("Int")
    default:
        break
    }
}

if let obj2 = t2 {
    switch obj2 {
    case is UInt8:
        print("UInt8")
    case is Int16:
        print("Int16")
    case is Int:
        print("Int")
    default:
        break
    }
}

XCode 8 playground console prints:
Int
Int16
XCode 9 playground console prints:
UInt8
UInt8
A. Can someone explain why, and/or attached any documeted reference regarding this?
B. Would be happy I someone can help me acheive same functionality in XCode 9.
Thanks.

A: Since Swift 3 all numeric types are Any, not AnyObject
var t1: Any?
var t2: Any?

t1 = 30 as Any
t2 = Int16(30) as Any
...

This solves the issue.
I suppose casting to AnyObject bridges the type to NSNumber which matches any case.


text:
Q: How to disable "Missing XML comment" warning for auto generated code in Windows Store app? I get numerous compiler warnings CS1591 Missing XML comment for publicly visible type or member ... in my Universal Windows Store App project in VS2015 for auto generated code files, e.g.

*

*App.g.cs

*App.g.i.cs

*SomePage.g.cs

*SomePage.g.i.cs

I know of the different approaches available to fix these warnings from showing up, but I can't get the specific approach mentioned in Quoc Lam's blog to work. The other possible solutions don't work for me, so what do I have to do make it work for my project?
There are a couple of things I still don't understand:

*

*Where do I have to place the code lines containing the new target? I tried to put them into my Windows Phone project file (.csproj), but XamlGeneratedCodeFiles always seems to be empty (judging from diagnostic build output)

*I also tried setting the AftetTargets attribute from XamlMarkupCompilePass1 to XamlMarkupCompilePass2, but still the same as above

*Where is XamlGeneratedCodeFiles actually filled with data? Or do I misunderstand something?

*Is XamlGeneratedCodeFiles the right variable to access?

I also looked at several of the msbuild .target files but got completely lost. Please let me know if you need further information that is still missing form this post.
Update
In addition to the accepted answer I post the working solution for my project as it wouldn't fit into a comment:
<Target Name="CodeWarningRemover" AfterTargets="MarkupCompilePass2">
    <ItemGroup>
        <CSFiles Include="**\*.g.cs;**\*.g.i.cs" />
    </ItemGroup>
    <Message Text="CSFiles: '@(CSFiles)'" />
    <Exec Command="for %%f in (@(CSFiles)) do echo #pragma warning disable > %%f.temp" />
    <Exec Command="for %%f in (@(CSFiles)) do type %%f >> %%f.temp" />
    <Exec Command="for %%f in (@(CSFiles)) do move /y %%f.temp %%f" />
</Target>

A: You could load the list of files to modify in the target wit ItemGroup :
<Target Name="CodeWarningRemover" AfterTargets="FindTheTagertToOverwrite">
    <ItemGroup>
        <Content Include="*.g.cs" />
        <Content Include="*.g.i.cs" />
    </ItemGroup>
    <Exec Command="for %%f in (@(Content)) do echo #pragma warning disable > %%f.temp" />
    <Exec Command="for %%f in (@(Content)) do type %%f >> %%f.temp" />
    <Exec Command="for %%f in (@(Content)) do copy /y %%f.temp %%f" />
</Target>

You need to find the target to overwrite : named "FindTheTagertToOverwrite" in the sample. It's the target used by the Universal Windows Store App project and it's build process or your custom build process. Sorry, I'm not familliar with this project
You could try with MarkupCompilePass1

A: The "CodeWarningRemover" worked for my UWP projects until recently, when I created a solution configuration with a name that contained spaces. After some digging into MSBuild I was able to figure out the following:
<Target Name="PragmaWarningDisablePrefixer" AfterTargets="MarkupCompilePass2">
    <ItemGroup>
        <GeneratedCSFiles Include="**\*.g.cs;**\*.g.i.cs" />
    </ItemGroup>
    <Message Text="CSFiles: @(GeneratedCSFiles->'"%(Identity)"')" />
    <Exec Command="for %%f in (@(GeneratedCSFiles->'"%(Identity)"')) do echo #pragma warning disable > %%f.temp && type %%f >> %%f.temp && move /y %%f.temp %%f" />
</Target>


text:
Q: IBM Watson Tone Analyzer API call in C# I was trying to write a post API call to watson tone analyzer service in C#. It seems that the way to authenticate a user was changed lately from username and password to an api key.
I was trying to pass the apikey through "Authorization" header, or through a header called "apikey".. In both cases I received error 401 Unauthorized.. The other header I was using is Content-Type sets to application/json..
This calls doesn't work in a .net project nor in postman.
How can I send an API request using C#, how shell I pass the api key, and what headers should I use ?
This is the code I tried(This code returns an error of internal server error 500, while the tests I did with postman returns 401 Unauthorized):
   HttpClient client = new HttpClient();
    string baseURL;
    string apikey= "****************";

    baseURL = "https://gateway-lon.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21";

string postData = "{\"text\": \"" + "hi hello" + "\"}";

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("apikey", apikey);

var response = client.PostAsync(baseURL, new StringContent(postData, Encoding.UTF8, "application/json")).Result;

Console.WriteLine(response);

The error I am receiving:
StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Mime-Version: 1.0
  Connection: close
  Date: Sun, 17 Feb 2019 11:37:53 GMT
  Server: AkamaiGHost
  Content-Length: 177
  Content-Type: text/html
  Expires: Sun, 17 Feb 2019 11:37:53 GMT
}

A: For this to work you need to do a proper basic authorization (see Authorization section at https://cloud.ibm.com/apidocs/tone-analyzer). According to RFC 7617 basic authorization means the authorization scheme is Basic and the authorization parameter is username:password in Base64 encoding.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("apikey:" + apikey)));

The following code worked for me:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("apikey:" + apikey)));

string postData = "{\"text\": \"" + "I am happy it finally worked" + "\"}";
var response = client.PostAsync("https://gateway-lon.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21", new StringContent(postData, Encoding.UTF8, "application/json")).Result;
var responseContent = response.Content.ReadAsStringAsync().Result;

Which returned {"document_tone":{"tones":[{"score":0.956143,"tone_id":"joy","tone_name":"Joy"},{"score":0.620279,"tone_id":"analytical","tone_name":"Analytical"}]}}.
As a side note, I initially used the Frankfurt gateway (gateway-fra) and when I used my apikey for this gateway on the London gateway (gateway-lon) I also received server error 500 (Internal server error). For other gateways I received error 401 (Unauthorized), because the apikeys seem to be per service and gateway/location. After I deleted my ToneAnalyzer service and set up an new one this time for the London gateway, it worked. So I guess, IBM's authorization server or the Akamai load balancer they are using is a little bit wonky when you use an apikey for one gateway on another gateway.


text:
Q: type '(dynamic) => NotificationModel?' is not a subtype of type '(dynamic) => NotificationModel' of 'f' This code is having problem when I build my app. It can't convert datas in first run but after I restart the app, this part works fine. I don't get it.
List<T>? fromJsonList(dynamic jsonList) {
    try {
      return jsonList?.map<T>((dynamic json) => fromJson(json))?.toList();
    } catch (e) {
      debugPrint("fromJsonList_Err: ${e.toString()}");
      return null;
    }
  }


text:
Q: How to get chunk {scripts} in html-webpack-plugin i faced one problem. I need to build custom index.html files with angular. I decided to use angular-builders and html-webpack-plugin. It works fine, but one chunk doesn't includes in html-webpack-plugin result.
There is my configs:
custom-webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    plugins: [
        new HtmlWebpackPlugin({
          inject: false,
          template: '../Views/Documents/_LoaderTemplate.cshtml',
          filename: '../../../Views/Documents/_AngularLoader.cshtml'
        })
      ]
};

angular.json
      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./custom-webpack.config.js"
            },
            ...
            "scripts": [
              "src/app/division/division-draw/lines.js",
              "src/app/division/division-draw/mouse_control.js",
              "src/app/division/division-draw/Screen.js"
              ]
          },
          ...

I have template for html-webpack-plugin
<%= JSON.stringify(htmlWebpackPlugin) %>

<% for (var chunk in htmlWebpackPlugin.files.chunks) { %>
<script src="<%= htmlWebpackPlugin.files.chunks[chunk].entry %>"></script>
<% } %>

And result of build doesn't contains scripts.js, but result scripts of building have it.
chunk {main} main.js, main.js.map (main) 175 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 338 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {scripts} scripts.js, scripts.js.map (scripts) 33.1 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 169 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 6.78 MB [initial] [rendered]

I use package.json like
    "html-webpack-plugin": "^3.2.0",
    "@angular-devkit/build-angular": "0.13.9",
    "@angular-builders/custom-webpack": "7.5.2",
    "@angular/cli": "~7.0.3",
    "@angular/compiler-cli": "~7.0.0",
    "@angular/common": "^7.0.0",
    "@angular/compiler": "^7.0.0",
    "@angular/core": "^7.0.0",
    "@angular/forms": "^7.0.0",
    "@angular/http": "~7.0.0",
    "webpack": "^4.40.0",
    "webpack-cli": "^3.3.8"

I want include all builded scripts (by angular-cli) to my result output file filename: '../../../Views/Documents/_AngularLoader.cshtml'

A: try to use <%= htmlWebpackPlugin.tags.bodyTags %>


text:
Q: Generate Matriculation Number Involvement: Oracle database and C# (Windows Forms)
I have a two separate database tables: Faculty and Department, each having name and numeric ID Column. To assign a matriculation number to each student record added to my STUDENT_REC table, I used the last 2 digits of year, faculty_id and department_id using C# code to fetch records from my Faculty and Department tables.
Example: 18- year is constant, 10- faculty of science and 38 - department of geology are selected from combo box and automatically generates the number in my Windows Form ( matric number will be 181038. But now I want it to add 001/002/etc to every added record.
How do I add such serial numbering to the end of each number being unique and distinct to EACH department...serially?


text:
Q: How to convert 3-D coordinates into 2-D coordinates in computer graphics I am doing a program to display a three dimensional cube on the screen. I am doing the program in DOSBOX. My algorithm is as follows:
1. I take the length of the side as input from the user
2.I draw the cube with the initial coordinate prefixed as (140,280,0)
3. I convert the 3-D representation to 2-D by using the formula x=x+(z/sqrt(6))
The following is my code:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<math.h>

float idmat[4][4],inpmat[4][8];

void main()
{
int gd=DETECT,gm;
float s,temz,sqp,tx1,ty1,tz1;
int i,tz,j,side,d2mat[3][8],tx,ty;
for(i=1;i<=4;i++)
{for(j=1;j<=4;j++)
idmat[i][j]=0;
}

 for(i=0;i<4;i++)
 {for(j=0;j<4;j++)
 {if(i==j)
 {
 idmat[i][j]=1;
 }
 }}

 printf("Enter the side of the cube\n");
 scanf("%d",&side);
 inpmat[1][1]=140;
 inpmat[2][1]=280;
 inpmat[3][1]=0;
 tx=140;
 ty=280;
 tz=0;
 tx=tx+side;
 inpmat[1][2]=tx;
 inpmat[2][2]=ty;
 inpmat[3][2]=tz;
 ty=ty+side;
 inpmat[1][3]=tx;
 inpmat[2][3]=ty;
 inpmat[3][3]=0;
 tx=inpmat[1][1];
inpmat[1][4]=tx;
inpmat[2][4]=ty;
inpmat[3][4]=tz;
tz=tz+side;
printf("tz is %d ",tz);
inpmat[1][5]=tx;
inpmat[2][5]=ty;
inpmat[3][5]=tz;
tx=tx+side;
inpmat[1][6]=tx;
inpmat[2][6]=ty;
inpmat[3][6]=tz;
ty=ty+side;
inpmat[1][7]=tx;
inpmat[2][7]=ty;
inpmat[3][7]=tz;
tx=inpmat[1][1];
inpmat[1][8]=tx;
inpmat[2][8]=ty;
inpmat[3][8]=tz;
for(i=1;i<=8;i++)
inpmat[4][i]=1;

sqp=sqrt(6);
printf("The sqrt is %f \n",sqp);
for(i=1;i<=8;i++)
{
    tx1=inpmat[1][i];
    printf("%f ",inpmat[1][i]);
    ty1=inpmat[2][i];
   printf("%f lala\n ",inpmat[3][i]);

    tz1=inpmat[3][i];
     printf("prr %f \n",tz1);
    temz=tz1/sqrt(6);
      printf("temz is %f \n",temz);
    tx1=tx1+temz;
    ty1=ty1+temz;
    d2mat[1][i]=tx1;
      // printf("%f ",d2mat[1][i]);
    d2mat[2][i]=ty1;
    //  printf("%f ",d2mat[2][i]);
    d2mat[3][i]=1;
      //    printf("%f \n",d2mat[3][i]);
  }

  initgraph(&gd,&gm,"C:\\TurboC3\\BGI\\");
line(d2mat[1][1],d2mat[2][1],d2mat[1][2],d2mat[2][2]);
line(d2mat[1][2],d2mat[2][2],d2mat[1][3],d2mat[2][3]);
line(d2mat[1][3],d2mat[2][3],d2mat[1][4],d2mat[2][4]);
line(d2mat[1][4],d2mat[2][4],d2mat[1][1],d2mat[2][1]);
//printf("%f %f %f %f ",inpmat[1][4],inpmat[2][4],inpmat[1][6],inpmat[2][6]);
line(d2mat[1][5],d2mat[2][5],d2mat[1][6],d2mat[2][6]);

line(d2mat[1][6],d2mat[2][6],d2mat[1][7],d2mat[2][7]);
line(d2mat[1][7],d2mat[2][7],d2mat[1][8],d2mat[2][8]);
line(d2mat[1][8],d2mat[2][8],d2mat[1][5],d2mat[2][5]);

line(d2mat[1][5],d2mat[2][5],d2mat[1][1],d2mat[2][1]);
line(d2mat[1][6],d2mat[2][6],d2mat[1][2],d2mat[2][2]);
line(d2mat[1][8],d2mat[2][8],d2mat[1][4],d2mat[2][4]);
line(d2mat[1][7],d2mat[2][7],d2mat[1][3],d2mat[2][3]);

getch();
//closegraph();
//restorecrtmode();
}

When the figure is drawn on the screen, what i get is a cuboid instead of a perfect cube. Can somebody help me with this situation? Thanks in advance.

A: Thanks to all those looked into my question.I found the mistake in my program.
Before I enter inpmat[1][7],inpmat[2][7],inpmat[3][7], I was supposed to do ty=ty-side so that the y coordinate moves back to the initial position. Instead I did ty=ty+side and when drew the figure. When I saw that the resultant figure was wrong, I tried editing the code for drawing the lines accordingly instead of looking into the above section of the code. I am sorry for waiting your valuable time.


text:
Q: How to handle nested each with input type in Jquery I tried to look after a similar problem but couldn't find any here. So here is my problem. I have a structure with multiple div. Each div have a class name 'testClass'. I need to fetch the attributes of all input types, button
Here is my code,

    /* Few Code */
    <input type="text" id="txt1" />
   <input type="text" id="txt21" />
    /* Few Code */
    <button id="btn1">Button1</button>

    /* Few Code */
    <input type="text" id="txt2" />
   <input type="text" id="txt22" />
    /* Few Code */
    <button id="btn2">Button2</button>

    /* Few Code */
    <input type="text" id="txt3" />
   <input type="text" id="txt23" />
    /* Few Code */
    <button id="btn3">Button3</button>

I have tried following
$("div .testClass").each(function() {

/* Some code present */

      $(this).find('input,button').each(function(){

      });
});

but it is not working. How can i select input types from div class testClass after the first each statement.
Could you help? Thanks.

A: This should work:
$("div.testClass").find(":input").each(function() {
    var type = $(this).attr('type');
    // Do something with the returned type
});

If you just need the buttons, set the find value to ':button'

A: Maybe you should try this:
$("div.testClass :input").each(function() {
    var type = $(this).attr('type');
});


text:
Q: Odoo display images alternative Odoo ORM has Binary type field which can hold images. The problem with these images is that they are delivered with HTML as base64 encoded. These add up to the HTML size and can't be cached or delivered via CDN.
I need to add images uploading to a module. These images will then be displayed on the website. Is there an alternative approach to this? Model code below:
class BannerImage(models.Model):
    _name = 'banner.image'
    _description = 'Banner Image'

    image_desktop = fields.Binary('Desktop Image', attachment=True)
    image_mobile = fields.Binary('Mobile Image', attachment=True)

    start_date = fields.Date("Start Date")
    end_date = fields.Date("End Date")

    action = fields.Char("URL")
    desc = fields.Text("Additional Description")
    banner = fields.Many2one('banner.banner', "Banner")

View for backend declared as below:
<record id="action_view_banner_images" model="ir.actions.act_window">
  <field name="name">Banner Images</field>
  <field name="res_model">banner.image</field>
  <field name="view_mode">tree,form</field>
</record>

These are used in HTML template as below:

    <t t-foreach="banners.images" t-as="banner_image">

    </t>

Is there another way to call these images, probably using URLs?

A: you can use image "t-attf-src=/web/binary/image?model=ir.attachment&field=datas&id=(your img ID)" instead of "t-attf-src="data:image/*;.... "


text:
Q: Terraform local-exec to pass new resource( not hard-coding) I'm executing a bash script using terraform. My null_resource configuration code is given below
resource "null_resource" "mytest" {

triggers = {
    run = "${timestamp()}"
 }

 provisioner "local-exec" {
  command = "sh test.sh"

 }
 }

Let us take git repo as an example resource. I'm doing  bunch of operations using the batch script on the resource. This resource names are passed using terraform.tfvars
resource_list = ["RS1","RS2","RS3","RS4"]

If I want to add a new repo named RS5 then I can update the the above list by adding RS5 to it.
How I will pass the new resource name to the batch script. Here I'm not looking to hard code the parameter as given below
sh test.sh "RS5"

How i will pass the most recent resource to the batch script?

A: Use for_each to execute the batch script once per resource in the resource_list variable
resource "null_resource" "mytest" {
  for_each = toset(var.resource_list)

  # using timestamp() will cause the script to run again for every value on
  # every run since the value changes every time.
  # you probably don't want that behavior.

  # triggers = {
  #  run = "${timestamp()}"
  # }

  provisioner "local-exec" {
    command = "sh test.sh ${each.value}"
  }
}

When you run this the first time it will execute the script once for each of the resources in resource_list. Then the terraform state file will be updated to know what has already run, so any subsequent runs will only include new items added to resource_list.


text:
Q: How can I convert the following data into LOOP I am trying to convert the following into loop but whatever I tried all in vain
I want someone help me to convert this type of data into loop.
ArrayList<String> parentList = new ArrayList<>();
        ArrayList<ArrayList> childListHolder = new ArrayList<>();

        parentList.add("Parent1");
        parentList.add("Parent2");
        parentList.add("Parent3");

        ArrayList<String> childNameList = new ArrayList<>();
        childNameList.add("Child1");
        childNameList.add("Child2");
        childNameList.add("Child3");

        childListHolder.add(childNameList);

        childNameList = new ArrayList<>();
        childNameList.add("Child4");
        childNameList.add("Child5");
        childNameList.add("Child6");

        childListHolder.add(childNameList);

        childNameList = new ArrayList<>();
        childNameList.add("Child7");
        childNameList.add("Child8");
        childNameList.add("Child9");

        childListHolder.add(childNameList);

A: No need for loop(s) here, also don't use ArrayList as a raw-type and prefer the List interface. Use Arrays.asList(T...) to generate your List(s). Like,
List<List<String>> childListHolder = new ArrayList<>();
List<String> parentList = Arrays.asList("Fruits & Vegetables",
        "Beverages & Health", "Home & Kitchen");
childListHolder.add(Arrays.asList("Apple", "Mango", "Banana"));
childListHolder.add(Arrays.asList("Red bull", "Maa", "Horlicks"));
childListHolder.add(Arrays.asList("Knife", "Vessels", "Spoons"));

A: The equivalent of your code with loops is this:
ArrayList<String> parentList = new ArrayList<>();
ArrayList<ArrayList> childListHolder = new ArrayList<>();

for (int i = 1; i <= 3; i++) {
    parentList.add("Parent" + i);

    ArrayList<String> childNameList = new ArrayList<>();
    for (int j = 1; j <= 3; j++) {
        childNameList.add("Child" + (3 * (i - 1) + j));
    }
    childListHolder.add(childNameList);
}


text:
Q: Finding the line of reflection and two points of the image with the coordinates of pre-image and one coordinate of image I am having trouble with a coordinate geometry question:

Triangle ABC has been reflected. The pre-image has vertices at
A(2, -1), B(4, 0), and C(3, -3). The image has a vertex A' at (-1, 0).
Where are B' and C' located and what is the equation for the line
of reflection?

I know how to find the line of reflection, but to find the midpoints you would need more than one point. Is guess-and-check the only method to solving this, or is there a formula that will help?

A: We start with the perpendicular bisector of $\overline{AA'}$, as per stewbasic's comment. This line passes through the midpoint $M=(A+A')/2 = (1/2,-1/2)$ and has a the vector $\mathbf n=A-A'=(3,-1)$ for a normal, so an equation for this line is $\mathbf n\cdot\mathbf x=\mathbf n\cdot\mathbf M$, or $3x+y=2$.
We can now find the images of the other two points using the formula for reflection in a line through the origin with normal $\mathbf n$: $$\mathbf v'= \mathbf v-2{\mathbf n\cdot\mathbf v\over\mathbf n\cdot\mathbf n}\mathbf n.$$ Our line of reflection doesn't pass through the origin, though, so we'll have to do a couple of translations to get the right formula. The reflection formula for our line is thus $$\begin{align}\mathbf v' &= (\mathbf v-M)-2{\mathbf n\cdot(\mathbf v-M)\over\mathbf n\cdot\mathbf n}\mathbf n+M\\ &= \mathbf v-2{\mathbf n\cdot(\mathbf v-M)\over\mathbf n\cdot\mathbf n}\mathbf n.\end{align}$$

A: As @stewbasic very rightly stated, the line of reflection that sends $A$ to $A'$ is the perpendicular bisector of the line $AA'$ (that is, the line connecting $A$ and $A'$).
The line $AA'$ has gradient $m_1 = \frac{-1 -0}{2-(-1)}= \frac{-1}{3}$. Thus it's perpendicular bisector will be perpendicular to this gradient so will have gradient $m = \frac{-1}{m_1} = 3$. And since it is a bisector, it must pass through the midpoint of the line $AA'$. This midpoint is at: $ x = \frac{(-1)+2}{2} = \frac{-1}{2}$ and $y= \frac{0 + -1}{2} = \frac{-1}{2}$.
So the perpendicular bisector is of the form $y = mx+c$ where $m = 3$ and the line passes through the point $(\frac{-1}{2}, \frac{-1}{2})$. We can thus solve for c giving the line of reflection:
  $$y = 3x - 2$$
Can you complete the rest from here?


text: Q: Is it possible to install without a CD or USB drive? I've got a friend who wants to try Ubuntu on his netbook, but doesn't have a USB drive he can use, and of course the netbook doesn't have a CD drive. Is it possible for him to install Ubuntu?


text:
Q: how to keep alignment while moving elements

$('.box').on('click', function(){
$('.act').removeClass('act');
$(this).addClass('act');
});

$('button').on('click', function(){
$('.act').insertAfter($('.act').next());
});
.parent{
text-align:justify;
text-align-last:justify;
background:lightgreen;
}

.box{
display:inline-block;
width:20%;
height:25px;
background:orange;
}

.act{
background:skyblue;
}

1

1

1

1

<button>CLICK</button>

Click on the first box to make it active.
Then click on the button to move it right.
You see that alignment is lost, i.e. there is no spaces between boxes.
How to prevent this?

A: Instead of using insertAfterafter, which will mess up the justify style, just switch the location between the divs:

$('.box').on('click', function(){
$('.act').removeClass('act');
$(this).addClass('act');
});

$('button').on('click', function(){

    div1 = $('.act');
    div2 = $('.act').next();

    tdiv1 = div1.clone();
    tdiv2 = div2.clone();

    if(!div2.is(':empty')){
        div1.replaceWith(tdiv2);
        div2.replaceWith(tdiv1);

        $('.box').on('click', function(){
            $('.act').removeClass('act');
            $(this).addClass('act');
        });
    }
//   $('.act').insertAfter($('.act').next());
});
.parent{
text-align:justify;
text-align-last:justify;
background:lightgreen;
}

.box{
display:inline-block;
width:20%;
height:25px;
background:orange;
}

.act{
background:skyblue;
}

1

2

3

4

<button>CLICK</button>

A: I would suggest the same way the previous answer is done, i.e by cloning and switching between the elements. But in the prev. answer the elements are getting disappeared after couple of clicks.
I've handled the condition when .next() is not available, hence having siblings elements looped.
$('.box').on('click', function (){
  $('.act').removeClass('act');
  $(this).addClass('act');
});

$('button').on('click', function (){
  if($('.act').length > 0)
  {
    activeBox = $('.act');
    nextBox = $('.act').next('.box').length > 0 ? $('.act').next('.box') : $('.box').eq(0);

    cloneActiveBox = activeBox.clone();
    cloneNextBox = nextBox.clone();

    activeBox.replaceWith(cloneNextBox);
    nextBox.replaceWith(cloneActiveBox);

    $('.box').on('click', function (){
      $('.act').removeClass('act');
      $(this).addClass('act');
    });
  }
});

Link to the working fiddle: http://jsfiddle.net/43psy50b/2/


text:
Q: How to get GitLab Runner to work with Bash on Windows I am trying to setup CI/CD within our GitLab instance to be run on a Windows 10 machine.
I have installed Git for Windows (which includes Git Bash) on the windows system.
I then register the runner according to the instructions given here.
I have then adjusted the config.toml file to use a bash shell, in this manner :
[[runners]]
  name = "DESKTOP-R9R6OV2"
  url = "https://git.mycompany.com/"
  token = "ozaxN3XoJm2sEPzc3BPx"
  executor = "shell"
  shell = "bash"
  builds_dir="/C/Build/"

As per this article - GitLab CI and Git Bash - I have created a bash.cmd file which contains
@"C:\Program Files\Git\usr\bin\bash.exe" -l

I have also ensured that C:\Program Files\Git and C:\Program Files\Git\usr\bin are in the global path definition as the runner is installed in the system admin account.
The pipeline kicks off, but seems to hang :
Running with gitlab-runner 14.7.0 (98daeee0)
  on DESKTOP-R9R6OV2 ozaxN3Xo
Preparing the "shell" executor
Using Shell executor...
Preparing environment

With the process waiting on Preparing environment
I have looked in the Event Viewer logs and there are no messages explaining what is going on.
So my question is, what else do I need to do to get the bash shell to work within GitLab Runner on a Windows 10 system ?
Are there special system permissions which need to be set ?

A: The working answer to this scenario is to use windows powershell and then launch the git bash shell from there.
So, in your gitlab-ci.yml, add the following powershell commands :
- New-Alias -Name gitBash -Value "$Env:ProgramFiles\Git\bin\bash.exe"
- gitBash -c <name of your bash file>

This will run your bash file within the git bash environment.
This means that your config.toml file must be setup thus :
[[runners]]
    ...
    executor = "shell"
    shell = "powershell"


text:
Q: Creating input object for mcl algorithm Having a dataset like this:
dframe = data.frame(id = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3), date = c("2013-07-14T21:44:37", "2017-09-18T12:04:06", "2014-08-13T19:17:55", "2016-04-17T07:45:54", "2014-11-19T08:05:26", "2013-06-27T05:48:02", "2017-03-07T08:40:31", "2018-05-20T13:37:22", "2014-08-31T07:33:38", "2011-04-05T14:11:51", "2014-06-19T16:27:29", "2016-10-24T21:59:17", "2013-04-30T06:49:54", "2011-08-04T20:27:33", "2011-10-31T07:45:49", "2012-03-03T23:29:02", "2018-05-19T09:48:13", "2018-02-25T20:42:00", "2016-12-08T05:03:17", "2015-05-21T23:26:41", "2015-07-16T12:38:33", "2015-08-09T17:15:39", "2017-10-14T05:38:04", "2017-09-23T06:11:29", "2015-07-11T02:46:40", "2017-12-17T04:14:08", "2015-06-14T02:28:37", "2017-12-16T02:17:07", "2018-02-26T06:35:26", "2016-12-14T22:27:04", "2016-12-22T23:31:51", "2016-12-20T01:49:41", "2017-08-28T11:39:42", "2015-06-15T00:51:13", "2015-09-02T15:02:53", "2018-05-02T19:07:45", "2015-10-26T22:11:16", "2015-10-28T09:37:02", "2018-02-10T07:58:27", "2015-05-05T13:21:20", "2018-04-25T19:09:41", "2016-03-30T08:06:27", "2017-10-31T12:09:44", "2016-11-04T13:46:06", "2015-09-02T15:02:12", "2016-09-01T14:54:16"), course = c("computer", "computer", "computer", "computer", "computer", "computer", "chemistry", "history", "history", "history", "history", "history", "parallel", "parallel", "poetry", "italics", "italics", "italics", "literature", "literature", "literature", "literature", "literature", "literature", "literature", "literature", "literature", "literature", "mathematics", "mathematics", "mathematics", "poetry", "poetry", "poetry", "gym", "motion", "computer", "literature", "literature", "literature", "literature", "literature", "literature", "literature", "physics", "poetry"))

The id column is the user who changes a course preference, which is the third column based on time which is the date column. So the preference of the course is the transfer/states.
How is it possible to create an appropriate input for mcl algorithm?
Example of expected input using an example of mcl package:
library(MCL)

mat <- matrix(c(0,1,1,1,0,0,0,0,0,1,0,1,1,1,0,0,0,0,1,1,
       0,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,1,0,0,0,1,1,0,
    0,0,0,0,0,1,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), byrow=TRUE, nrow=9)

mat
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
 [1,]    0    1    1    1    0    0    0    0    0
 [2,]    1    0    1    1    1    0    0    0    0
 [3,]    1    1    0    1    0    0    0    0    0
 [4,]    1    1    1    0    0    0    0    0    0
 [5,]    0    1    0    0    0    1    1    0    0
 [6,]    0    0    0    0    1    0    1    0    0
 [7,]    0    0    0    0    1    1    0    0    0
 [8,]    0    0    0    0    0    0    0    0    0
 [9,]    0    0    0    0    0    0    0    0    0


text:
Q: Examples of Probabilistic Discriminative Models I am trying to understand the class of binary classifiers that are 'probabilistic discriminative' in nature. For e.g. logistic regression is one such classifier because it is discriminative and has probabilistic interpretation. SVM is discriminative but not probabilisitic. The generalization of logistic regression to multiple classes are probabilisitic discriminative but they are not binary classifiers. Naive Bayes on the other hand is both binary and has probabilistic interpretation but is not a discriminative model.
Can someone suggest examples of binary classifiers other than logistic regression that have probabilistic discriminative interpretation. Please restrict to supervised settings only.

A: You can try out Linear discriminant(LDA) analysis and Quadratic discriminant(QDA) which are both probabilistic(Bayes) and discriminative at the same time.


text:
Q: Files are only sent with postman but not with file input When I send a file through the form, I get req.file is undefined. But through Postman, I get the file. Why?
<form action="/up" method="POST" enctype="multipart/form-data" class="row">

                Name
                <input type="text" class="form-control" name="name" id="name">

                CSV File
                <input type="file" id="csv" name="csv" accept=".csv">

                Rounds
                <input type="number" class="form-control" id="rounds" name="rounds" min="0">

                <button type="submit" class="btn btn-primary mb-3">Guardar</button>
                <button  class="btn btn-warning mb-3">Cancelar</button>

Route
router.post('/up', upCSV.single('csv'), newCamp);

Multer Middleware
const storage = multer.memoryStorage();
const upload = multer({ storage: storage});

Files are only sent with Postman but not with file input.


text:
Q: I want to make my game pause whenever the users finger is not touching the screen As I said, I would like to make my game only run when the user is touching the screen. So far I have:
public boolean onTouchEvent(MotionEvent e) {

    // Get finger's X and Y position
    float x = e.getX();
    float y = e.getY();

    if(x > startPlaying.left || x < startPlaying.right && y < startPlaying.bottom && y > startPlaying.top) {

        Playing = true;
    }

    if (Playing == true) {

                switch (e.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    playerX = x;
                    playerY = y;
                case MotionEvent.ACTION_UP:
                    Playing = false;
                }

            }

    return true;
}

Im thinking theres a problem with the 2 cases not being able to work together but im not really sure, im new to java. Any suggestions or fixes?
@Override protected void onDraw(Canvas canvas) {

    if (Playing == true) {
        rowSpeed = -2;
        rowSpeed -= 0.0002f;
        scoreCounter += 0.005;

    } else {
        rowSpeed = 0;
        rowSpeed -= 0f;
        scoreCounter += 0;
    }

A: The normal way to do a switch statement is
switch (e.getAction()) {
            case MotionEvent.ACTION_MOVE:
                playerX = x;
                playerY = y;
                break;                      // any reason you do not want this?
            case MotionEvent.ACTION_UP:
                Playing = false;
            }


text:
Q: EaselJS: change shape fill color on mouse click I'm having an hard time working with EaselJS. Basically I want to create a simple grid and highlight the actual element selected:
var stageWidth = 800,
   stageHeight = 600,
   cell_size = 50,
   w = 16,
   h = 12,
   n = w * h,
   canvas,
   stage,
   background;

$(document).ready(function(){

            canvas = $("#container")[0];
            stage = new createjs.Stage(canvas);

            var x_pos = 0,
                y_pos = 0,
                res = 0,
                grid_el;

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

                res = i%w;

                if(i>0){
                    if(res===0){
                        x_pos = 0;
                        y_pos++;
                    } else {
                        x_pos++;
                    }
                }

                grid_el = new createjs.Shape();
                grid_el.graphics.setStrokeStyle(2,"square").beginStroke("#000000");
                grid_el.graphics.beginFill("#70FF85");
                grid_el.graphics.rect(x_pos * cell_size,y_pos * cell_size,cell_size,cell_size);
                grid_el.x_pos = x_pos * cell_size;
                grid_el.y_pos = y_pos * cell_size;
                grid_el.name = "quad";

                stage.addChild(grid_el);
            }

            stage.update();

            stage.onMouseDown = function(e){
                console.log(e);
                var quad = this.getObjectsUnderPoint(e.stageX,e.stageY);

                var clone = quad[0].graphics.clone();
                clone.beginFill("#51D9FF");

                quad[0].graphics = new createjs.Graphics(clone);

                stage.update();
            }

        });

I tried cloning the actual element graphics property, changing the fill color and then updating the stage, but I only obtain a white element, just like it didn't recognize the new graphics properties.
Thanks for any help.

A: What I would recommend is using the onMouseOver/onMouseOut calls backs on a the shape or display object that you are creating.
When you can update you color that was.
Here is a simple demo that might help illustrate my point.
Link to demo
var stage = new createjs.Stage("test");
createjs.Touch.enable(stage);
stage.enableMouseOver(10);
var padding = 1;
var width = 55;
var height = 55;
var cols = 15;
for(var i=0;i<200;i++) {
    var s = new createjs.Shape();
    s.overColor = "#3281FF"
    s.outColor = "#FF0000"
    s.graphics.beginFill(s.outColor).drawRect(0, 0, width, height).endFill();
    s.x = (width + padding) * (i%cols);
    s.y = (height + padding) * (i/cols|0);
    s.onMouseOver = handleMouseOver;
    s.onMouseOut = handleMouseOut;
    stage.addChild(s)
}

createjs.Ticker.addListener(stage);

function handleMouseOver(event) {
   var target = event.target;
   target.graphics.clear().beginFill(target.overColor).drawRect(0, 0, width, height).endFill();
}

function handleMouseOut(event) {
    var target = event.target;
    target.graphics.clear().beginFill(target.outColor).drawRect(0, 0, width, height).endFill();
}

function tick() {
  stage.update();
}

Hope this helps.

A: Might consider going with KineticJS, you would just do:
circle.on('click', function() {
  // do stuff
});

I believe KineticJS is the only canvas framework that mirrors the DOM event model (you can bind events to nodes, they can bubble, you can leverage event delegation, etc.)


text:
Q: R: Piping with dplyr returns additional NULL I would like to get the mean squared error from a model in a dplyr pipeline.
Somehow when I use dplyr the output is NULL instead of the desired error measure.
Why is that?
MWE:
require(dplyr)
data("iris")
iris %>%
 CVlm(form.lm = formula(Sepal.Length ~ Sepal.Width), m = 2) %>%
 attributes(.)["ms"] #Returns NULL instead of 0.719

cvlm_model <- CVlm(data = iris, form.lm = formula(Sepal.Length ~ Sepal.Width), m = 2)
attributes(cvlm_model)['ms'] # Returns 0.719

Thanks

A: Try to use curly braces
library(magrittr)
library(DAAG)

iris %>%
 CVlm(form.lm = formula(Sepal.Length ~ Sepal.Width), m = 2) %>%
 {attributes(.)["ms"]}

A: This will do what you're after
iris %>%
  CVlm(form.lm = formula(Sepal.Length ~ Sepal.Width), m = 2) %>%
  attributes %>% .$ms

# [1] 0.719


text:
Q: Impelementing atomic CAS in gcc inline I've been trying to implement a gcc inline function (AT&T assembly) that will perform an atomic CAS operation, but I can't get it to work - the return value is always getting messed up.
I've tried 2 different approaches, each seems to have its own misbehaviours:
1.
static inline int
cas(volatile void * addr, int expected, int newval)
{
  int result = 1;
  asm volatile("lock; cmpxchgl %3, (%2)\n\t"
               "pushfl\n\t"
              "popl %%ebx\n\t"
              "andl $0x40, %%ebx\n\t"
              "cmpl $0x0, %%ebx\n\t"
              "jnz res%=\n\t"
              "movl $0, %0\n\t"
              "res%=:\n\t"
              : "=m"(result)
              : "a"(expected), "b"(addr), "r"(newval)
              : "memory");

  return result;
}

2.
static inline int cas(volatile void * addr, int expected, int newval) {
  int ret = 1;
  asm volatile("lock; cmpxchgl %3, (%2)\n\t"
          "jz cas_success%=\n\t"
          "movl $0, %0\n\t"
          "cas_success%=:\n\t"
  : "=m"(ret)
  : "a"(expected), "b"(addr), "r"(newval)
  : "memory");
  return ret;
}

But neither work, could anyone point me at the problem with one of the implementations?
Thanks


text:
Q: Finding a closed-form formula to a recurrence with summation of past terms I'm trying to find a closed form formula for the following recurrence problem but I'm having some difficulty:
\begin{align}
g(n) &= -\frac{1}{n+1} - \sum_{i=1}^{n} \frac{1}{n+1}g(i) \\
&= \frac{1}{n+1} \biggl( -1 - n\sum_{i=1}^{n} g(i) \biggr)
\end{align}
With $$g(0) = -\frac{1}{3}$$
I've seen several other posts use generator functions which I've attempted to use but got stuck relatively quickly.
\begin{align}
f(x) &= \sum_{n=0}^{\infty}g(n)\,x^n \\
&= \sum_{n=0}^{\infty} \biggl( \frac{1}{n+1}
\Bigl( -1 - (n) \sum_{i=1}^{n}g(i) \Bigr)x^n \biggr) \\
&= \sum_{n=0}^{\infty} \biggl( \frac{x^n}{n+1}
\Bigl( -1 - (n) \sum_{i=1}^{n}g(i) \Bigr) \biggr) \\
&= \sum_{n=0}^{\infty} - \frac{x^n}{n+1}
- \sum_{n=0}^{\infty}
\biggl( \frac{x^n(n)}{n+1} \sum_{i=1}^{n} g(i) \biggr) \\
&= \frac{\log(1-x)}{x} - \sum_{n=0}^{\infty} \biggl( \frac{x^n(n)}{n+1}
\sum_{i=1}^{n}g(i) \biggr)
\end{align}
But I'm not too sure where to go from there.

A: I think you need to be careful with the writing of the problem as mentioned in the comments. You also mention the value of $g(0)$ to be $-\frac{1}{3}$ but I think you mean $g(1)$. Therefore, I will solve the problem so it is consistent with $g(1)=-\frac{1}{3}$ and using the definition
$$
g(n)=-\frac{1}{n+1}\left(1+\sum_{i=1}^ng(i)\right)
$$
which is the same as the first line you have written.
Let $s(n)=\displaystyle\sum_{i=1}^n g(i)$. Then, we have
$$
g(n)=-\frac{1}{n+1}(1+s(n))
$$
On the other hand, note that $g(n)=s(n)-s(n-1)$, and hence we can plug this into the above to get
$$
s(n)-s(n-1)=-\frac{1}{n+1}(1+s(n))
$$
or after simplifying a bit
$$
(n+2)s(n)-(n+1)s(n-1)=-1.
$$
One can guess that $s(n)=-\frac{n}{n+2}$ solves such equation and satisfies $s(1)=g(1)=-\frac{1}{3}$.
Hence, we have
$$
\begin{align}
g(n)&=s(n)-s(n-1)\\
&=-\frac{n}{n+2}+\frac{n-1}{n+1}\\
&=-\frac{2}{(n+1)(n+2)}.
\end{align}
$$


text:
Q: Magento 2 get Product Collection creates issue on preparecollection I am using Magento 2.2.7. On custom product grid _prepareCollection() I tried to get all product collection by
$collection = $this->_productFactory->create()->getCollection();

but it gets only enabled & in_stock products. If I get count($collection->getData()) it shows all product count. but If I tried with $collection->count() it get only enabled and in_stock product count. How I get all products in grid through $this->setCollection($collection);


text:
Q: How do I set jquery pagination show page 1 on load I'd like to set page 1 to show first when I load my page using the pagination from this link
jquery pagination

A: Reading the documentation: https://github.com/gbirke/jquery_pagination#readme
It seems that the plugin has an option named :
current_page :- The page that is selected when the pagination is initialized. Default: 0
So I think you could do something like:
$("#News-Pagination").pagination(122, {
        items_per_page:20,
        callback:handlePaginationClick,
        current_page : 1
});

HTH :)


text:
Q: Passing Additional Arguments into a Callback Function I feel like I must be missing something obvious, but I can't seem to find it.
In nodejs how can I pass additional arguments into a callback function?
fs = require('fs');

for(var i = 0; i < 5; i++){
    fs.readFile(filePath, function(err, data){
        console.log(i);
    });
}

doing it this way you usually get a bunch of 4's written to the screen. I understand why that is happening. It is happening because that is the value of 'i' by the time it gets to that part of the code for all the callbacks. This doesn't work either:
fs = require('fs');

for(var i = 0; i < 5; i++){
    fs.readFile(filePath, callback(err, data, i));
}

function callback(err, data, i){
    console.log(i);
}

as 'err' and 'data' are undefined. I also understand why that is the case.
This works for 'i' but then I lose the err and data values that I need.
fs = require('fs');

for(var i = 0; i < 5; i++){
    fs.readFile(filePath, callback(i))
}

function callback(num){
    console.log(num);
}

How do I solve this?

A: Try wrapping it in a self executing anonymous function:
fs = require('fs');

for(var i = 0; i < 5; i++){
    (function(i) {
        fs.readFile(filePath, function(err, data){
            console.log(i);
        });
    })(i)
}

Also, keep in mind this approach won't scale. If you try a for loop to 1000 for instance, it will try to make all 1000 readFile calls concurrently. You're better off using something like the async library to make sure you're not running too many IO operations concurrently.

A: The easiest way is to use an immediately-invoked function expression (IIFE):
fs = require('fs');

for(var i = 0; i < 5; i++){
    (function(i){
        fs.readFile(filePath, function(err, data){
            console.log(i);
        });
    })(i);
}

This "captures" the value of i at each iteration inside an anonymous closure.


text:
Q: Google Earth Engine: Apply ee.Reducer to all image values Background
I would like to return percentile values for a multi-band image, using ee.Reducer.percentile().
For example, the image could look like this:
var image = ee.ImageCollection('LANDSAT/LT05/C01/T1')
  .filterDate('2008-01-01', '2008-03-01')
  .filter(ee.Filter.eq('WRS_PATH', 44))
  .filter(ee.Filter.eq('WRS_ROW', 34))
  .select('B1', 'B2')
  .toBands();

print(image);

In my case I am stacking an imageCollection (every image is one year), resulting in 18 bands:
var year_stack = imageCollectionYears.toBands();

In the R environment, I would use quantile(values(image), p = seq(0, 1, by = 0.2), na.rm = TRUE), which would return 6 quantile values, taken from all cell values in the raster image, regardless of layering.
Tried so far
I have applied the reducer to the image, but this returns percentile values for every band separately, rather than for all values in the image:
var percentiles = image.reduceRegion({
                  reducer:ee.Reducer.percentile([0, 20, 40, 60, 80, 100]),
                  bestEffort:true
  });

print(percentiles);

In my case, each band is an individual year, and the code returns percentile values for each year.
I have also tried to apply the reducer to my imageCollection, which returns an image with 6 bands.
var test = imageCollectionYears.reduce({
                  reducer:ee.Reducer.percentile([0, 20, 40, 60, 80, 100])

  });

I am struggling to retrieve the numbers of the percentiles in the returned image test, so I don't know if this worked (e.g. print(test.get("b1_p20")) prints null):
Question
How do I apply the reducer to all values, regardless of what band they are in, and return 6 percentile values? My aim is to get overall percentile values over all years, which I would then use for further analysis.

A: Here's some of the most terrible code I've ever written in EE. It really isn't a good idea to do it like this, and you will run out of memory when doing this at any larger scale. Maybe there's a better way to do this, that doesn't require every single pixel value to be in memory at once, but I cannot come up with one.
If you don't need the percentiles, maybe you could create multiple histograms, combine them, and get statistics from that? That should allow you to get similar type of information, and work for larger areas/more data.
var percentiles = ee.List(ee.ImageCollection(ee.ImageCollection('LANDSAT/LT05/C01/T1')
  .filterDate('2008-01-01', '2008-03-01')
  .filter(ee.Filter.eq('WRS_PATH', 44))
  .filter(ee.Filter.eq('WRS_ROW', 34))
  .select('B1', 'B2')
  .map(function (image) {
    var bands = image.bandNames().map(function (bandName) {
      return image.select(ee.String(bandName)).rename('band')
    })
    return ee.ImageCollection(bands)
  })
  .flatten())
  .iterate(function (image, acc) {
    var pixels = image.reduceRegion({
      reducer: ee.Reducer.toList(),
      bestEffort: true
    }).get('band')
    return ee.List(acc).cat(pixels)
  }, ee.List([])))
  .reduce(ee.Reducer.percentile([0, 20, 40, 60, 80, 100]))

https://code.earthengine.google.com/10718c9b3187bd65925ab9eae16f1f06


text:
Q: Which database architect is best for website/page stats counting I have already tried MongoDB and Redis and what i believe ..these databases are only good when you have a good hardware with a cluster offcourse.
My problem is that, I have to calculate few stuff of a video

*

*Views / Unique Views / Geo Location / Browser / Playtime etc.

*Number of comments

*Number of shares

There is alot of writing, i update data after every hour in my master database, so there is just one read (for each video in every hour). There are around (min) 5000 visitors online every moment on the website and i have to keep its tracking. I was using Redis, redis works great but i am really worried about its persitancy, I have lost around 4 times my data, millions of views reset. Redis is really good but you need to have a cluster so that if one server is down there is always another server to back it up. MongoDB went slow or may be i am not able to use it properly.
My Question is
I can afford 1 stats server right now, just for stats counting.

*

*4x SSD , 24 Gig Ram, Dual quad core 2.4 xeon

With this configuration, which Database Model is Best for Stats Counting Considering 1000 writes per second. I won't mind using SQLite. Need a suggestion perhaps. Help me decide.
I will write my code in PHP.

A: Do you have considered the use of redis only as a queueing server ?
This is how we manage our stats systems : a triggered event write into a redis server and we have a node.js daemon wich check every minutes the new row in this redis and send the whole new row into a "classical" SQL server (in our case, we have two sql server: one for events and stats, and another for notifications system).
The datas into the Sql servers are aggregated during the night by an another node.js script lauched by cron script (aggregation by time: stats of the day, stats of the week, of the month, etc.).

A: I believe SQLite will struggle with so many writes. In my opinion Redis was a good choice.
I am not a Redis power user but I've read a bit about it and used it a few times. The persistence problem you face shouldn't happen. Redis has the ability to save data to the disk: either explicity (ie, on command) or every X seconds.
You could then backup the Redis file to an other server, to make sure you won't lose too much. If you save to disk every hour, you won't lose more than 1 hour of data.


text:
Q: How could I use Spring's TransactionInterceptor with JPA? I have an existing project using Spring 3 and Hibernate 3. I have the following code in order to "safe-guard" the database consistency. If I'm going to convert the project into JPA, how could I resolve the transactionManager property inside the transactionInterceptor bean since JPA using persistence.xml and doesn't make use of dataSource and sessionFactory?
<bean id="transactionInterceptor"
   class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributes">
   <props>
    <prop key="save">PROPAGATION_REQUIRED</prop>
   </props>
</property>
</bean>

<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="dataSource" ref="dataSource" />
  <property name="sessionFactory" ref="sessionFactory" />
</bean>

A: Try using a configuration similar to the below xml snippet. This has been tested with Hibernate 4, but I would expect it to work with version 3 as well.
<!-- EntityManagerFactory configuration that doesn't need a persistence.xml -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
      p:dataSource-ref="dataSource"
      p:packagesToScan="${jpa.entity.packages}">

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
              p:showSql="${hibernate.show_sql}"/>
    </property>

    <property name="jpaProperties">
        <props>
            <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<!-- Scans for classes/methods with @Transactional annotation to apply the
     transaction management aspect (TransactionInterceptor) on them. -->
<tx:annotation-driven/>