text:
Q: move left right up down nodes to assign them roles in a tree i am making a tree with the help javascript and jquery .
I the tree there are four buttons that are being provided to change the indentation of the nodes.
let me explain the buttons.
-> left indent if i select a child and  click on it should make the particular child  to a next level child.
for ex: a is the root that have two children b,c at same level if i select c and click on the
left indent c should become the child of b.
result will be a has two level children b at one level and c is the child of b .
<- right indent if i select a child of child and click on this right indent than it should become same level child.
for ex: in the above case i have made c as child of b whose root is a now i want that c should again be at the same level of b than i select c and click right indent.
*Result*a has two children b,c at the same level.
if any of the selected item have further childs than it should follow it automatically.
I hope i am able to visualize my scenario.
how to proceed with this no clue.
in my markup there is only one div tag which is containing every thing and a button that
calls the function 'getuperparent()'
I am pasting my code to get a feel of how things are going on.
    //for calling first time parent
function GetSuperParent() {
            genrateHirerachy();
    }

    function genrateHirerachy() {
        var dvHirearchy = document.createElement("div");
        var counter = $("#hdnDivCounter").val();
        dvHirearchy.id = "dv_" + counter;

        $(dvHirearchy).addClass("divContainer");
        var ulSibContainer = document.createElement("ul");
        ulSibContainer.id = "ul_" + counter;
        var btnAdd = document.createElement("Input");
        btnAdd.setAttribute('onclick', 'GetTextData("'+dvHirearchy.id+'","'+ulSibContainer.id+'")');
        var spnData = document.createElement("span");
        spnData.id = "spnParent_"+counter;
        spnData.setAttribute('ondblclick', 'GetTexBox("'+spnData.id+'")');
        spnData.innerHTML = "double click to add super parent";
        btnAdd.type = "button";
        btnAdd.value = "+";
        //it will be added latter
       // var btnminus = document.createElement("Input");
       // btnminus.type = "button";
        //btnminus.value = "-";

        var btnchild = document.createElement("Input");
        btnchild.type = "button";
        btnchild.value = "+Child";
        btnchild.setAttribute('onclick', 'GetChildData("' + dvHirearchy.id + '")');
        var drpOrder = document.createElement("Select");
        var drpOption = document.createElement("OPTION");

        var drpText = document.createTextNode("display order");
        drpText = document.createTextNode("order");
        drpOption.appendChild(drpText);
        drpOption.setAttribute("value", "0");
        drpOption.setAttribute("value", "1");
        drpOrder.appendChild(drpOption);

        counter++;
        $("#hdnDivCounter").val(counter);
        $(dvHirearchy).append(ulSibContainer);
        $("#dvContainer").append(spnData);
        $("#dvContainer").append(btnAdd);
        //$("#dvContainer").append(btnminus);
        $("#dvContainer").append(btnchild);
        $("#dvContainer").append(drpOrder);
        $("#dvContainer").append(dvHirearchy);
    }

    //for setting the textbox for super parent
    function GetTexBox(spnID) {

        var elem = document.createElement("input");
        elem.type = "text";
        elem.id = "textbox1";
        elem.setAttribute('onblur', 'GetSpanValue("'+spnID+'")');
        if ($('#' + spnID).html() != "double click to add super parent" && $('#' + spnID).html() != '') {
            elem.value = $('#' + spnID).html();
        }
        $('#' + spnID).html('');
        $('#' + spnID).append(elem);
        elem.focus();

    }
    //on blur for super parent text box and remove it
    function GetSpanValue(spId) {
        $('#'+spId).append($('#textbox1').val());
        $('#textbox1').remove();
    }

    //for making the span for parent
    function GetTextData(divID,ulID) {

        //to check from where the function is called
        var checkClass = $('#dvContainer').find('span.bgLime').length;
        if (checkClass == 0) {
            AddSiblings(divID,ulID);
        $('#hdnChkSibbling').val('2');
        }
        else {

            var getValue = $('#dvContainer').find('span.bgLime');
            var spnID = getValue[0].id;
            var check = spnID.indexOf("spn");
            if (check>0) {
                AddSiblings();
                $('#' + spnID).removeClass('bgLime');
            }
            else {
                var chId = getValue.closest("div").attr("id");
                $('#' + spnID).removeClass('bgLime');
                var prntChID = chId.substring(0, 7);
                addSameLevelChild(prntChID);
            }

        }

    }

    //add the sibling
    function AddSiblings(divID,ulID) {
        var dvPrnt = AddNode();
            var liData = document.createElement("li");
                $(liData).append(dvPrnt);
                if ($("#hdnCount").val() != 2) {
                        $('#' + ulID).append("<br/>");
                    }
                        $('#' + ulID).append(liData);
    }

    //for creating the dynamic div
    function AddNode() {
        $("#hdnMngChildCss").val('1');
        var countSpan = $("#hdnCount").val();
        var dvPrnt = document.createElement("div");
        dvPrnt.id = "dv_Pr_" + countSpan;
        dvPrnt.innerHTML = "double click to add parent";
        dvPrnt.setAttribute('ondblclick', 'GetTextBoxForParent()');
        countSpan++;
        $("#hdnCount").val(countSpan);
        return dvPrnt;
    }
        //double click event of the div for sibbling
    function GetTextBoxForParent() {
        if ($("#hdnMngChildCss").val() == 1) {
            var decCount = $("#hdnCount").val() - 1;
            var spnNew = 'dv_Pr_' + decCount;
            $('#' + spnNew).html('');
            var spnImage = document.createElement("span");
            spnImage.id = spnNew + "_" + "spn1";
            $(spnImage).addClass('SpanImage');
            $('#' + spnNew).append(spnImage);
            var spnText = document.createElement("span");
            spnText.id = spnNew + "_" + "spn2";
            spnText.setAttribute('onclick', 'GetColorPrnt("' + spnText.id + '")');
            var elem = document.createElement("input");
            elem.type = "text";
            elem.id = "txtParent";
            elem.setAttribute('onblur', 'SetSpanValueForParent("' + spnText.id + '")');
            $(spnText).append(elem);
            setTimeout(function() { elem.focus() }, 50);
            $('#' + spnNew).append(spnText);
        }
    }

    function GetColorPrnt(spanChildId) {
        $('#' + spanChildId).addClass("bgLime");
        //$("#btnChild").removeAttr("disabled");
    }

    //on blur for all parents of textbox to remove it and set value
    function SetSpanValueForParent(parentId) {
        $('#'+ parentId).append($('#txtParent').val());
        $('#txtParent').remove();
        $("#btnRemove").removeAttr("disabled");
          }

    function addSameLevelChild(childId) {
        var liChild = document.createElement("li");
        var dvChildren = createDivChild(childId);
        $(liChild).append(dvChildren);
        $('#' + childId).append(liChild);
    }

    function createDivChild(childId) {
        var countSpan = $("#hdnChildCounter").val();
        var dvChild = document.createElement("div");
        dvChild.id = childId + "_" + countSpan;
        dvChild.innerHTML = "double click to add children";
        dvChild.setAttribute('ondblclick', 'GetChildNode("'+dvChild.id+'")');
        countSpan++;
        $("#hdnChildCounter").val(countSpan);
        return dvChild;
    }

    //for giving the message for adding child
    function GetChildData(dvPrntID) {
    debugger
        var getValue = $('#dvContainer').find('span.bgLime');
            var spnID = getValue[0].id;
            var check = spnID.indexOf("spn");
            var prntDvId = getValue.closest("div").attr("id");
            if (check > 0) {

                addChild(prntDvId);
            }
            else {
                //call the function to append the new child of a particular child and pass the spnID as
                //child id to append the respective node

                addChildofChild(prntDvId);
            }
            $('#' + spnID).removeClass('bgLime');
    }

    function addChildofChild(secChildid) {
        if ($("#hdnChildCounter").val() == 1) {
            var ulChildrens = document.createElement("ul");
        }
        var liChildrens = document.createElement("li");
        var dvChildrens = CreateChildNode(secChildid);
        $(liChildrens).append(dvChildrens);
        if (ulChildrens.tagname == 'ul') {
            $(ulChildrens).append(liChildrens);
            $(secChildid).append(ulChildrens);
        }
        else {
            $(secChildid).append(liChildrens);
        }

    }

    function createUl() {
        var ulChild = document.createElement("ul");
        ulChild.id = "ulc_" + $("#hdnChildCounter").val();
        return ulChild;
    }

    function addChild(parentId) {
        var childUl;
        if ($("#hdnChildCounter").val() == 1) {
            childUl = createUl();
        }
        var liChild = document.createElement("li");
        var dvChild = CreateChildNode(parentId);
        $(liChild).append(dvChild);
        $(childUl).append(liChild);
        $('#' + parentId).append(childUl);
    }

    function CreateChildNode(childID) {
        var childCounter = $("#hdnChildCounter").val();
        var dvChild = document.createElement("div");
        dvChild.id = childID + "_ch_" + childCounter;
        dvChild.innerHTML ="   " + "double click to add child";
        dvChild.setAttribute('ondblclick', 'GetChildNode("' + dvChild.id + '")');
        childCounter++;
        $("#hdnChildCounter").val(childCounter);
        return dvChild;
    }

    //double click for getting appended the textbox
    function GetChildNode(parentID) {

        $('#' + parentID).html('');
        var spnchImage = document.createElement("span");
        spnchImage.id = parentID + "_" + "chn1";
        $(spnchImage).addClass('SpanImage');
        $('#' + parentID).append(spnchImage);
        var spnChText = document.createElement("span");
        spnChText.id = parentID + "_" + "chn";
        spnChText.setAttribute('onclick', 'GetColorPrnt("' + spnChText.id + '")');
        var elemTxtChild = document.createElement("input");
        elemTxtChild.type = "text";
        elemTxtChild.id = "txtChildren";
        elemTxtChild.setAttribute('onblur', 'SetChildValueForParent("' + spnChText.id + '")');
        $(spnChText).append(elemTxtChild);
        $('#' + parentID).append(spnChText);
        $("#hdnMngChildCss").val('2');
        setTimeout(function() { elemTxtChild.focus() }, 50);
    }

    //On blur event for the text box
    function SetChildValueForParent(spanParentId) {
        $('#' + spanParentId).append("   ");
        $('#' + spanParentId).append($('#txtChildren').val());
        $('#txtChildren').remove();
        $("#btnChild").attr('disabled', 'disabled');
    }

    function DeleteNode() {

        var getNode = $('#dvTree').find('span.bgLime');
        var removeNode = getNode[0].id;
        $("#" + removeNode).remove();

    }

A: If I understand correctly, you want to do something like indent / unindent in MS Word's "outline mode". So, in this situation:

*

*a

*b

*

*c

*d

When you press "indent" on "b", the situation should be:

*

*a

*

*b

*c

*d

If you then press "unindent" on "c", the situation is:

*

*a

*

*b

*c

*d

You can do it this way (assuming the selected element has class "selected" and there is only one such element at any time):
function indent() {
    var $element = $('.selected'),
        $newParent = $element.prev();

    if ($newParent.length) {
        $element.appendTo($newParent); // I'm pretty sure this moves the element, might have to remove() as well
    }
}

function unIndent() {
    var $element = $('.selected'),
        $parent = $element.parent();

    $element.insertAfter($parent); // I'm pretty sure this moves the element, might have to remove() as well
}

This will also move any children of the moved node, that is, they will remain under their (moved) parent.
EDIT: as a bonus, here's the moveUp and moveDown functions:
function moveUp() {
    var $element = $('.selected'),
        $previous = $element.prev();

    if ($previous.length) {
        $element.insertBefore($previous);
    }
}

function moveDown() {
    var $element = $('.selected'),
        $next = $element.next();

    if ($next.length) {
        $element.insertAfter($next);
    }
}

Obviously some redundancy could be removed here, which I'll leave as "an exercise to the reader" ;)


text:
Q: Why is my bundle of data not being sent to my other activity? I am trying to pass some data from one activity to the second activity once the user clicks on the "Place your order button". I want the data to show up on the second activity but is is giving me either null or zero values. Only explanation is that the data being passed through the bundle is not being set, or is not being delivered. I made a global string variable called size and made it equal to xLarge to try and find where this bug is. When I run the program, it returns a null value in the second activity. Does anyone know why? Here is the code with some photos

Activity 1
    package com.example.switchviews;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class Activity1 extends Activity {
    /** Called when the activity is first created. */
    EditText mEdit;
    EditText mEdit2;
    double amount;
    double small;
    double meduium;
    double large;
    int count = 0;
    int numToppings;
    double toppingsTot=0;
    Button next;
    String size ="xLarge";
    double sizePrice;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
         next = (Button) findViewById(R.id.Button01);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                    Intent myIntent = new Intent(Activity1.this, Activity2.class);
                    Bundle myData = new Bundle();
                    myData.putDouble("price", amount);
                    myData.putDouble("toppings", toppingsTot);
                    myData.putInt("numberOfToppings", numToppings);
                    myData.putDouble("size", sizePrice);
                // Why is this set to null in activity 2?
                    myData.putString("sizePrice", size);
                    int[] myLittleArray = {1, 2, 3, 4,5,6, 7};
                    myData.putIntArray("myIntArray1", myLittleArray);
                    myIntent.putExtras(myData);
                    startActivityForResult(myIntent,2);
                }

        });
    }

Activity 2
    package com.example.switchviews;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Activity2 extends Activity {

    TextView pizza;
    TextView toppings;
    TextView total;
    Button submit;
    Button cancel;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        pizza = (TextView)findViewById(R.id.pizza);
        toppings = (TextView) findViewById(R.id.toppings);
        total = (TextView)findViewById(R.id.total);
        submit = (Button)findViewById(R.id.Button02);
        cancel = (Button)findViewById(R.id.Button03);

        Intent myLocalIntent = getIntent();
        Bundle myBundle = myLocalIntent.getExtras();

        double amount = myBundle.getDouble("price");
        double toppingsTot = myBundle.getDouble("toppings");
        int numToppings = myBundle.getInt("numberOfToppings");
        double sizePrice = myBundle.getDouble("sizePrice");
        String size = myBundle.getString("size");
        int[] arr1 = myBundle.getIntArray("myIntArray1");

        pizza.setText("Pizza "+ size + " 1x" + Double.toString(sizePrice)+ "    "+ "   "+ Double.toString(sizePrice) );

        Button next = (Button) findViewById(R.id.Button03);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
            }

        });
    }

}

Manifest XML
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.switchviews"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.switchviews.Activity1"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Activity2"></activity>
    </application>

</manifest>

A: Why is this set to null in activity 2?
Due to key data-type mismatch. sending sizePrice as String from first Activity but trying to get as double instead of String.
Do it as:
double sizePrice = myBundle.getDouble("size");
String size = myBundle.getString("sizePrice"); // return xLarge

A: Change this
    myData.putDouble("size", sizePrice); // Why is this set to null in activity 2?
 myData.putString("sizePrice", size);

To
    myData.putDouble("sizePrice", sizePrice);
 myData.putString("size", size);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to post angular form data using web api contact.component.html
<form class="contact-form" #f = "ngForm">

            <input type="text" name="name" class="input" [(ngModel)] = "selectedContact.name">

            <input type="text" name="phone" class="input" [(ngModel)] = "selectedContact.phone">

            <input type="text" name="email" class="input" [(ngModel)] = "selectedContact.email">

            <textarea class="required valid" name="message" [(ngModel)] = "selectedContact.message"></textarea>
            <button class="btn btn-primary" name="submit" type="button" (click)="createOrUpdateContact(f)">Send Message</button>

</form>

contact.component.ts
import { Component, OnInit } from '@angular/core';
import { Title } from "@angular/platform-browser";
import { ApiService } from '../../api.service';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {

  constructor(private title: Title, private apiService: ApiService) { }

  contacts:  any;
  selectedContact:  any  = {name:null, email:  null, phone: null, message: null};

  ngOnInit(): void {
    this.title.setTitle('Finance | Contact Us');
    this.apiService.readContacts().subscribe((contacts: any)=>{
      this.contacts = contacts;
      console.log(this.contacts);
    })
  }

  createOrUpdateContact(form){
      this.apiService.createContact(form.value).subscribe((contacts: any)=>{
        console.log("Contact created, ", contacts);
      });
  }
}

api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Contact } from  './model/contact.model';
import { Observable } from  'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  PHP_API_SERVER = "http://localhost";

  constructor(private httpClient: HttpClient) { }

  readContacts(): Observable<Contact[]>{
    return this.httpClient.get<Contact[]>(`${this.PHP_API_SERVER}/financeAPI/read.php`);
  }

  createContact(contact: Contact): Observable<Contact[]>{
    return this.httpClient.post<Contact[]>(`${this.PHP_API_SERVER}/financeAPI/create.php`, Contact);
  }
}

create.php
<?php
require 'config/db.php';
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata))
{
  $request = json_decode($postdata);
  if(trim($request->name) === '' || trim($request->email) === '' || trim($request->phone) === '' || trim($request->message) === '')
  {
    return http_response_code(400);
  }
  $name = mysqli_real_escape_string($con, trim($request->name));
  $email = mysqli_real_escape_string($con, trim($request->email));
  $phone = mysqli_real_escape_string($con, trim($request->phone));
  $message = mysqli_real_escape_string($con, trim($request->message));
  $s_date = date('Y-m-d');
  $sql = "INSERT INTO `contact`(`name`,`email`,`phone`,`message`,`s_date`) VALUES ('{$name}','{$email}','{$phone}','{$message}','{$s_date}')";
  if(mysqli_query($con,$sql))
  {
    http_response_code(201);
    $policy = [
      'name' => $name,
      'email' => $email,
      'phone' => $phone,
      'message' => $message,
      's_date' => $s_date
    ];
    echo json_encode($policy);
  }
  else
  {
    http_response_code(422);
  }
}

I am new in angular and I am simply trying to insert angular form data in mysql using web api. Now, What happen here when I try to read data from database it work perfectly and all data are showing in my console. But when I fill form data then it throw an error as mention below.
POST http://localhost/financeAPI/create.php 400 (Bad Request)
ERROR HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: 'Bad Request', url: 'http://localhost/financeAPI/create.php', ok: false, …}
I don't know why this happen? Please help me to solve this issue.
Thank You

A: in your submit button try change
createOrUpdateContact(f)
to
createOrUpdateContact(f.value)
to get the value from  your form
<button class="btn btn-primary" name="submit" type="button" (click)="createOrUpdateContact(f.value)">Send Message</button>

I replicate your code Here


text:
Q: ios Right way to free 2 dimensional memory allocated via calloc I have a iOS app. I allocate 2d memory and then deallocate using free function. Is this the right way to free? Recently I had crash pointing to free statement. Should I be releasing buf[i] in loop?
+(int**) initArr:(int) Nr:( int) Nc
{
int ** buf;
  buf = calloc(Nr,sizeof(int*));

for(int i = 0; i < Nr; i++)
{
    buf[i] = calloc(Nc,sizeof(int));

}
//Funny Processing

//Release
for(int i = 0; i < Nr; i++)
    free(buf[i]);
free(buf);
}

Here is the error message
2 libsystem_c.dylib 0x328b87ec _sigtramp + 48
3 libsystem_c.dylib 0x328ae20e pthread_kill + 54
4 libsystem_c.dylib 0x328a729e abort + 94
5 libsystem_c.dylib 0x32862380 free + 380
6 MyApp 0x0009be52 +[clsGlobalHelper resizeImageAvg:::] (clsGlobalHelper.m:300)


text:
Q: How to test sequelize query (where) logic? I'm trying to write unit tests which will test if the search query is right In other words if the logic written in where statement is returning expected results.
 async function search(some_data){
   return Event.findOne({
    where: {
      id: 123435,
      [Op.or]: [
        days: {
            [Op.overlap]: some_data.days,
        },
        [Op.or]: [
          {
            startTime: {
              [Op.gt]: some_data.start1,
            },
            endTime: {
              [Op.lt]:some_data.end1,
            },
          },
          {
            startTime: {
              [Op.lt]: some_data.start2,
              [Op.lt]: some_data.end2,
            },
            endTime: {
              [Op.gt]: some_data.end2,
              [Op.gt]: some_data.start2,
            },
          },
        ],
    ],
  },
})};

I need to test the result for different inputs.
I don't want to convert this test into integration test and use the original db, so I used sequelize-mock lib, but this returns only the result that I've defined and does not run the real query.

A: To test that your method is called with the correct parameters, you will need to use dependency injetion and a library to "spy" on your findOne method. In the example below, I am using Sinon
// app.js
// Note that "Event" must be used an argument in order to mock it out
async function search(Event, some_data) {
  return Event.findOne({
    where: {
      id: 123435
    }
  })
}

If your test file:
// your test file
const app = require('./app');
const sinon = require('sinon');
const EventMock = {
  findOne: sinon.spy()
};

describe('search', () => {
  it('should call with the right parameters', () => {
    const some_data = {};
    search(EventMock, some_data);

    assert(EventMock.findOne.calledWith({
      where: {
        id: 123435
      }
    }))
  });
});


text:
Q: Angular: error on cdk overlay when used with *ngIf I try to add a contextual menu to a button, I implemented the very simple example from the angular material documentation and it works well:
my-component.html
<button
    type="button" cdkOverlayOrigin #trigger="cdkOverlayOrigin"
    (click)="isOpen = !isOpen">
    Menu
</button>

<ng-template
  cdkConnectedOverlay
  [cdkConnectedOverlayOrigin]="trigger"
  [cdkConnectedOverlayOpen]="isOpen">

Item 1

Item 2

Item 3

</ng-template>

This works very well but then I have a more complex button: actually, the trigger button is displayed or not with the *ngIf directive.
<button *ngIf="accessMenu"
    type="button" cdkOverlayOrigin #trigger="cdkOverlayOrigin"
    (click)="isOpen = !isOpen">
    Menu
</button>

When I add this directive, I have an error at compilation:
Property 'trigger' does not exist on type 'myComponent'. Line 79 [cdkConnectedOverlayOrigin]="trigger"

I tried to set the directive out of the button by wrapping the button by an ng-container and adding the directive to the ng-container but it's the same.
Do you know why adding this structural directive make my compilation fail? And how should I do this? Thanks

A: The solution is simply to wrap the trigger button WITH the ng-template of the overlay in the ng-container, and not the ng-template alone:
<ng-container *ngIf="accessMenu">

  <button mat-mini-fab
    type="button" cdkOverlayOrigin #trigger="cdkOverlayOrigin"
    (click)="isOpen = !isOpen">
    Menu
  </button>

  <ng-template
    cdkConnectedOverlay
    [cdkConnectedOverlayOrigin]="trigger"
    [cdkConnectedOverlayOpen]="isOpen">

Item 1

Item 2

Item 3

  </ng-template>

</ng-container>


text:
Q: Uploading file using esriRequest Arcgis : failed I am trying to upload file using Esri request javascript api.
esriRequest({
      url: "http://localhost:20659/service/Service.svc/Upload/",
      form : this.datafile,
      handleAs: "json",
      callbackParamName: "callback"
    },{usePost: true, useProxy:true}).then(lang.hitch(this,function(response){

    }), lang.hitch(this,function(error){
      console.log(error);
    }))

my wcf service code
[OperationContract]
[WebInvoke(Method = "POST",
           UriTemplate = "Upload/",
           BodyStyle = WebMessageBodyStyle.Bare)]
UploadedFile Upload(System.IO.Stream Uploading);

public UploadedFile Upload(Stream Uploading)
{
    UploadedFile upload = new UploadedFile
    {
        FilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())
    };

    int length = 0;
    using (FileStream writer = new FileStream(upload.FilePath, FileMode.Create))
    {
        int readCount;
        var buffer = new byte[8192];
        while ((readCount = Uploading.Read(buffer, 0, buffer.Length)) != 0)
        {
            writer.Write(buffer, 0, readCount);
            length += readCount;
        }
    }

    upload.FileLength = length.ToString();

    return upload;
}

My html content
<form method="post" data-dojo-attach-point="datafile" enctype="multipart/form-data">
        <input type="file" name="Upload" id="uploadfile"  >
    </form>

When i click upload button. My service is not calling, not any response.
But other methods in my WCF service getting calling.
Any help


text:
Q: Sizing pipes for a filter system with two pumps and one inlet and outlet, bernoulli and venturi? I need help with a concrete problem that needs solving through good application of physics principles. Here's the problem:
I would like to build a filtering system for my bestway pool, the pool has only one inlet and one outlet for filtering water, diameter of each 32 mm.
I also have a system that can heat the water by passing the filtered water through some 1/2 inch pipes (that are buried under concrete, so I can't replace them) to a heat exchanger to the heat pump.
And I have a 10 M3/h filtering pump. My problem is that the pipes to the heating are too small for the 10M3/h pump, this causes a pressure build up in the sand filter, which is plastic, breaking it rather quickly.
I would like to modify the system, so that the 10m3/h pump is only used for actual filtering, while the heating is done using a smaller pump (2.5 m3/h). The pool still has only one intake and one outtake for water, so I will need at some point to have some sort of T split. to split the two flows, and rejoin them after heating/filtering. like shown here:
Because the two pumps are very different in their hydraulic characteristics, I'm worried that I won't be able to run both pumps at the same time, i.e. the powerful one will make the small one useless.
I'm looking for a solution to this:
Venturi said that if I have a pipe, and reduce it's diameter in the shrinkage I'll get lower pressure. I imagine the opposite will be true too: if I enlarge the pipe, I'll get a higher pressure.

So if

*

*pressure at A = pressure at B

*pipe diameter at A = diameter at B

*main pipe diameter at C < diameter at A

*main pipe diameter at D > pipe diameter at B

then

*

*pressure at C < pressure at A

*pressure at D > pressure at B

*pressure at C < pressure at D

I could then join these two pieces together as in the figure:

because there's a higher pressure at B (pipe C)  than there's at F (pipe D), then there must be a flow in the lateral pipe C-D. even when there's no pump in this pipe, but only one located at E.
now, I'm not too sure there can be real flow without a pump on C-D but at least I hope I might be able to have a smaller pump on C-D running the water heating system.
I'm planning to 3d print the parts for this, so I have the chance to calibrate the sizes of all the pipes.
If this principle is sound, how would I calculate the diameters of the pipes and how would I shape the T junctions to make it work?
I got this idea from this: https://www.thingiverse.com/thing:4920000


text:
Q: how to get frequency of audio at specific time in python? I am working on mp3 file to get the speech in the form of text with speech_recognization python. Here I need to get the text from mp3 file for every 10sec. I am not able accurate results. so my idea is to get the frequency of the audio for every 10sec, if the frequency is too low then I want to convert audio to text to that point.(I don't want to use numpy, scipy, matplotlib).
Please give your valuable suggestions.

A: In order to detect low frequency you will need to use STFFT [ Short Time Fast Fourier Transformation] algorithms. A better way may be to detect amplitude [ loudness ] and silence.
PYDUB has easier way of accomplishing loudness in DBFS / Maximum volume and RMS volume detection.
You can install pydub using
pip install pydub
As far as splitting audio in 10 second interval and feeding it through speech_recognition module in python, I got a crude program working finally. It has few kinks and by no way a comprehensive one, but it gives some insight into the direction you are looking for.And it works to provide a proof of concept.
The program works with WAV files, but you can replace wav format with MP3 to get it working with MP3.
Setup
Basically, I downloaded free / open-source pre-recorded wav file from this site And concatenated them using PYDUB.
[https://evolution.voxeo.com/library/audio/prompts/numbers/index.jsp]
When I tested individual files, only google translator was working so I got rid of others to make code clean.
Sample python code for speech-recognition was downloaded from here,
https://github.com/Uberi/speech_recognition/blob/master/examples/wav_transcribe.py
So the program uses pydub to read and slice audio file that has spoken words from 0 through 100 at the interval of 10 seconds. Due to the nature of pre-recorded file and the fact that this program does not account for dynamic slicing, as you will see in the output , the recognition is not co-ordinated.
I believe a better program that recognizes silence dynamically and slices audio accordingly can be developed.
This was developed on Windows system with python 2.7
Program
############################### Declarations ##############################################

import os
from pydub import AudioSegment
import speech_recognition as sr

#Read main audio file to be processed. Assuming in the same folder as this script
sound = AudioSegment.from_wav("0-100.wav")

#slice time are in seconds
tenSecSlice = 10 * 1000

#Total Audio Length
audioLength = len(sound)

#Get quotient and remainder
q, r = divmod(audioLength, tenSecSlice)

#Get total segments and rounds to next greater integer
totalSegments= q + int(bool(r))

exportPath = "\\tempDir\\"

####################################################
#Function for Speech Recognition
#downloaded & modified  from above mentioned site
####################################################

def processAudio(WAV_FILE):
    r = sr.Recognizer()
    with sr.WavFile(WAV_FILE) as source:
        audio = r.record(source) # read the entire WAV file

    # recognize speech using Google Speech Recognition
    try:
        # for testing purposes, we're just using the default API key
        # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
        # instead of `r.recognize_google(audio)`
        print("Google Speech Recognition thinks you said " + r.recognize_google(audio))
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))

############################### Slice Audio and Process ################################

#Declare empty List

exportPath = "tempDir\\"
segmentList = []
n=0

#Iterate through slices  and feed to speech recognition function
while n < totalSegments:
    firstPart = (tenSecSlice * n)
    secondPart =  (tenSecSlice * (n + 1))

    print ("Making slice  from %d to %d  (sec)" % (firstPart /1000 , secondPart /1000))
    print ("Recognizing words from  %d to %d " % (firstPart /1000 , secondPart /1000))
    tempObject = sound[ firstPart :secondPart ]
    myAudioFile = exportPath + "slice" + str(n) +".wav"
    tempObject.export(myAudioFile , format="wav")
    n += 1
    processAudio(myAudioFile)
    print ("")

############################### End Program ##############################################

OUTPUT
    Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
================================ RESTART ================================

Making slice  from 0 to 10 (sec)
 Recognizing words from  0 to 10
Google Speech Recognition thinks you said 0 1 2 3 4 5 6 7 8 9 10 11

Making slice  from 10 to 20 (sec)
 Recognizing words from  10 to 20
Google Speech Recognition thinks you said 12 13 14 15 16 17 18 19 20 21

Making slice  from 20 to 30 (sec)
 Recognizing words from  20 to 30
Google Speech Recognition thinks you said 21 22 23 24 25 26 27 28 29

Making slice  from 30 to 40 (sec)
 Recognizing words from  30 to 40
Google Speech Recognition thinks you said 30 31 32 33 34 35 36 37 38

Making slice  from 40 to 50 (sec)
 Recognizing words from  40 to 50
Google Speech Recognition thinks you said 39 40 41 42 43 44 45 46 47

Making slice  from 50 to 60 (sec)
 Recognizing words from  50 to 60
Google Speech Recognition thinks you said 48 49 50 51 52 53 54 55 56

Making slice  from 60 to 70 (sec)
 Recognizing words from  60 to 70
Google Speech Recognition thinks you said 57 58 59 60 61 62 63 64 65

Making slice  from 70 to 80 (sec)
 Recognizing words from  70 to 80
Google Speech Recognition thinks you said 66 67 68 69 70 71 72 73 74

Making slice  from 80 to 90 (sec)
 Recognizing words from  80 to 90
Google Speech Recognition thinks you said 75 76 77 78 79 80 81 82 83

Making slice  from 90 to 100 (sec)
 Recognizing words from  90 to 100
Google Speech Recognition thinks you said 84 85 86 87 88 89 90 91 92

Making slice  from 100 to 110 (sec)
 Recognizing words from  100 to 110
Google Speech Recognition thinks you said 93 94 95 96 97 98 99 100


text:
Q: XMLReader returning "\n " instead of value I'm having a strange issue and I can't really find the cause. It just suddenly stopped working and I don't know what triggered it.
I'm using XMLReader in C# to read an xml file. I'm reading the values from the xml file like this:
if(subReader2.MoveToAttribute("X"))
    float.TryParse(reader.Value, NumberStyles.Any
           , CultureInfo.InvariantCulture, out pt.point.X);

The xml contains a tag like this:
<Point X="0" Y="0" Easing="Linear" EaseIn="True" EaseOut="True" />

When it reads the attributes X and Y, reader.Value returns \n for some reason. It has worked before, but something is stopping it now. The attributes, Easing, EaseIn and EaseOut are being read just fine. So I have no idea why X and Y would fail.
The full xml file
The complete parsing function
Any ideas?

A: When you have read.Value, shouldn't that be subReader2.Value?

A: The problem here is that you are pointing subReader2 at the X attribute and then taking a value from reader. Is there a reason you're using a separate reader for each loop?


text:
Q: twoord.plot axis changing I am using twoord.plot for the first time, and I am having trouble getting the x axis set to years for a time-series data set. I have two different y-axes on different scales. Here is the code that I am working with.
#Install BatchGetSymbols
install.packages('BatchGetSymbols')
library(BatchGetSymbols)

#Get data from FRED
library(quantmod)
getSymbols('CPALTT01USM661S', src = 'FRED')

library(quantmod)
getSymbols('M2SL', src = 'FRED')

#Create data sets with equal number of observations

CPI = CPALTT01USM661S["1960-01-01/2019-01-01"]
M2 = M2SL["1960-01-01/2019-01-01"]

library(plotrix)
twoord.plot(rx = time(CPI), ry = CPI, lx = time(CPI), ly = M2,
            main = "Money Supply and Prices",
            xlim = NULL, lylim = NULL, rylim = NULL,
            mar = c(5,4,4,4), lcol = "red", rcol = "blue", xlab = "", lytickpos = NA,
            ylab = "M2", ylab.at = NA,
            rytickpos = NA, rylab = "CPI", rylab.at = NA, lpch = 1,rpch = 2,
            type = "l", xtickpos = NULL, xticklab = NULL,
            halfwidth = 0.4, axislab.cex = 1, do.first = NULL)

Here is the graph that I am getting. Notice the x-axis is not in years.

A: The date values ( beginnings of each month) are in the index of the matrices, so to extract the year beginnings get every 12th item:
twoord.plot(rx=time(CPI), ry=CPI, lx=time(CPI),ly = M2, main="Money Supply and Prices",xlim=NULL,lylim=NULL,rylim=NULL,
            mar=c(5,4,4,4),lcol="red",rcol="blue",xlab="",lytickpos=NA,ylab="M2",ylab.at=NA,
            rytickpos=NA,rylab="CPI",rylab.at=NA,lpch=1,rpch=2,
            type="l",
            xtickpos=index(CPI)[seq(1,nrow(CPI), by=12)], #tick at year start
            xticklab=format( index(CPI)[seq(1,nrow(CPI), by=12)], "%Y"), #just year
            halfwidth=0.4, axislab.cex=1,
            do.first=NULL, las=2)   # not sure why las=2 didn't seem to work.


text:
Q: Android ) java.lang.NoClassDefFoundError: com.google.android.gms.internal.zzno I fixed again and again but the final error I'm having is:
java.lang.NoClassDefFoundError: com.google.android.gms.internal.zzno

My build.gradle is below:
buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:1.3.0'
    classpath 'com.google.gms:google-services:1.5.0-beta2'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
    repositories {
        jcenter()
    }
}

subprojects {
    repositories {
        mavenCentral()
        maven { url 'http://devrepo.kakao.com:8088/nexus/content/groups/public/' }
    }
}

And another build.gradle is below :
    apply plugin: 'com.android.application'
    apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

dexOptions {
    javaMaxHeapSize "4g"
}

defaultConfig {
    applicationId "com.example.min.photozzle"
    minSdkVersion 17
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:multidex:1.0.1'

    compile group: 'com.kakao.sdk', name: 'kakaolink', version: '1.1.0'
    compile group: 'com.kakao.sdk', name: 'kakaostory', version: '1.1.0'// 카카오스토리 sdk를 사용하기 위해 필요.
    compile group: 'com.kakao.sdk', name: 'kakaotalk', version: '1.1.0'    // 카카오톡 sdk를 사용하기 위해 필요.
    compile group: 'com.kakao.sdk', name: 'push', version: '1.1.0'    // push sdk를 사용하기 위해 필요.

    compile 'com.squareup.retrofit:retrofit:1.9.0'
    //compile 'com.google.android.gms:play-services-gcm:8.3.0'
    compile "com.google.android.gms:play-services:8.3.0"
    compile 'org.apache.directory.studio:org.apache.commons.io:2.4'

}

Fianlly my manifest is below :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.min.photozzle" >

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<permission
    android:name="com.example.min.photozzle.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.example.min.photozzle.permission.C2D_MESSAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <activity android:name=".StoryGame" />
    <activity android:name=".StoryMode" />
    <activity android:name=".CustomMode" />
    <activity android:name=".Title" />
    <activity android:name=".Splash" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver
        android:name="com.google.android.gms.gcm.GcmReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>

            <!-- Receives the actual messages. -->
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />

            <!-- Receives the registration id. -->
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="com.example.min.photozzle" />

        </intent-filter>
    </receiver>

    <service
        android:name=".GCM.RegistrationIntentService"
        android:exported="false" >
    </service>

    <service
        android:name=".GCM.MyInstanceIDListenerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.google.android.gms.iid.InstanceID"/>
        </intent-filter>
    </service>

    <service
        android:name=".GCM.MyGcmListenerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>

    <meta-data
        android:name="com.kakao.sdk.AppKey"
        android:value="@string/kakao_app_key" />
</application>

And our error log is below:
12-08 20:16:32.306  19305-19305/? E/dalvikvm﹕ Could not find class 'com.google.android.gms.internal.zzqq$zzd', referenced from method com.google.android.gms.measurement.internal.zzt.zzBK
12-08 20:16:32.306  19305-19305/? E/dalvikvm﹕ Could not find class 'com.google.android.gms.internal.zzqq$zzd', referenced from method com.google.android.gms.measurement.internal.zzt.zzBK
12-08 20:16:32.311  19305-19305/? E/dalvikvm﹕ Could not find class 'com.google.android.gms.internal.zzqq$zzc', referenced from method com.google.android.gms.measurement.internal.zzt.zzBK
12-08 20:16:32.311  19305-19305/? E/dalvikvm﹕ Could not find class 'com.google.android.gms.internal.zzqq$zzd', referenced from method com.google.android.gms.measurement.internal.zzt.zza
12-08 20:16:32.381  19305-19305/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.min.photozzle, PID: 19305
    java.lang.NoClassDefFoundError: com.google.android.gms.internal.zzno
            at com.google.android.gms.measurement.internal.zzx.zzj(Unknown Source)
            at com.google.android.gms.measurement.internal.zzt.<init>(Unknown Source)
            at com.google.android.gms.measurement.internal.zzx.zzBQ(Unknown Source)
            at com.google.android.gms.measurement.internal.zzt.zzaU(Unknown Source)
            at com.google.android.gms.measurement.AppMeasurementContentProvider.onCreate(Unknown Source)
            at android.content.ContentProvider.attachInfo(ContentProvider.java:1591)
            at android.content.ContentProvider.attachInfo(ContentProvider.java:1562)
            at android.app.ActivityThread.installProvider(ActivityThread.java:5233)
            at android.app.ActivityThread.installContentProviders(ActivityThread.java:4828)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4711)
            at android.app.ActivityThread.access$1600(ActivityThread.java:175)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5602)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)

I googled it for an hour and introduced that but that doesn't work well for me.
Am I'm trying to use GCM for my application.

A: I encounter the same issue. And add content in following file into proguard-project.txt helps. Please give it a try.
https://github.com/google/google-api-java-client-samples/blob/master/calendar-android-sample/proguard-google-api-client.txt

A: classpath 'com.google.gms:google-services:+'

try this line in the top level gradle.build should retrieve the latest version of google services pack, maybe thats the issue.


text:
Q: How to use assert within async functions? (Typescript) I have a block like below, which is a function using async
If I add an assert statement in there, it will stop the code executing at that line, but no error is thrown. It just dies silently :(
async function testMongo() {
  let db = await dbConnect();

  await db.collection("stories").remove({});
  let c = await count("stories", {} );
  assert.strictEqual(c, 999);   // should fail
  console.log("moving on...");  /// will never get reached.

}

Is there some reason that the assertion maybe gets swallowed up?
I've had problems like these before with errors inside event emitters, and it seems the immediate return of the async function is some type of event emitter/Promise.

A: console.log() call can be skipped is if async db.connection() or count() will reject their promises. It this case your should try wrapping those calls in try/catch:
try
{
    await db.collection("stories").remove({});
}
catch(e)
{
    //...
}

Or catch error using promise:
await db.collection("stories").remove({}).catch((e) => {//...});

[EDIT]
The generic wrapper that will execute async function and continue even on rejection can look something like this:
async function Do<T>(func: ()=>Promise<T>)
{
    try
    {
        await func();
    }
    catch(e)
    {
        console.log(e);
    }
}


text:
Q: Procedures with linked server with strange error I have two procedures that uses the same linked server,one works and one doens't, when i execute they directly in the DB both Works normal but in the cs just one Works.
The proc that Works is that
ALTER  PROCEDURE [dbo].[SP_WKF_INS_ANEXO]

    @ID_PROCESSOITEM    INT,
    @DOCUMENTO          VARBINARY(MAX) = null,
    @DOCUMENTONOME      VARCHAR(200)   = null,
    @DOCUMENTOTIPO      VARCHAR(200)   = null,
    @COD_FUNC           INT

AS
BEGIN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
    SET XACT_ABORT ON
    INSERT INTO [WorkFlow].[dbo].[WKF_ProcessoAnexo]
    (
        Id_ProcessoItem,
        Id_ProcessoDetalhe,
        Doc_Anexo,
        Des_DocNome,
        Des_DocTipo,
        Cod_Func,
        Dt_Inclusao,
        Dt_Alteracao
    )
    VALUES
    (
        @ID_PROCESSOITEM,
        null,
        @DOCUMENTO,
        @DOCUMENTONOME,
        @DOCUMENTOTIPO,
        @COD_FUNC,
        GetDate(),
        Null
    )

END

And i use it this way.
public static void spItnInsAnexo(this dbContext db, int idProcessoItem, byte[] documento, string documentoNome,string documentoTipo,int codigoFuncionario)
        {
            db.Database.ExecuteSqlCommand(
               "[BRZGRUAP17].[WorkFlow].[dbo].[SP_WKF_INS_ANEXO] @ID_PROCESSOITEM, @DOCUMENTO,@DOCUMENTONOME,@DOCUMENTOTIPO,@COD_FUNC",
                new SqlParameter("@ID_PROCESSOITEM", idProcessoItem),
                new SqlParameter("@DOCUMENTO", documento),
                new SqlParameter("@DOCUMENTONOME", documentoNome),
                new SqlParameter("@DOCUMENTOTIPO", documentoTipo),
                new SqlParameter("@COD_FUNC", codigoFuncionario)
            );
        }

The one that doesn't work is the next one,i pass the parameters correct but i cant find why it doens't work,when i execute it does not give any error,but it don't update in the DB.
ALTER PROCEDURE [dbo].[SP_WKF_UPD_ITENS]

    @ID_REFERENCIA VARCHAR(30),
    @ID_PROCESSOITEM INT

 AS

BEGIN

    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
    SET XACT_ABORT ON
    UPDATE [WorkFlow].[dbo].[WKF_ProcessoItem] SET
    Id_Referencia = @ID_REFERENCIA
    where Id_ProcessoItem = @Id_ProcessoItem

END

And this is how i call it.It uses the same way i use in the other one that Works,i cant find why it doesnt work,if i use the same idProcessoItem and IdReferencia in the db and update normally.Someone knows what i'm missing?
public static void spItnUpdItens(this dbContext db, int idProcessoItem,string IdReferencia)
    {
        db.Database.ExecuteSqlCommand(
           "[BRZGRUAP17].[WorkFlow].[dbo].[SP_WKF_UPD_ITENS] @ID_PROCESSOITEM, @ID_REFERENCIA",
            new SqlParameter("ID_PROCESSOITEM", idProcessoItem),
            new SqlParameter("ID_REFERENCIA", IdReferencia)
        );
    }


text:
Q: Is the VTC backlog only on Stack Overflow? I was wondering if the VTC backlog was only on Stack Overflow, or if it existed on other Stack Exchange sites. If it did exist on other sites, that might mean that the system for all Stack Exchange sites may need to be changed.

A: Oldest pending close review task and # of pending tasks by site:
Oldest      Count  Site Name
----------- ------ ---------
Jul 10 2012 103518 StackOverflow
May 26 2013 383    SuperUser
Dec  4 2013 40     ServerFault
Nov 11 2013 5      Cooking
Dec  6 2013 3      Game Developers
Dec  9 2013 2      Gaming
Dec 10 2013 2      Mathematics
Sep  2 2013 13     Photography
Dec  9 2013 1      Statistical Analysis
Oct 28 2013 72     Web Apps
Aug 14 2012 3      Webmasters
Jan 11 2013 22     Theoretical Computer Science
Dec  8 2013 16     English Language and Usage
Nov 12 2013 1      Personal Finance and Money
Dec 10 2013 1      Role-playing Games
Dec  9 2013 2      TeX - LaTeX
Oct  1 2013 342    Ubuntu
Dec  9 2013 4      Unix and Linux
Dec  9 2013 1      WordPress
Nov  8 2013 8      Bicycles
Nov 14 2013 41     Programmers
Dec  7 2013 6      Android Enthusiasts
Nov 20 2013 9      OnStartups
Dec  8 2013 1      Board and Card Games
Dec  9 2013 2      Physics
Dec  9 2013 2      IT Security
Nov 11 2013 5      Writers
Dec  9 2013 4      Electronics and Robotics
Dec  5 2013 12     Database Administrators
Oct  6 2013 8      Area 51 Discussions
Dec  9 2013 2      Code Review
Dec  6 2013 4      Code Golf
Nov 15 2013 3      Project Management
Nov 25 2013 7      Skeptics
Oct 21 2013 70     Drupal Answers
Sep  6 2013 15     Fitness and Nutrition
Nov  2 2013 4      Motor Vehicle Maintenance and Repair
Nov 22 2013 3      Parenting
Dec  8 2013 1      Musical Practice and Performance
Aug 27 2013 3      Jewish Life and Learning
Nov 12 2013 1      Gardening and Landscaping
Oct  7 2013 8      Philosophy
Nov 29 2013 5      Personal Productivity
Dec  9 2013 2      Travel
Oct 28 2013 6      Cryptography
Apr 27 2013 4      Signal Processing
Dec  7 2013 2      French Language and Usage
Dec  6 2013 10     Christianity
Sep 13 2013 34     Bitcoin
Nov  7 2013 6      Biblical Hermeneutics
Dec  4 2013 7      History
Dec  9 2013 1      Spanish Language and Usage
Dec  5 2013 2      Computational Science
Dec  8 2013 2      Mathematica
Sep 23 2013 12     Cognitive Sciences
Dec  9 2013 1      The Great Outdoors
Dec  9 2013 2      Sports
Dec  9 2013 1      Academia
Nov 17 2013 34     Computer Science
Dec  9 2013 4      The Workplace
Nov 13 2013 2      Windows Phone
Dec  2 2013 1      Chess
Sep  3 2013 28     Raspberry Pi
Aug 12 2013 2      Islam
Dec 26 2012 32     Patents
Dec  9 2013 1      User Experience
Aug 22 2013 2      Genealogy and Family History
Nov  8 2013 2      Robotics
Oct 22 2013 6      Politics
Aug  6 2013 6      Audio-Video Production
Dec  9 2013 1      English Language Learners
Dec  5 2013 1      Tridion Stack Exchange
Nov 10 2013 5      Reverse Engineering Stack Exchange
Nov  8 2013 2      Open Data Stack Exchange
Jun  4 2013 2      Freelancing Stack Exchange
Dec  8 2013 2      Blender Stack Exchange
Dec  7 2013 4      MathOverflow

(sites with no pending close review tasks omitted)


text:
Q: A question about SQL insert statement! I have two tables:
Threads
*******
ThreadID
UserID
TopicsID
Date
ThreadTitle
ThreadParagraph
ThreadClosed

Topics
******
TopicID
Theme
Topics
Date

I need to insert two statements and connect between them!
This the first statment:
string insertCommand =
    "INSERT INTO Users (UserID,TopicID,Date,ThreadTitle,ThreadParagraph) " +
     "VALUES ('CONVERT(uniqueidentifier, '" + giveMeGuidID() +
     "),TopicID,dateTime,questionTitle,subTopic)";

and i need to have another statement for the Topics Table:
string insertCommand =
    "INSERT INTO Topics (UserID,TopicID,Date,ThreadTitle,ThreadParagraph) " +
    "VALUES ('Theme, Topics, Date')";

The problem is that i have a connection between TopicsID (Threads table) and TopicsID
(Topics table). Both are incremental ints, so how do i insert the same TopicID to
both of them so they get the same value?

A: If you use MS SQL server, you can get the autoincrement value with @@Identity.
string insertCommand =
    "INSERT INTO Users (UserID,TopicID,Date,ThreadTitle,ThreadParagraph) " +
    "VALUES ('CONVERT(uniqueidentifier, '" + giveMeGuidID() +
    "),TopicID,dateTime,questionTitle,subTopic); SELECT @@Identity";

Then, run this command as ExecuteScalar and get your value

A: You can maintain the Transaction by using TransactionScope and using SCOPE_IDENTITY() to get the inserted Id from the First Query.
 // Create the TransactionScope
using (TransactionScope oTranScope = new TransactionScope())
{
   Int32 TopicID;
    // Open a connection
    using (SqlConnection oCn1 = new SqlConnection(this.sCn1))
    {
        SqlCommand oCmd1 = new SqlCommand("INSERT INTO Users (UserID,TopicID,Date,ThreadTitle,ThreadParagraph) " +
"VALUES ('CONVERT(uniqueidentifier, '" + giveMeGuidID() +
"),TopicID,dateTime,questionTitle,subTopic); SELECT SCOPE_IDENTITY()";, oCn1);

        oCmd1.Parameters.Add ... Better to use parameter to save SQL Injection Attack

        oCn1.Open();
        // At this point, the connection is in the transaction scope,
        // which is a lightweight transaction.
        TopicID = Convert.ToInt32 oCmd1.ExecuteScaler()); // as you want to get Id
        oCn1.Close();
    }
    // Open a connection
    using (SqlConnection oCn2 = new SqlConnection(this.sCn2))
    {
        SqlCommand oCmd2 = new SqlCommand("SQLQuery", oCn2);
        //use return TopicID from last inserted query
        oCn2.Open();
        // The connection is enlisted in the transaction scope,
        // which is now promoted to a distributed transaction
        // controlled by MSDTC
        oCmd2.ExecuteNonQuery();
        oCn2.Close();
    }
    // Tell the transaction scope to commit when ready
    oTranScope.Consistent = true;
    // The following bracket completes and disposes the transaction
}

A: If you are looking for something reliable you need to use Transactions.
Refer to Managing Transactions in SQL Server Stored Procedures to get an idea.
Also, take a look at Controlling Transactions (Database Engine) and SQL Server Transaction Isolation Models.
You also need to use @@Identity the last-inserted identity value.

A: You code samples do not correlate well with the rest of the information provided. Without the code your post seems consistent enough, though, so I'm inclined to consider those snippets as simply erroneous.
Anyway, your idea seems clear. In SQL Server 2005+ you could solve your problem with an INSERT statement like this one:
string insertCommand =
    "INSERT INTO Topics (Theme, Topics, Date) " +
      "OUTPUT 'CONVERT(uniqueidentifier, '" + giveMeGuidID() +
      "'), INSERTED.TopicID, @dateTime, @questionTitle, @subTopic " +
      "INTO Threads (UserID, TopicID, Date, ThreadTitle, ThreadParagraph) " +
    "VALUES (@Theme, @Topics, @Date)";

Although this is a single statement, it performs two inserts into different tables. The 'main' insert is being made into the Topics table. The 'secondary' one, into Threads, is defined by the OUTPUT...INTO clause. Basically, the OUTPUT clause allows you to reference the data being inserted and either return them as a rowset to the client, or (when combined with INTO) direct them into an existing table, like you can see it done here.


text:
Q: USB serial verification in C++ I have a DLL which I intend to send to a 3rd party and I'd like to protect it by restricting it to run only if a specific USB device is connected.
I'm using the setupapi to get the device's serial number (by calling SetupDiGetDeviceInstanceId()).
I would like to make the verification hard to track in case someone disassembles the DLL.
for example, a simple call to SetupDiGetDeviceInstanceId is trackable and if someone wants to use my DLL without the proper serial from the USB, he could easily look for my strcmp in the assembly code and change if(strcmp(...) == 0) to if(strcmp(...) == 1).
What would be a good (and preferably "easy") approach for protecting my code against reverse engineering? Is there maybe a different API (other than setupapi) I could use that would take care of that?
Thanks in advance!

A: I find restricting software like that usually comes and bites you later. The work of finding a way to implement it in a "fool proof" manner is often underestimated and could also unintentionally cripple the product in the end annoying legit customers. Better to instead to provide good support and do frequent updates. Any protection can be circumvented so I wouldn't spend too much time on that.

A: You clearly cannot just read the serial number and compare to a known-good value -- that's trivial to find and remove.
To make things a bit more difficult, use a cryptographic hash (e.g., SHA-256) of the serial number to a cryptographic hash of the correct serial number. Make sure the code for the hash is generated inline, so you a fairly large mess of "stuff" between reading the serial number and doing the jump based on the comparison of the hash value. This won't stop a determined attacker, but it'll stop most people who just glance at the code in a debugger and aren't willing to spend a lot of time on reverse engineering it.
If you want to make things more difficult still, store some of your code in encrypted form, with the correct serial number as the key. At run time, read the serial number and use it to decrypt the code. If it's wrong, the result will be bad code, which you can either execute as is (knowing it will quickly crash and burn) or you can do some sort of checksum to verify the result, and fail a bit more gracefully (i.e., display an error message and die) if the code didn't decrypt correctly.

A: In my opinion it cannot be easy for you and hard for the 3rd party. An id check is too easily found and disabled. I would try to move some essential, hard to figure out computation of your DLL into the external device.


text:
Q: Add span to tablerow I have an ASP.Net login form. Now I want to add a span with an icon in the td next to my input.
It looks like this:

    Some text

    Input with an ID

The thing is; I only know the ID of the input. How can I "find" the td next to it, to add the span?

A: $("table #myInput").parent().next().append("html");

Find input id -> go parent -> next element -> append your icon
Hope it will help you.

A: Use regex to find the content and append span to next td of that td.

$('td').each(function(){
if (/\input\b/gi.test($(this).text())){
 $(this).next().append('span added');
}

  //\b = word boundary
  //g = global
  //i = case insensitive (if needed)
});

    Some text

    Input with an ID

A: If you know the id of the td element then you can simply do this :
// For same element
$('td#input').html('' + $('td#input').text() + '');
// For next element
$('td#input').next().html('' + 'test' + '');**


text:
Q: Velocity- and displacement-proportional forces I have troubles building compound adjectives and enumerating them. In my field (mechanics) we deal with forces which are proportional to displacement or velocity. We tend to call them "displacement proportional forces" and "velocity proportional forces". However, I have a feeling that a hyphen might be missing there: "displacement-proportional" and "velocity-proportional" seems to be "more correct" for me. Which of these two options would be the best?
Further, I would like to enumerate them like: "[...] featuring displacement- and velocity-proportional forces". But it just does not feel right. I have to admit, I have a German background and we do a lot of such shortening while enumerating - but does it work here as well?

A: What you're talking about is a suspended compound or a suspended hyphen. It's a stylistic choice, but it's perfectly acceptable according to the majority of grammarians:
From the Government of Canada's TERMIUM Plus:

When two or more compound adjectives contain the same word, to avoid repetition, writers usually omit that word from the compound(s) at the beginning of the series. Thus, first-class and second-class fares becomes simply first- and second-class fares, with the word class omitted in the first compound adjective.
Note that the hyphen before the omitted word is retained: first- and second-class fares (not first and second-class fares).
This structure is called a "suspended compound." Here are some more examples:
      high- and low-pressure turbine
        interest- or revenue-producing schemes
        short- and long-term plans
        two-, four- and six-metre widths

From The Chicago Manual of Style (17th ed.), 7.88:

When the second part of a hyphenated expression is omitted, the suspended hyphen is retained, followed by a space (or, in a series, by a comma).
      fifteen- and twenty-year mortgages
        Chicago- or Milwaukee-bound passengers
        five-, ten-, and twenty-dollar bills

From Mignon Fogarty's blog post "How to Use a Hyphen":

You can also suspend hyphens. No, it doesn't mean they got in trouble at grammar school, it means that to save space, you can suspend hyphens when you're listing several words describing the same noun. How do you suspend them? Let's say Santa found a fire-proof, dog-proof, and soot-proof vest online. You don't need to write the full compound adjective each time, since each one is modifying the same noun, "vest." Instead of writing "proof" each time, you'll list them, each with only the first part of the compound, followed by a hyphen and then a comma. So if you were suspending hyphens when listing what type of vest Santa was planning on buying, you'd write that he purchased "the fire-, dog-, and soot-proof vest online."

Unless you are following a style guide that specifically gives different guidance, there is nothing wrong with using any of these presentations:

Velocity-proportional forces and displacement-proportional forces.
  Velocity-proportional and displacement-proportional forces.
  Velocity- and displacement-proportional forces.

You can also choose to rephrase it completely:

Forces that are proportional to velocity and displacement.

Which presentation you use is entirely up to you.

A: Without knowing anything about your field, I would agree that those terms, individually, seem better with the hyphens:

velocity-proportional forces
displacement-proportional forces

In German, which I mention because you said you are German, I understand that you make a lot of compound words by joining them together. In a way, hyphenation is the English way of doing it, but we only normally link words that are related to each other. In your examples, the forces are proportional to either velocity or displacement, so it makes sense that they are "displacement-proportional" or "velocity-proportional". There is no need to join the word "forces" with a hyphen as well.
However, your other proposed sentence which attempts to abbreviate the use of both together is incorrect:

"... featuring displacement- and velocity-proportional forces"

You have included a hyphen at the end of the word "displacement" but it is not joined to anything! It should be fine to express this as:

"... featuring displacement and velocity-proportional forces"

It makes sense to me because the word "and" is joining "displacement" and "velocity", then the hyphen links them both to the word "proportional".
Consider this example:

I grew up with both London and Oxford-born friends.

It is fairly clear from context that you didn't grow up with someone called "London". It means you had friends born in both London and Oxford.
However, if you are concerned about any ambiguity in your specific context, it might be best to write:

"... featuring displacement-proportional and velocity-proportional forces"


text:
Q: configure TTL in elastic search with index template I have  requirement to only store data for 10 days in elastic search which is coming through logstash. As I don't have too much data so I am taking approach for setting up TTL through index template.
Could anybody let me know what is exactly I  have to do.
I can go for creation of index template and in template file I have kept the following code in default.json file
{
   "_ttl" : {
    "enabled" : true,
    "default" : "10d"
 }
}

But I am not sure where to keep this file and how that file is getting called.
will it get called automatically or will I have to call manually.
Could anybody Please let me know the step by step configuration.

A: The _ttl field has been deprecated in ES 2 and completely removed in ES 5.
What you should do instead is to use one index per timeframe (day, week, month) that makes sense for your use case.
In Logstash, simply use the following pattern for naming your index "logstash-%{+YYYY.MM.dd}" in your elasticsearch output.
Once you have that set up you can use the curator tool to delete indices older than 10 days, it's pretty straightforward.


text:
Q: Why do we consider only one mass when solving linear harmonic oscillators in quantum physics? While solving the Hamiltonian, books concentrate on the horizontal flow with only one mass attached to the string. Isn't there any consequences if we add more masses and why is friction always ignored?

A:
Isn't there any consequences if we add more masses

Yes, there are indeed consequences. Typically you need to decompose the system into normal modes of oscillation.

and why is friction always ignored?

It's always ignored except in the places where it is not ignored, where we typically use the term damped harmonic oscillator.
(Within quantum mechanics, on the other hand, friction is a rather complicated thing - you can indeed do it, but it requires an open-systems approach and dealing with mixed states instead of pure states. Again, perfectly doable, but certainly not within the confines of a standard undergraduate course in QM.)
If you've only read introductory material, then you've only seen a skewed perspective on the total of things that are done, with a strong bias towards simplicity. If you want to free yourself of that bias and see what happens if you do add friction or more masses, the terms in italics above make good search keywords to get you started.


text:
Q: Simulate "shift" pressing key on checkbox to select multiple rows I have the following input
 <input type="checkbox"  checked={isChecked}
  onChange={handleOnChange}/>

and my function is this
 const handleOnChange = () => {
  let element:any = document.querySelector('input');
 element.onkeydown = (e: { key: any; })  => alert(e.key);
element.dispatchEvent(new KeyboardEvent('keydown',{'key':'Shift'}));
  setIsChecked(!isChecked);

};

This checkbox is created dinamically as I add new rows and I would like to simulate holding the key "shift" so that when I check multiple checkboxes these rows remain selected.
I am using reactjs.

A: There's no native way to do it but you can implement it based on the index you have checked.
const checkboxes = new Array(20).fill(null);

export default function App() {
  const [checked, setChecked] = useState([]);
  const lastChecked = useRef(null);
  const handleChange = useCallback((e) => {
    const index = Number(e.target.dataset.index);

    if (lastChecked.current !== null && e.nativeEvent.shiftKey) {
      setChecked((prev) => {
        const start = Math.min(lastChecked.current, index);
        const end = Math.max(lastChecked.current, index);
        return uniq([...prev, ...range(start, end), end]);
      });
      return;
    }
    if (e.target.checked) {
      lastChecked.current = index;
      setChecked((prev) => [...prev, index]);
    } else {
      lastChecked.current = null;
      setChecked((prev) => prev.filter((i) => i !== index));
    }
  }, []);

  return (

      {checkboxes.map((_, i) => (

            <input
              checked={checked.includes(i)}
              data-index={i}
              type="checkbox"
              onChange={handleChange}
            />
            checkbox {i}

      ))}

  );
}


text:
Q: vue component data and computed properties I am having the following issue.
I am declaring data and i want to setup before, current and day after.
data () {
  return {
    notes: {
      ...
    },
    view: {
      dayCurrent: new Date(),
      dayBefore: new Date().setDate(this.view.dayCurrent.getDate() - 1),
      dayAfter: new Date().setDate(this.view.dayCurrent.getDate() + 1)
    }
  }
}

But once I save this i am getting following error

Error in data(): "TypeError: Cannot read property 'dayCurrent' of undefined" as if my view object does not exist.

Why is this? How do I setup this and avoid this kind of error.

A: Another solution would be to declare dayCurrent outside the return statement and reference it in your other properties.
data () {
  const dayCurrent = new Date();
  return {
    notes: {
      ...
    },
    view: {
      dayCurrent: dayCurrent,
      dayBefore: new Date().setDate(dayCurrent.getDate() - 1),
      dayAfter: new Date().setDate(dayCurrent.getDate() + 1)
    }
  }
}

A: I recommend to initialize your view property in mounted hook as follows :
data() {
    return {
      notes: {
        ...
      },
      view: {
        dayCurrent: '',
        dayBefore: '',
        dayAfter: ''
      }
    }
  },
  mounted() {
    this.view.dayCurrent = new Date();
    this.view.dayBefore = new Date(this.view.dayCurrent.getDate() - 1);

    this.view.dayAfter = new Date(this.view.dayCurrent.getDate() + 1)

  }

new Vue({
  el: '#app',

  data() {
    return {
      notes: {

      },
      view: {
        dayCurrent: '',
        dayBefore: '',
        dayAfter: ''
      }
    }
  },
  mounted() {
    this.view.dayCurrent = new Date();
    let d1 = new Date().setDate(this.view.dayCurrent.getDate() - 1);
    this.view.dayBefore = new Date(d1);
    let d2 = new Date().setDate(this.view.dayCurrent.getDate() + 1);
    this.view.dayAfter = new Date(d2)

  }
})

{{view.dayBefore}}

{{view.dayCurrent}}

{{view.dayAfter}}


text:
Q: Source map generated by webpack works, but can't debug properly I'm new to Webpack and React. I'm building an app using react, and today tried to create a build for the first time (i'm using create-react-app).
When trying to debug using Chrome dev tools, I can see all my Components using the map file generated by webpack/babel, however I get an error when placing a breakpoint inside a basic map method, and trying to access the value of the current item, or the mobx store items.
It's obviously working fine in development mode.
I guess i'm missing something with the configuration?
Thanks,

A: Currently fixed it by setting mangle=false in the uglify plugin. This causes uglify to not change variable names, so the map file has no problem to map to the real variables.


text:
Q: Can a numpy array be compared to an integer? This was in some code that I'll have to use for a homework:
from PIL import Image
import numpy as np
img = np.array(Image.open("image.png"))[:,:,0]
Known = (img > 0).astype(int)

What does the last line - Known = (img > 0).astype(int) - do?
(I tried looking it up, but it's hard to search for the ">" symbol in google search.

A: It does pretty much what you'd expect: it tests the array img to see if it's greater than 0. But since it's a NumPy array, this is an elementwise comparison: each element is compared to 0. This creates an array of Booleans with the result of the comparison for each element. astype(int) converts this array of Booleans to an array of integers. Basically, it's making a mask of the non-zero pixels in the image.

A: (img > 0).astype(int) = 1 if the array cell is bigger than 0 and 0 if not
>>> a=np.array([3,5,3])
>>> (a>0)
array([ True,  True,  True], dtype=bool)
>>> (a>0).astype(int)
array([1, 1, 1])


text:
Q: Android ffmpeg Issue :-  : No such file or directory I am using FFMPEG tool to merge IMAGE & AUDIO files. Its working only in SAMSUNG GALAXY TAB II.
I had tried in many android devices & emulators but unfortunately it had not worked in any of them.
Same issue is posted here also. But Its solutions has not worked for me.
Following is error log of emulator,
02-15 08:46:33.667: D/NIRAV(921): Shell Line : /data/data/org.ffmpeg.android/lib/libffmpeg.so -y -loop 1 -r 1 -i /mnt/sdcard/ffmpeg/img.jpg -i /mnt/sdcard/ffmpeg/myrecord.mp4 -acodec aac -vcodec mpeg4 -s 480x320 -strict experimental -b:a 32k -shortest -f mp4 -r 2 /mnt/sdcard/ffmpeg/out.mp4
02-15 08:46:33.707: D/NIRAV(921): Shell Line : ffmpeg version 0.11.1 Copyright (c) 2000-2012 the FFmpeg developers
02-15 08:46:33.717: D/NIRAV(921): Shell Line :   built on Nov 15 2013 00:50:10 with gcc 4.6 20120106 (prerelease)
02-15 08:46:33.717: D/NIRAV(921): Shell Line :   configuration: --arch=arm --cpu=cortex-a8 --target-os=linux --enable-runtime-cpudetect --enable-small --prefix=/data/data/info.guardianproject.ffmpeg/app_opt --enable-pic --disable-shared --enable-static --cross-prefix=/home/n8fr8/dev/android/ndk//toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/arm-linux-androideabi- --sysroot=/home/n8fr8/dev/android/ndk//platforms/android-3/arch-arm --extra-cflags='-I../x264 -mfloat-abi=softfp -mfpu=neon' --extra-ldflags=-L../x264 --enable-version3 --enable-gpl --disable-doc --enable-yasm --enable-decoders --enable-encoders --enable-muxers --enable-demuxers --enable-parsers --enable-protocols --enable-filters --enable-avresample --enable-libfreetype --disable-indevs --enable-indev=lavfi --disable-outdevs --enable-hwaccels --enable-ffmpeg --disable-ffplay --disable-ffprobe --disable-ffserver --disable-network --enable-libx264 --enable-zlib --enable-muxer=md5
02-15 08:46:33.717: D/NIRAV(921): Shell Line :   libavutil      51. 54.100 / 51. 54.100
02-15 08:46:33.717: D/NIRAV(921): Shell Line :   libavcodec     54. 23.100 / 54. 23.100
02-15 08:46:33.717: D/NIRAV(921): Shell Line :   libavformat    54.  6.100 / 54.  6.100
02-15 08:46:33.717: D/NIRAV(921): Shell Line :   libavdevice    54.  0.100 / 54.  0.100
02-15 08:46:33.727: D/NIRAV(921): Shell Line :   libavfilter     2. 77.100 /  2. 77.100
02-15 08:46:33.727: D/NIRAV(921): Shell Line :   libswscale      2.  1.100 /  2.  1.100
02-15 08:46:33.727: D/NIRAV(921): Shell Line :   libswresample   0. 15.100 /  0. 15.100
02-15 08:46:33.727: D/NIRAV(921): Shell Line :   libpostproc    52.  0.100 / 52.  0.100
02-15 08:46:33.747: D/NIRAV(921): Shell Line : /mnt/sdcard/ffmpeg/img.jpg: No such file or directory
02-15 08:46:33.747: D/NIRAV(921): Exit Value : 1

I had verified the path of img.jpg & myrecord.mp4 files.
I am using android-ndk-r7 to build ffmpeg.


text:
Q: How to disable a button if all of the inputs is empty in asp.net core I'm trying to submit a form. I have a binding dropdown list and an input field. The dropdown list has three input fields. 0 = pending, 1 = accepted, and 2 = denied. I want to store data if the dropdown value is not 0/pending. If the dropdown is changed/ not pending or the comment input field have not empty, then the Save button enables. Otherwise, the save button is disabled.

function success() {
            if (document.getElementById("textsend").value === "") {
                document.getElementById('button').disabled = true;
            } else {
                document.getElementById('button').disabled = false;
            }
        }

                Decision
                <select asp-for="Heating.Status" asp-items="Html.GetEnumSelectList<ApplicationDecision>()" class="form-control">
                    <option></option>
                </select>

                Comments
                <textarea class="form-control " id="textsend" onkeyup="success()" style="height:100px" maxlength="2000"></textarea>

                <input type="submit" id="button" value="Save" class="btn btn-blueTwo float-right" disabled />

But I can't use the dropdown list to add these conditions. Couldn't you please help me?

A: Finally, I solved this problem.

                    Decision
                    <select asp-for="BurnOut.Status" id="StatusResponse" asp-items="Html.GetEnumSelectList<ApplicationDecision>()" class="form-control ">
                        <option></option>
                    </select>

                    Comments
                    <textarea class="form-control " id="CommentResponse" asp-for="BurnOut.Remarks" style="height:100px" maxlength="2000"></textarea>

                    <input type="submit"  value="Save" class="btn btn-blueTwo float-right save-btn" />


text:
Q: Why does Luma sample use widget and block for home page? In the sample data with the Luma theme the home page is implemented with a Widget ("Home Page" Widget of type "CMS Static Block") plus block ("Home Page Block" containing the page content area html).
Particularly for a learning example, why not simply use a Page? It seems you can put the content into the Page, and assign the page to the CMS Home Page > Main Content Area.  Would that not achieve the same effect?
(Related question with diagram: How does Luma theme home page work?)

A:
why not simply use a Page?

That's the goal of sample data: show samples / examples of what can be achieved in Magento. The widget is there to show how widgets work.

Would that not achieve the same effect?

Yes you can get the same effect by copy/paste the content of the CMS block in the CMS page content and remove the widget.
It becomes useful to use such widgets when you have several different blocks in your page and they have different purposes. E.g one widget for site presentation and one widget for current sale. You can disable the current sale block when the sale is over and thus you don't have to delete/comment content from the page

A: So Blocks are there to fill content into the page Widget structure that is already provided by the LUMA theme?
So LUMA sounds like it provides page structure via Widgets and the content developer finds the correct Widget to place the Content in?
Is there a LUMA "page Widget map" that points out the location of the Widgets on a particular page?
As far as theming goes do you see any problem with the way I am using CSS and not LESS?
OMG, this is such great info!! Thank you so much!!!


text:
Q: Trigger performance - UPDATE statement joining on INSERTED I have a trigger (MS SQL Server) on TABLE_A that fires on an update that looks basically like the following (I've changed the names of the tables/trigger to simplify):
CREATE TRIGGER [dbo].[TABLE_A_B_UPDATE] ON [dbo].[TABLE_A]
FOR UPDATE
AS

IF UPDATE ( [ATTRIBUTES] )
BEGIN
    BEGIN TRAN
    -- update the attributes of the table C records
    UPDATE [TABLE_C]
    SET [ATTRIBUTES] = I.ATTRIBUTES
    FROM TABLE_C C
    INNER JOIN INSERTED I ON
        C.UNIQUE_ID = I.UNIQUE_ID AND C.USER_ID = I.USER_ID
    WHERE E.[ATTRIBUTES] & 4 = 0

    UPDATE  [TABLE_B]
    SET     [ATTRIBUTES] = I.ATTRIBUTES
    FROM TABLE_C C
    INNER JOIN INSERTED I ON
        C.UNIQUE_ID = I.UNIQUE_ID AND C.USER_ID = I.USER_ID
    INNER JOIN [TABLE_B] B ON
        B.UNIQUE_ID = C.UNIQUE_ID AND B.USER_ID = C.USER_ID
    WHERE B.[ATTRIBUTES] & 4 = 0

    COMMIT TRAN
END

Currently by design, there is only ever ONE record in the INSERTED table (we are only updating one record at a time from a UI).
What we have discovered is that, as the number of records increase in TABLE_B, trigger performance degrades rapidly. For example, with around 12000 or so records in TABLE_B, this update statement takes around 40 seconds (we established a timeout of 30 seconds). As I remove records from TABLE_B, performance gradually improves. As this was an unacceptable solution, I had to find ways to improve this update statement.
Through testing/profiling, I found that the problem was with the second update statement (update TABLE_B). The first update statement works without problem; if I change the second update statement to its equivalent SELECT statement, it also runs fast.
The solution that I found was to shove the singular record in the INSERTED table into a #TEMP table and join on that instead. I was also able to do this with a table variable as well, but performance was terrible until I created an index on it. This immediately resolved the problem and the update now runs almost instantaneously.
My question is this - why did this solve the performance problem? Perhaps I am looking at this in the wrong way, but I can't imagine why I would need an index on a one record table. I have read that the INSERTED table isn't created with an index on it, but it still seems odd to me that I should need one.
Thanks in advance!
EDIT: As pointed out, I forgot to mention some other relevant table structure tidbits.
TABLE_B indeed has a compound primary key/index created as follows:
CONSTRAINT [TABLE_B] PRIMARY KEY CLUSTERED
(
    [USER_ID] ASC,
    [UNIQUE_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

TABLE_C has the same index as above. All indexes were rebuilt at the start of testing.
Both tables have additional triggers that are being fired - however, during testing, I disabled these triggers to determine where specifically the performance hit was. Disabling all other triggers did not improve performance.
EXECUTION PLAN:
I'm not super savvy on execution plans for triggers, but as far as I can tell, you can view them from the profiler with the showplan option turned on. I believe this is the relevant plan:

I'm not sure what to think about this plan, other than I noticed that 80% on that clustered index scan. Hopefully this is what was being asked for, if not, I can repost. Thanks again!

A:
as the number of records increase in TABLE_B, trigger performance degrades rapidly

That would imply the updates do not have appropriate indexes available, or are unable to use them for some reason, on TABLE_B or the tables that it is joined to.
Without more detail about the table layout (what indexes you have on each of the tables) and the query plan that SQL has decided to use we can't help you in much detail, so I suggest you update the question with that information.
Some first thoughts:

FROM TABLE_C C INNER JOIN INSERTED I ON C.UNIQUE_ID = I.UNIQUE_ID AND C.USER_ID = I.USER_ID

As you say the performance is tied to TABLE_B this is probably OK, though again the query plan would be helpful information to provide. Presumably you have an index on TABLE_C.UNIQUE_ID or it is the primary key or subject to a unique constraint.

INNER JOIN [TABLE_B] B ON B.UNIQUE_ID = C.UNIQUE_ID AND B.USER_ID = C.USER_ID

With the right indexes/keys this should not be an issue either. For maximum efficient for this specific statement TABLE_C should have an index covering UNIQUE_ID & USER_ID and TABLE_B one covering UNIQUE_ID & USER_ID and including ATTRIBUTES.

WHERE B.[ATTRIBUTES] & 4 = 0

This may be significant. Depending on how TABLE_B and TABLE_C are getting joined (again, provide the index details and query plan) this could be forcing a table scan of TABLE_B. The expense of that operation would grow at linearly with the number of rows in TABLE_B.

A:
as the number of records increase in TABLE_B, trigger performance degrades
  rapidly.

Which indicates the update statements accessing TABLE_B are inefficient - because of missing indices. Standard debugging will help.


text:
Q: Stop NSRunLoop On Keypress I'm writing a command line foundation tool in Mac OS X and would like the tool to quit on a keypress such as 'q'.  The code is launching an asynchronous request for retrieving data from a remote server.  This necessitates the NSRunLoop.  At least that's what I understand I need to do.
Can someone tell me how to stop the runloop on the specific keypress?
Below is the code snippet.
int main (int argc, const char * argv[]) {

BOOL keepRunning = YES;
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

Requestor *myRequestor = [[Requestor alloc] init];
[myRequestor GetData];

NSRunLoop *runLoop;
runLoop = [NSRunLoop currentRunLoop];

while (keepRunning && [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);

[pool drain];
return 0;
}

Thank you!

A: I haven't done this myself, but I would expect that you want to use [[NSFileHandle fileHandleWithStandardInput] readInBackgroundAndNotify] and register to receive the NSFileHandleReadCompletionNotification notification.  If you receive a 'q', do what ever cleanup you need to and call exit().

A: Well, my initial theories and experiments starting with your existing code didn't turn up much in the way of usable code.
I'm imagining that what you're looking for is something like how, on Windows, you can run something in a command line shell window, and when the process has finished, it says something like "Press the Q key to continue...". When you bring the window forward (if it isn't already frontmost), and press the Q key, the window closes.
Are you planning on calling this command line tool from your primary application, or is this command line tool something the end-user will be interacting with directly? (For example, if the latter, they'd be calling it from a Terminal window, hmm, then I think Ken's code could probably be combined with mine to make the following. Note that in its current form, this only works after you press Q and then hit Return?
#import <Cocoa/Cocoa.h>

@interface Requestor : NSObject <NSApplicationDelegate> {
    BOOL            gotData;
    NSFileHandle    *stdIn;
}
- (void)getData;
- (void)requestorGotData:(id)sender;
@end

@implementation Requestor

- (id)init {
    if (self = [super init]) {
        gotData = NO;
        stdIn = nil;
        [NSApp setDelegate:self];
    }
    return self;
}

- (void)getData {
    NSLog(@"getting data.........");
    gotData = NO;

    [self performSelector:@selector(requestorGotData:)
               withObject:nil
               afterDelay:5.0];
}

break
- (void)requestorGotData:(id)sender {
    NSLog(@"got data");
    gotData = YES;
    NSLog(@"Press 'Q' key to continue...");
    stdIn = [[NSFileHandle fileHandleWithStandardInput] retain];
    [[NSNotificationCenter defaultCenter]
       addObserver:self
          selector:@selector(fileHandleReadCompletion:)
              name:NSFileHandleReadCompletionNotification
            object:stdIn];
    [stdIn readInBackgroundAndNotify];
}

- (void)fileHandleReadCompletion:(NSNotification *)notification {
    NSLog(@"fileHandleReadCompletion:");
    NSData *data = [[notification userInfo]
                    objectForKey:NSFileHandleNotificationDataItem];
    NSLog(@"data == %@", data);
    NSString *string = [[[NSString alloc]
                             initWithData:data
                        encoding:NSUTF8StringEncoding] autorelease];
    if (string) {
        string = [string stringByTrimmingCharactersInSet:
                  [NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([[string lowercaseString] isEqualToString:@"q"]) {
            [stdIn closeFile];
            [stdIn release];
            [[NSNotificationCenter defaultCenter] removeObserver:self];
            [NSApp terminate:nil];
        } else {
            [stdIn readInBackgroundAndNotify];
        }
    }
}
@end

break
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    [NSApplication sharedApplication];

    Requestor *requestor = [[Requestor alloc] init];
    [requestor getData];

    [NSApp run];

    [requestor release];

    [pool drain];
    return 0;
}

A: If you haven't already considered libcurses, perhaps that will help you.  It's really straightforward to catch keypresses with it, but what I'm not 100% about is if you can get it to work without the entire terminal window being used.
The curses bit alone is just:
#include <ncurses.h>

initscr();

/* snip */

char c;
while (c = getch()) {
  if (c == 'q') {
    // Put your cleanup and shutdown logic here
  }

  /* any other keypresses you might want to handle */
}

EDIT | You probably don't wanna put that tight loop inside your run loop... just call getch() each time the runloop ticks over.


text:
Q: htaccess to not show index.php in sub directory I have a simple page structure like below
/directory/subdir_1/index.php
/directory/subdir_2/index.php
....
(there are no other files in these directories)
is it possible to have 'fake/pretty' urls for the above files as below?
/directory/subdir_1
/directory/subdir_2
...
so this path would show whether the visitor typed that,/directory/subdir_2/ or /directory/subdir_2/index.php.
Many thanks

A: You could check $_SERVER['REQUEST_URI'] at the top of index.php to get the address and if the string ends with index.php redirect them. However, I would suggest not necessarily doing this and leaving it. Just change the links on your page to not include index.php.

A: If you have
DirectoryIndex index.php

in your .conf or .htaccess file, it should do that anyway. see http://httpd.apache.org/docs/2.2/mod/mod_dir.html#DirectoryIndex

A: Question is too unclear to me.
but by default web-server works as you described:
Both /directory/subdir_2/ or /directory/subdir_2/index.php would run index.php from the /directory/subdir_2/.
If you want to redirect a client in case it requests /directory/subdir_2/index.php, to the /directory/subdir_2/ you'd better not to do it. Just have all links on your site without trailing index.php.


text:
Q: System.InvalidOperationException: 'The LINQ expression how I Use my Type REferencesType In the base document, I have a field that inherits from the BaseReferencesType class. It's virtual, why can't I do anything when I'm busy.
This field which i want get
public virtual ReferenceType ReferenceType { get; }

And my script:
var document = await _context.BaseDocuments
    .Where(x => bulkPostDto.Documents.Contains(x.ReferenceType) &&
                x.CreatedDate.Value.Date >= bulkPostDto.Start.Date &&
                x.CreatedDate.Value.Date <= bulkPostDto.Finish)
    .OrderBy(x => x.DocumentDate)
    .ToListAsync();

Now my problem looks like this@

System.InvalidOperationException: 'The expression 'x.ReferenceType' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty'). Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.'

I transferred data through the service, but received an error
{
  "documents": [
    0
  ],
  "start": "2022-01-05T13:16:31.289Z",
  "finish": "2023-01-05T13:16:31.289Z",
  "repostAlreadyPosted": true,
  "postUnposted": true,
  "interruptWhenPostFailed": true
}

Photo class ReferenceType


text:
Q: Display adwords stats on intranet dashboard My company is requiring me to add our daily spend totals, ctr, conversions in a table on our intranet page.
I was planning on doing this using the Adwords API but the dashboard is done in ASP.NET Core and there is no documentation for that.
Would Google Scripts, which I haven't used, help me pull this data using a JSON call from our website intranet page or is there another solution to avoid using Adwords API?
Is there a simple solution to pull this simple data?


text:
Q: Python parse mathematical text expression I was wondering if anyone knew of a good python library for evaluation text-based mathematical expressions. So for example,
>>> evaluate("Three plus nine")
12

>>> evaluate("Eight + two")
10

I've seen similar examples that people have done for numeric values and operators in a string. One method used eval to compute the literal value of the expression. And another method of doing this used regex to parse the text.
If there isn't an existing library that handles this well I will probably end up using a combination of the regex and eval techniques for this. I just want to confirm that there isn't already something like this already out there.

A: You could try pyparsing, which does general recursive descent parsing. In fact, here is something quite close to your second example.
About your other suggestions.

*

*See here about the security issues of eval (ironically, using it for a calculator).

*Fundamentally, regular languages are weaker than pushdown automata languages. You shouldn't try to fight a general parse tree problem with regexes.


text:
Q: How to change the existing autofiled id to custom Integer primary key in django - Sqlite3? We didn't decide any primary key before creating the database and Django created a custom autoincrement primary key called 'id'. We have 20 tables with this primary key.
Now, I want to migrate from this auto-increment 'id' primary key to a custom integer primary key without auto-increment. Also, I would like to keep the name of the new primary key as 'id' itself.
What is the shortest and easier way of migrating without changing the existing id?
Will this work?
If I change the SQLite database (remove auto increment)
CREATE TABLE "users" (`id`  integer NOT NULL PRIMARY KEY AUTOINCREMENT, `name`  varchar ( 5 ) NOT NULL, `place` varchar ( 5 ) NOT NULL);

Add this line in my model
id = models.BigIntegerField(primary_key=True)

After this, I can use makemigrations and migrate ?
DB used: SQLite3
Thank you in Advance.


text:
Q: Number of zero elements in a vector Define a vector $v=(v_1,...,v_n) \in \mathbb{Z}_{2^{\alpha}}$ (i.e. the elements are $\alpha$-bit length).
My question: What is the expected number of components of the vector $v$ that are zero?
My approach: The probability of an element of the vector to be zero is exactly $\frac{1}{2^{\alpha}}$. How to continue from this point?
By the way, I suspect the answer is $\frac{n}{2^{\alpha}}$. But, I need a formal proof.