Q:

Call PHP function in ajax

My problem is the following:
I have a real simple PHP file called "writeSettings2.php" that has:
<?php
    $text=$_GET["text"];
     setcookie("MG_FileTree_Opener_SelPath", $text);
?>

And then I have my PHP page, in which I have a JavaScript function called "makeChanges", this function is called in a input type submit function and gets the combobox selected value and calls through xmlhttp the PHP function above like so:
<input type="submit" id="choice" value="Escolher" name="Esc" onClick="makeChanges()">

And the function "makeChanges" is like:
function makeChanges(  )
{
    var selObj = document.getElementById('opiniao');
    var selIndex = selObj.selectedIndex;
    var str = selObj.options[selIndex].text;

    if (window.XMLHttpRequest)

    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();

    }
    else
    {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
   xmlhttp.open("GET","writeSettings2.php?text="+str,true);
   xmlhttp.send(null);
   history.go(0);
}

Basically what I'm doing is use the JavaScript on the client fo call PHP function to rewrite the client cookie, and then refresh the page to get PHP to rewrite the page with the new info on the cookie.
This code works fine, but only for the fist 2 times! For instance my combox has item 1 and 2.
I load it and is item 1.
Change to item 2.
Change back to item 1.
Change to item 2 again ---- FAILS never changes again, it always remains on 1.
Any suggestions?

A:

Your browser is caching the ajax response. You need to add a random value to the ajax request, or put the no-cache header in the called page.
You can change the javascript like so to fix it:
var str = selObj.options[selIndex].text+'&random='+(new Date()).getTime();

And/Or use the following php header:
header("Cache-control: no-cache");


Q:

Generate table from Object data

I have an object like the one below:
var obj = {
   a : {
      x : 1,
      y : 2,
      z : 3
   },
   b : {
      x : 1,
      y : 2,
      z : 3
   }
}

With it, I will like to generate the following table. Format is showed bellow
http://jsfiddle.net/gD87t/
I am trying to get the elements from object and and trying to append but getting confused with the rowSpan value
var tr = document.createElement('tr');
for(var i in obj){
   var td = document.createElement('td');
   td.rowSpan = ? // Here I am getting confused.
}

Can a template engine solve my problem?
What is the best way to do this?

A:

Here's one way of doing it with a recursive function in pure js:
function addObjectToTable(table, obj, tr) {
  var rows = 0;
  for (key in obj) {
    if (tr == null) {
      tr = document.createElement('tr');
      table.appendChild(tr);
    }

    var td = document.createElement('td');
    td.textContent = key;
    tr.appendChild(td);

    var value = obj[key];
    if (typeof value != 'object') {
      var td = document.createElement('td');
      td.textContent = value;
      tr.appendChild(td);
      rows += 1;
    }
    else {
      var subrows = addObjectToTable(table, value, tr);
      td.setAttribute('rowspan',subrows);
      rows += subrows;
    }

    tr = null;
  }
  return rows;
}

Which would be called like this:
var table = document.createElement('table');
addObjectToTable(table,obj);
document.body.appendChild(table);

Note that when first called, the tr parameter is null, since we always have to create a new row at the top level. When the function is called recursively though, the tr parameter is passed in from the upper level since lower levels will intially be adding to the the row of their parent object.
The function returns the number of rows added, so when it is called recusively the caller will know what to set the rowspan value to.
Fiddle link

A:

I couldn't find an answer which handled circulars, and I also decided to do this without any unnecessary DOM writes. Also, I didn't follow the exact mark-up the OP requested because I felt nesting tables was more convenient for a recursive operation such as this- and serves close to the same visual purpose.
So, here's the function I've created:
function dataToTable (data) {
    var storage = [];
    return (function buildTable (data) {
        var table = '

';
        var name, value;
        // Add the object/array to storage for cirular detection.
        storage.push(data);
        for (name in data) {
            value = data[name];
            table += '
' + name + '	';
            // If the value is an object we've put in storage (circular)
            if (storage.indexOf(value) !== -1) {
                table += 'Circular';
            } else if (typeof value === 'object') {
                table += buildTable(value);
            } else {
                table += value;
            }
            table += '
';
        }
        return table + '

';
    }(data));
}

Here is the object I used to test:
var obj = {
   a : {
      x : 1,
      y : 2,
      z : 3
   },
   b : {
      x : 1,
      y : 2,
       z : {
           test1: 0,
           test2: {
               test3: 1,
               test4: ['a','b','c']
           }
       }
   }
};
obj.c = obj;
obj.b.z.test2.test4.push(obj.a);

The function will turn this object into an HTML table. What you do with the table is up to you. On my fiddle, I used the DOM to add the table to a DIV (document.getElementById).
http://jsfiddle.net/5RhXF/1/
I hope you'll find my implementation clear.
UPDATE::
I decided to test this on the jQuery library, and it worked! Except, the functions were printing as their toString value with no good format for text.. Which makes sense, but not very helpful. So, I'm thinking this is a nice and easy way to look through APIs for frameworks/libraries and what-not. Therefore, I added prettify for syntax-highlighting of functions, and also added a type-check for functions in the table generator, and a quick class to get rid of borders around the prettify box (as there's already a border on the table cell). If anyone is interested in the version designed for source-reading/debugging, here's the fiddle:
http://jsfiddle.net/5RhXF/7/


Q:

swfupload - multiple instances and setting dynamic data with setPostParam

I am using swfupload, and have a bunch of 'Attach File' links and each one of them opens up the same Jquery Dialog which is associated with 1 swfupload instance. I tried to set custom post params but it fails:
www.arianhojat.com/temp/code/swfupload/index.html
if you remove the 'setPostParam' line its fine but id like to set params... It gives an error in firebug: "uncaught exception: Call to SetPostParams failed"...
So instead i tried an alternate solution... I came up with recreating the swfupload object each time the Dialog opens up... and destroy it after it closes... but i get a "uncaught exception: Could not find Flash element" at the end. not sure if that is a critical error as the popup still shows up if you reclick links. I think this may be possiblly the way to go but not sure about that error
Here is my online example of that code in action:
http://www.arianhojat.com/temp/code/swfupload/index_destroy.html
(PS the file upload should close the dialog and alert an error, as I dont have that host setup right now to correspond to the java servlet backend i have to handle it... just wanted to get the frontend working first and get rid of that error so errors are first handled gracefully without firebug user like myself noticing a js error occured.)

A:

You have to use css positioning to hide (and not display:block/none;) and show your dialog as the Flash reloads when you hide/unhide it and goofs.


Q:

Is it possible to run three phase motor with single phase supply? How?

I have rubber mixer machine that motor need three phase supply. Unfortunately I only have single phase supply. I heard a rumor that three phase motor can be run with single phase supply. So, pls guy here help me out of this problem. Your answer is so greatful in advance.

A:

A variable-frequency drive (VFD) should be preferred over the Steinmetz connection. The Steinmetz connection only allows the motor to work at about 70% of its rated power and produce 20% to 30% of the rated starting torque. I suspect that a rubber mixer will not tolerate that limitation.
A VFD of a current design from a reputable manufacturer will allow most motors to work at full power and produce rated starting torque. Most manufacturers have both variable torque / standard duty models and constant torque / heavy duty models. For a rubber mixer, you should buy the heavy duty model. Most of the well-known international manufacturers of industrial electrical equipment make VFDs.
Single-phase input, three-phase output are only widely available for 230 volt motors rated up to about 3 Hp (2.2 kW). Larger sizes are available, but more difficult to find.


Q:

How to download an MTOM attachment in VB6

Please, someone can show me an example about how to download an MTOM attachment and save it to disk using VB6?
At the moment I am able to get a response from my ws, using this code:
Dim objDom As Object
Dim objXmlHttp As Object
Dim strRet As String
Dim intPos1 As Integer
Dim intPos2 As Integer
On Error GoTo Err_PW
' Create objects to DOMDocument and XMLHTTP
Set objDom = CreateObject("MSXML2.DOMDocument")
Set objXmlHttp = CreateObject("MSXML2.XMLHTTP")

'Set objXmlHttp = New MSXML2.XMLHTTP40
' Load XML
objDom.async = False
objDom.loadXML XmlBody

' Open the webservice
objXmlHttp.Open "POST", AsmxUrl, False
' Create headings
objXmlHttp.setRequestHeader "Content-Type", "text/xml; charset=utf-8"
objXmlHttp.setRequestHeader "SOAPAction", SoapActionUrl

' Send XML command
objXmlHttp.Send (objDom.xml)
' Get all response text from webservice
strRet = objXmlHttp.responseText

But from this point I don't know how to proceed to grab the MTOM attachment.
This is what return from ws:
--uuid:0b9372cf-63bb-484f-87f3-7bedfaa776fb
Content-Id: <rootpart*0b9372cf-63bb-484f-87f3-7bedfaa776fb@example.jaxws.sun.com>
Content-Type: application/xop+xml;charset=utf-8;type="text/xml"
Content-Transfer-Encoding: binary

<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body><ns2:getContentStreamResponse xmlns:ns2="http://docs.oasis-open.org/ns/cmis/messaging/200908/" xmlns="http://docs.oasis-open.org/ns/cmis/core/200908/">
<ns2:contentStream>
<ns2:length>2572861</ns2:length>
<ns2:mimeType>application/vnd.openxmlformats-officedocument.wordprocessingml.document</ns2:mimeType>
<ns2:filename>SF-MASTER - SDTC.docx</ns2:filename>
<ns2:stream>
<xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:4b7c8c60-fc9e-4da8-92fc-aa8c2fdfb401@example.jaxws.sun.com"/></ns2:stream>
</ns2:contentStream>
</ns2:getContentStreamResponse>
</S:Body>
</S:Envelope>
--uuid:0b9372cf-63bb-484f-87f3-7bedfaa776fb
Content-Id: <4b7c8c60-fc9e-4da8-92fc-aa8c2fdfb401@example.jaxws.sun.com>
Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
Content-Transfer-Encoding: binary

PK
31/05/2018 10:04:06: UUID documento: 0b9372cf-63bb-484f-87f3-7bedfaa776fb
31/05/2018 10:04:06: Tag finale: --uuid:0b9372cf-63bb-484f-87f3-7bedfaa776fb--
31/05/2018 10:04:06: lunghezza documento: 2572861

Thank you very much

A:

Use this as a guide and modify your code to save the returned file data as a binary file.
Add to top of function
Const adTypeBinary = 1
Const adSaveCreateOverWrite = 2

Dim varByteArray, ado
Dim strFile as String

After you send the request insert this code
If objXmlHttp.Status <> "200" Then
    Exit Function
End If

' Pull this from returned header data
strFile = "SF-MASTER - SDTC.docx"

' get file contents
varByteArray = objXmlHttp.ResponseBody

Set objXmlHttp= Nothing

'Now save the binary file
On Error Resume Next
Set ado = Nothing
Set ado = CreateObject("ADODB.Stream")
ado.Type = adTypeBinary
ado.Open
ado.Write varByteArray
ado.SaveToFile strFile, adSaveCreateOverWrite
ado.Close


Q:

How can we formally state a series converges?

If the series $\sum_{n=0}^{\infty}na_{n}$ converges absolutely, how can we write this using the definition of convergence?
The definition of convergence states this:
"The series $\sum_{n=1}^{\infty}a_{n}$ converges if and only if, given $\epsilon \gt 0$, there exists an $N \in \mathbf N$ such that whenever $n \gt m \ge N $ it follows that: |$ a_{m+1} + a_{m + 2} + ... + a_{n}| \lt \epsilon$ "
How do I extend this to my current series above? What is tricking me and I'm not too sure if what I'm doing is correct is the $n$ infront of the $a_{n}$. If that series converges absolutely, does it imply this:
|$ na_{m+1} + na_{m + 2} + ... + na_{n}| \lt \epsilon$ ?
Any help would be appreciated.

A:

The correct inequality is $(m+1)|a_{m+1}|+(m+2)|a_{m+2}|+\cdots+n|a_n|<\epsilon$.


Q:

write super script string in python

While ploting the data using matplotlib, I need to write the superscript string for 2 in m2. How can I do it?
import matplotlib.pyplot as plt

x = [1,3,5,7,9,10,12]
y = [2,5,6,3,9,11,4]

plt.scatter(x, y)
plt.xlabel('x (m2)')
plt.ylabel('y')
plt.show()
plt.close()

A:

you can use unicode strings
plt.xlabel(u'x (m²)')
plt.xlabel(u'y')

Using
plt.xlabel('x (m$^2$)')

gives a slightly different result - the 2 looks kind of weedy compared to the unicode version.


Q:

jQuery filter dropdown

Ok I have a drop down of countries and only want to display USA and Canada
I'm looking at something like this but don't think I'm doing this right
// Filter Countries
$('#selectId').filter(function() {
   return $('#option').val() == ('USA' || 'CANADA');
});

Example HTML:
<select id="country">
  <option value="AFG">Afghanistan</option>
  <option value="ALB">Albania</option>
  <option value="ALG">Algeria</option>
  <option value="CANADA">Canada</option>
  <option value="USA">United States</option>
</select>

A:

The || construct you have is invalid. Try this.
$(this).val() == 'USA' || $(this).val() == 'CANADA';

To remove the options that don't match, you could do something like this.
$().ready( function () {
  $('#country option').filter(function() {
     return !($(this).val() == 'USA' || $(this).val() == 'CANADA');
  }).remove();
});


Q:

How to delete multiple values from a vector? But not all of them

Say I have two vectors,
set <- c(1, 1, 1, 1, 3, 3, 4, 4, 8, 8, 10)
played <- c(1, 3, 1, 4)

I want to remove the "played" numbers from the original set, but I don't want to remove all of the 1, 3 or 4's.
Such that the resulting vector should be,
1,1,3,4,8,8,10

At the moment I am using a loop but this is not a very efficient method. Is there a function to do what I want.
Note: This is not a duplicate of Not a duplicate of
How to delete multiple values from a vector?
but rather an expansion, all about not removing all of the values.
Re-Edit: I said order matters, but I was mistaken.

A:

You can get it very simply with pmatch:
set[-pmatch(played,set)]
# [1]  1  1  3  4  8  8 10

And here's another idea:
rep.int(seq_len(max(set)),tabulate(set)-tabulate(played,nbins=max(set)))
# [1]  1  1  3  4  8  8 10

A:

You can use the table function:
a=table(set)
b=table(played)
a[names(a)%in%names(b)]=a[names(a)%in%names(b)]-b
as.numeric(rep(names(a),a))

[1] 1  1  3  4  8  8 10

You can also do:
a=merge(table(set),table(played),by.x="set",by.y="played",all=T)
a[is.na(a)]=0
as.numeric(as.character(rep(a$set,a$Freq.x-a$Freq.y)))
[1]  1  1  3  4  8  8 10

A:

Still using a loop, but this seems pretty good:
p_list = split(played, cumsum(duplicated(played)))
for(p in seq_along(p_list)) {
    set = set[-match(p_list[[p]], set)]
}

set
# [1]  1  1  3  4  8  8 10

This breaks played up by duplicates so that we can process each piece in a vectorized match call.


Q:

lazarus grids key-value pair

In the lazarus (and also delphi probably) documentation about grids, we can find the next description for the InsertRow function:
Function InsertRow
    Inserts a row in the grid and sets
    the Key-Value pair. Returns the
    index of the newly inserted row.

What is this key-value pair?

A:

This is related to the TValueListEditor, and not grids in general. The TValueListEditor is similar in appearance to the Delphi Object Inspector. For brevity, I'll refer to it as VLE in the text below.
TValueListEditor.InsertRow takes three parameters:
function InsertRow(const KeyName: string; const Value: string;
  Append: Boolean): Integer;

The keyname parameter is the name of the key (the left column of the VLE). Value is the key value (the right column of the VLE). This is stored in the same manner as the TStrings key=value pairs in the Strings property. For instance, calling it using InsertRow('Testing', '123', False) would store Testing=123.
Append merely controls whether the new entry is added before or after any already selected item in the VLE. If the VLE is empty, it has no effect.
For more information, see the Delphi VCL help


Q:

Разместить HBox с помощью StackPane

Нужно написать простой графический интерфейс для программы нахождения корня уравнения методом половинного деления. В центре окна находятся 3 TextField, а снизу кнопка для начала обсчета и Label для вывода результата. Я планировал для начала создать два HBox, запихнуть в один все что должно быть в центре, а во второй все что внизу. Затем с помощью StackPane разместить первый HBox в центре, а второй внизу. И при выполнении заметил что они вообще не меняют места. Получается что в javafx одними layout нельзя менять меся других layout, или я что-то не так сделал, и нужно это сделать другим способом.
P. S. Знаю что если не написать "и быстро" будут понижать рейтинг, поэтому И БЫСТРО
 public void start(Stage primaryStage) throws Exception {

        TextField leftLimitTextField = new TextField("Enrer left limit");
        TextField rightLimitTextField = new TextField("Enter right limit");
        TextField mistakeTextField = new TextField("0.0001");

        HBox metodOfDivisionSpecification = new HBox(leftLimitTextField,
                rightLimitTextField, mistakeTextField);

        Label result = new Label("Here be result");
        Button startCalculationButton = new Button("Start calculation");
        //TODO: button event listener
        HBox calculationsPanel = new HBox(startCalculationButton, result);

        StackPane root = new StackPane();

        root.getChildren().addAll(metodOfDivisionSpecification, calculationsPanel);
        StackPane.setAlignment(metodOfDivisionSpecification, Pos.CENTER);
        StackPane.setAlignment(calculationsPanel, Pos.BOTTOM_CENTER);

        Scene scene = new Scene(root, 300, 200);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

A:

Похоже, что в этой ситуации нужен javafx.scene.layout.BorderPane.
StackPane не про это, он для размещение компонентов поверх друг друга.


Q:

How to post a value into a WebService and get another value parsed? HTML

I want to use my 'result.text' from the result of the barcode scan to search in a webservice to get 'frn2'. This is an android application and I'm fairly new to this so incase you need more info, I can provide it.
JS:
       <script>
     function scan() {
    cordova.plugins.barcodeScanner.scan(
            function(result) {
                console.log(result.text)
                var barcode_res = (" ID\n" +
                    "Result: " + result.text);
                window.alert("ID Result: " + result.text);
            },
            function(error) {
                window.alert("Scanning Failed: " + error);
            },

            //getFRNbyMATRIC webservice call
            function(webserviceCall) {
                var string = result.text;
                $.post("http://localhost:8081/WebService.asmx?
                  op=getFRNByMATRIC", {
                    MATRIC: string
                }, function(response) {
                    frn2 = response;
                }).error(function() {
                    window.alert("Sorry could not proceed");
                });
                //return DCID Number
                return frn2;
            }

        )

    window.open("https://example.com/?frn=" + frn2);

         }
        </script>

XML/WEBSERVICE:
         <?xml version="1.0" encoding="utf-8"?>
<ArrayOfTEST1 xmlns="http://tempuri.org/">
 <TEST1>
   <ID>int</ID>
   <FRN>int</FRN>
   <FRN2>string</FRN2>
   <MATRIC>int</MATRIC>
   <numbers>
     <ID>int</ID>
     <Numbers>string</Numbers>
     <TEST1s>
       <TEST1 d5p1:nil="true" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-
instance" />
       <TEST1 d5p1:nil="true" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-
instance" />
     </TEST1s>
   </numbers>
 </TEST1>

A:

I would use a 'promise' to clean this up, something like this might work:
function scan() {
    cordova.plugins.barcodeScanner.scan(
        function(result) {
            console.log(result.text)
            var barcode_res = (" ID\n" +
                "Result: " + result.text);
            getFrn(result.text)
                .then(function(frn2){
                    // you can do something with frn2 here
                    window.open("https://example.com/?frn=" + frn2);
                });
            window.alert("ID Result: " + result.text);
        },
        function(error) {
            window.alert("Scanning Failed: " + error);
        });

    //getFRNbyMATRIC webservice call
    function getFrn(str) {
        return new Promise(function(resolve, reject) {
            $.post("http://localhost:8081/WebService.asmx?op=getFRNByMATRIC", {
                MATRIC: str
            }, function(response) {
                frn2 = response;
                resolve(frn2);
            }).error(function(e) {
                window.alert("Sorry could not proceed");
                reject(e);
            });
        })
    }
}


Q:

String Query cannot be executed

Hye,
I'm working on code where I can transfer the data from Excel and record it in the Access database. The code I've currently, I copied it from a site and changed the value and some statement regarding to my worksheet. But the problem is, I can't run my code but the file that I got from the other website able to run successfully. Could you explain what is the problem in my code. Here is the code:
Sub Customer Log()
Dim cn as Object
Dim strQuery as string
Dim custName As String
Dim ordID As String
Dim myDB As String

'Initialize Variables
custName = Sheets("Batch_Report").Range("D4").Value
ordID = Sheets("Batch_Report").Range("D5").Value

'Database Location
myDB = "C:\Users\intern.maxvue\Dekstop\Adhariah (Intern)\Bar Code System\ReviewReport_v1_2015.accdb"
Set cn = CreateObject("ADODB.Connection")

With cn
    .Provider = "Microsoft.ACE.OLEDB.12.0"    'For *.ACCDB Databases
    .ConnectionString = myDB
    .Open
End With

strQuery = "INSERT INTO CustomerLog ([CUSTOMER NAME], [ORDER ID]) " & _
           "VALUES (""" & custName & """, " & ordID & "); "

cn.Execute strQuery
cn.Close
Set cn = Nothing
End Sub

When I debug and the line reached at cn.Execute strQuery, the "run-time error: no value given for one or more required parameters" popped out.
Thanks in advance.

A:

Try:
strQuery = "INSERT INTO CustomerLog ([CUSTOMER NAME], [ORDER ID]) " & _
           "VALUES ('" & custName & "', " & ordID & ")"


Q:

Case insensitive search without using a function in the where clause

Any way to make a case insensitive without using a function in the where clause?
Please specify the database you are talking about when/if you reply.  I am aware that MySQL is already case insensitive by default.  What about Oracle or MSSQL or HANA?
select * from mytable WHERE upper(fieldname) = 'VALUE'

A:

collate SQL_Latin1_General_CP1_CS_AS.
Default Collation is SQL_Latin1_General_CP1_CI_AS which is case insensitive. And if we need to make it case sensitive, then adding COLLATE Latin1_General_CS_AS makes the search case sensitive.
Query
select * from [mytable]
where [fieldname] = 'VALUE' collate SQL_Latin1_General_CP1_CS_AS;

Find a demo here

A:

Since your question is tagged Oracle, I will provide a solution which works in Oracle.
You can set these session parameters for case insensitive searching
SQL> alter session set NLS_COMP=ANSI;
SQL> alter session set NLS_SORT=BINARY_CI;
SQL> select 1 from DUAL where 'abc' = 'ABC';

         1
----------
         1

Read more at  Linguistic Sorting and String Searching
as @mathguy points out,
ALTER SESSION SET NLS_COMP=LINGUISTIC;

is more common than using ANSI

A:

Oracle 12c answer
select * from mytable WHERE fieldname='Value' collate binary_ci

SAP HANA does not seem to have a way other than using upper or lower.
SQL Server and MySQL do not distinguish between upper and lower case letters—they are case-insensitive by default.


Q:

Zend Autoloader not loading Zend classes

I'm using the Zend Framework 2.0 to autoload Zend classes in my application, independent of an MVC framework.
The location of the zend framework, is C:/wamp/library/zendframework/library (contains Zend/Soap etc.)
Below is my code:
require_once 'Zend/Loader/StandardAutoloader.php';

$loader = new Zend\Loader\StandardAutoloader(array(
'Zend' => 'c:/wamp/library/zendframework/library'));

$loader = new Zend\Loader\StandardAutoloader();
$loader->registerNamespace('Zend', 'c:/wamp/library/zendframework/library');
$loader->register();

$auto = new Zend/Soap/Server(null,null);
$auto->setClass('services');
$auto->handle();

I'm trying to load the Zend/Soap/Server, but I keep getting the error:
Fatal error: Class 'Zend' not found in C:\wamp\www\Zend_soap\server.php on line 42

whereby on line 42:
$auto = new Zend/Soap/Server(null,null);

A:

very close, I think;
If your ZF2 installation is on the php include_path you should only need 3 lines of code and 4 if it;s not on the include_path.
require_once 'Zend/Loader/StandardAutoloader.php';

//if ZF2 is on php include_path set autoregister_zf to true else false
$loader = new Zend\Loader\StandardAutoloader(array('autoregister_zf' => true));
//Zend would be a vendor prefix not namespace, however a namespace may work just fine
//$loader->registerNamespace('Zend', 'c:/wamp/library/zendframework/library');
//if ZF2 is not on php include path and needs to be registered as a vendor
//$loader->registerPrefix('Zend', 'c:/wamp/library/zendframework/library');
$loader->register();

autoregister_zf: An boolean value indicating that the class should
  register the “Zend” namespace to the directory above where its own
  classfile is located on the filesystem.

Good Luck! I hope this helped.


Q:

Setting up Python Conda Environment in Heroku

Background
I created a heroku instance in my project directory using the guide here for a conda environment:
conda-buildpack
Error
sterlingbutters$ git push heroku master
Counting objects: 7, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (7/7), done.
Writing objects: 100% (7/7), 2.68 KiB | 2.68 MiB/s, done.
Total 7 (delta 1), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python/Conda app detected
remote: -----> Preparing Python/Miniconda Environment (3.8.3)
remote: /app/tmp/buildpacks/2abac4b7166986c6b1b33fcacccb13fb4e2036a9358f31ed8886bbf37c9987c7fbb8243090f0438ebbf02852a1cbeb1b5cae47f67dc2670115ce6d7bd2468300/bin/steps/conda_compile: line 9: conda: command not found
remote:  !     Push rejected, failed to compile Python/Conda app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to openmc-dash-interface.
remote:
To https://git.heroku.com/openmc-dash-interface.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/openmc-dash-interface.git'

Any ideas on what could be causing the error?
Additional requirements

After I get the python application deployed, I still need to add a conda channel in order to install a specific package. How can I do this?
Some of the package requirements do not have a compatible version on conda, only PyPI (pip), does the use of a conda environment in heroku forfeit the ability to use pip?

UPDATE: I think I figured out the additional requirements, contents of my environment.yml:
name: openmc-dash-interface
channels:
    - conda-forge
dependencies:
- python=3.6
- anaconda
- openmc
- pip
- pip:
  - dash
  - plotly
  - dash-core-components
  - dash-html-components
  - dash-daq
  - numpy
  - pandas
  - gunicorn

But still getting errors at build
Thanks in advance for any/all help

A:

It appears Python3 is not supported with this buildpack: https://github.com/heroku-python/conda-buildpack/issues/14
However, other third-party buildpacks exist that appear to support Python3:
https://elements.heroku.com/buildpacks/trib3/conda-buildpack
https://elements.heroku.com/buildpacks/teamupstart/conda-buildpack
Maybe: https://github.com/pl31/heroku-buildpack-conda


Q:

Well-ordered set and countable set

Question 1: Let $P$ is a well-ordered set of real numbers with the usual order. Is $P$ always countable? I think it is true, but I can't prove it.
Question 2: Let $P$ is a well-ordered set. Is $P$ always countable?
Thanks in advance.

A:

Suppose $A \subseteq \mathbb{R}$ is well-ordered in the order $<$ from $\mathbb{R}$. Then it is at most countable.
Suppose $A$ is well-ordered in $<$.
Then for each $a \in A$, there is some $r_a>0$ such that
$A \cap [a, a+r_a) = \{a\}$ (it's a right-sided limit point).
For, if this were not the case:
$$\forall r>0: \exists a'(r) \in A: a'(r) \neq a \land a'(r) \in [a, a+r)$$
And then take $a_1 = a'(1)$, and having defined $a_n$ set $a_{n+1} = a'(a_n -a)$. This defines a decreasing sequence $a_n$ in $A$, and so $\{a_n : n \in \mathbb{N}\}$ does not have a minimum, contradicting well-orderedness. So the claim holds, and we have the required $r_a$. Note that all intervals $[a, a+r_a)$ are pairwise disjoint by construction, and the set of open intervals
$(a, a+r_a)_{a \in A}$ is a family of pairwise disjoint non-empty open intervals of $\mathbb{R}$ of size $|A|$ and each interval contains a (necessarily different) rational, and $\mathbb{Q}$ is countable.
So $A$ is at most countable.
As to 2): In ZF we can develop countable ordinals and take the union of all of them. This is $\omega_1$ : the first uncountable ordinal, which is well-ordered (as all ordinals). So there are uncountable well-ordered sets.
Using AC (the axiom of choice) we can prove that all sets regardless of size, can have a well-order defined on them.


Q:

Split string and then remove space and number

I have these values that come from a php mysqli query.
Lobby 26, Noord-Brabant 8, Groningen 0, Friesland 12, Gelderland 28, Limburg 28, Zeeland 0, Overijssel 0, Drenthe 0, Noord-Holland 64, Zuid-Holland 0, Utrecht 14, Belgie 0

Let's say that the above is within str
var foo = str.split(,);

foo[3] would then give back Friesland 12 etc.
What i want is to remove the space and number from the split result.
How can i do this with jQuery?

A:

Let's forget about jQuery and use pure JavaScript...
var str = "Lobby 26, Noord-Brabant 8, Groningen 0, Friesland 12, Gelderland 28, Limburg 28, Zeeland 0, Overijssel 0, Drenthe 0, Noord-Holland 64, Zuid-Holland 0, Utrecht 14, Belgie 0";
var foo = str.split(',');

// Removes all spaces and digits
var bar = foo[3].replace(/[ 0-9]/g, '');

// Alternative: remove the first space followed by digits
var bar = foo[3].replace(/ [0-9]*/, '');


Q:

Using HttpClient with SSL - override the Credential Required pop-up

I am using the HttpClient with SSL connection but when I either use Automatic or the Manual Store method of attaching a certificate I get a Windows Security dialog with a prompt asking to confirm "Do you want to allow the app to access your private key?"
Even if I select "Allow", every time my app re-authenticates it asks me Allow the credentials. How do I ensure that the HttpClient makes a request without getting the pop-up shown?

A:

Figured this out myself in the end. Previously the certificate was installed onto the local user account and stored within the users own cert store. Once we installed the cert as local machine and within the trusted section it was fine.


Q:

Automatic comments to redmine after teamcity build

I want to make automatic comment in redmine issue after build in teamcity. For example teamcity made build for branch , I want to make comment in redmine about build result in issue/xyz. What is the best way to do that?

A:

You will need to create a new build step at the end that will run some sort of script or program that you'll need to make.
What the script will do is make use of the TeamCity REST API to get the changes. (See this)
Then you can use the Redmine REST API to update the issue based off the changes found using the TeamCity REST API.


Q:

Cannot use Onsen UI in visual studio Multi-Device Hybrid App (Cordova) Project

I have been trying for a long time but I cannot get OnsenUI to work on visual studio 2013 Multi-Device Hybrid App (Cordova) Project. Below is the link to my project.https://onedrive.live.com/redir?resid=DBAFE70AF18A9BDB%211817.

A:

There is an Onsen UI extension for Visual Studio 2015 here.
If you open that VSIX file as a Zip file you will find some templates prepared for Windows Phone and Visual Studio 2015 with Onsen UI, AngularJS and Cordova. Just adapt the folder structure to VS2013 (i.e. without 'www' folder) and they will work. More info in Onsen UI blog.
Hope it helps!


Q:

KonvaJS: How to serialize object with custom property?

var group = new Konva.Group();
group.customProp = ['a', 'b', 'c'];
group.toJSON();

Result:
{
    attrs: {},
    className: "Group",
    children: []
}

And customProp is lost.
How can I convert the object to JSON without losing the data?

A:

Properties on an instance will be not serialized. You should use public API to set/get properties.
var group = new Konva.Group();
group.setAttr('customProp', [1, 2, 3]);
// use this to read property
// group.getAttr('customProp')
group.toJSON();

Output:
{"attrs":{"customProp":[1,2,3]},"className":"Group","children":[]}


Q:

using temp tables in SQL Azure

I am writing a query to pivoting table elements where column name is generated dynamically.
SET @query = N'SELECT STUDENT_ID, ROLL_NO, TITLE, STUDENT_NAME, EXAM_NAME, '+
            @cols +
            ' INTO ##FINAL
            FROM
            (
                SELECT  *
                FROM #AVERAGES
                UNION
                SELECT  *
                FROM #MARKS
                UNION
                SELECT  *
                FROM #GRACEMARKS
                UNION
                SELECT  *
                FROM #TOTAL
                ) p
                PIVOT
                (
                MAX([MARKS])
                FOR SUBJECT_ID IN
                ( '+
                @cols +' )
            ) AS FINAL
            ORDER BY STUDENT_ID ASC, DISPLAYORDER ASC, EXAM_NAME ASC;'

EXECUTE(@query)

select * from ##FINAL

This query works properly in my local database, but it doesn't work in SQL Azure since global temp tables are not allowed there.
Now if i change ##FINAL to #FINAL in my local database, but it gives me error as

Invalid object name '#FINAL' .

How can I resolve this issue?

A:

Okay, after saying I didn't think it could be done, I might have a way. It's ugly though. Hopefully, you can play with the below sample and adapt it to your query (without having your schema and data, it's too tricky for me to attempt to write it):
declare @cols varchar(max)
set @cols = 'object_id,schema_id,parent_object_id'

--Create a temp table with the known columns
create table #Boris (
    ID int IDENTITY(1,1) not null
)
--Alter the temp table to add the varying columns. Thankfully, they're all ints.
--for unknown types, varchar(max) may be more appropriate, and will hopefully convert
declare @tempcols varchar(max)
set @tempcols = @cols
while LEN(@tempcols) > 0
begin
    declare @col varchar(max)
    set @col = CASE WHEN CHARINDEX(',',@tempcols) > 0 THEN SUBSTRING(@tempcols,1,CHARINDEX(',',@tempcols)-1) ELSE @tempcols END
    set @tempcols = CASE WHEN LEN(@col) = LEN(@tempcols) THEN '' ELSE SUBSTRING(@tempcols,LEN(@col)+2,10000000) END
    declare @sql1 varchar(max)
    set @sql1 = 'alter table #Boris add [' + @col + '] int null'
    exec (@sql1)
end

declare @sql varchar(max)
set @sql = 'insert into #Boris (' + @cols + ') select ' + @cols + ' from sys.objects'
exec (@sql)

select * from #Boris

drop table #Boris

They key is to create the temp table in the outer scope, and then inner scopes (code running within EXEC statements) have access to the same temp table. The above worked on SQL Server 2008, but I don't have an Azure instance to play with, so not tested there.


Q:

If there were two equal masses with one mass in the middle which way would gravity pull it?

If there were two masses with a third exactly in the middle of those two, which way would the middle mass be pulled?

A:

Asking which way the middle mass will be pulled is essentially like asking whether zero is less than zero or greater than zero. If the masses on the sides are equal, they pull equally hard in opposite directions, and so the net force on the middle mass is zero.
By Newton's 1st law, if the middle mass is initially at rest then it will remain at rest for all times. Now, there is admittedly a loophole here. If the middle mass's initial velocity has a nonzero component in the direction of the line determined by the outer masses, then in the next instant the middle mass will be closer to one of the outer masses, resulting in a greater force in the direction of that mass.


Q:

In what order should I watch The planet of the Apes franchise?

Basically, I ended somewhere on the reboot film made in 2001. I would like to get back to Planet of Apes series and watch it again.
With Star Wars franchise, there is famous order of how should one watch the series. Is there something similar with The Planet of Apes series?

A:

Star Wars is a single franchise, but Planet of the Apes doesn't work like that. First, there is :
Original film series

Planet of the Apes (1968)
Beneath the Planet of the Apes (1970)
Escape from the Planet of the Apes (1971)
Conquest of the Planet of the Apes (1972)
Battle for the Planet of the Apes(1973)

They should be followed in release order.
Then comes the Television series

Planet of the Apes (1974)
Return to the Planet of the Apes Animated series (1975)

Both TV series are based on the same work as the original movie series but they are stand-alone series (even unrelated to each other) and can be watched separately in any order.
Then comes reboot

Planet of the Apes (2001 film)

2001's reboot was expected to kick-start a new franchise but it never succeeds.
New reboot

Rise of the Planet of the Apes (2011)
Dawn of the Planet of the Apes (2014)
War for the Planet of the Apes (2017)

All works are based on the same novel but their direction is a bit different and they do play with the story and go a different way.
So you can either pick all or pick any one franchise. 2001's Burton's version is not part of recent reboot and if you are only interested in the new iteration, then start with Rise of the Planet of the Apes and skip previous works. Else you can watch the original film series. Both TV series are individual and can be watched separately if you want.
I will recommend picking only from the original movie series or the latest reboot or both.

A:

As far as I'm aware, there are two suggested watching orders:
1. Release order of films:
This involves watching the films in the order they were (or will be) released:

2. In-universe chronological order of films:
This involves watching the films in the in-universe timeline order presented in each of the films (which is a little complicated due to the alternative timelines and reboots involved). This looks like so (thanks to Gizmodo for this image):


Q:

Where can I find Drivers for Sharper Image Digital Camera Binoculars 10x25?

I have some Digital Camera Binoculars from Sharper Image, but do not have the driver CD that came with them. I searched online and can not find the a place to download the device drivers for them. It doesn't say anything about the manufacturer on them so I can't even search the manufacturers website.
http://www.sharperimage.com/si/view/product/Digital+Camera+Binoculars+10+x+25/100311
Does anyone know where I can download device drivers for these?
Update: I previously thought that they might be similar to the Vivitar brand binoculars (which they still may be), but have since found that the manufacturers website is http://mscustomercare.com

A:

I contacted The Sharper Image via the "live chat" on their website and they pointed me to the following website where the drivers can be downloaded from:
http://www.mscustomercare.com
You just click on the picture of the binoculars to view the download links. Also, just for simplicity sake, here's a direct link to the driver/software download for Windows:
http://www.mscustomercare.com/forms/10x25%20Software.zip


Q:

What is the difference between CMOS and Pass-Transistor Logic?

My friend and I are taking our first digital systems designs course this semester. Our professor has introduced to us two different type of circuit designs; CMOS and Pass-Transistor Logic. The professor isn't very accessible, and we've searched the internet trying to understand the difference between CMOS and Pass-transistor logic, but a lot of the explanations were beyond us. We would really appreciate if someone would explain to us in layman's terms what the difference between the two is, the advantages of each, etc.
Thank you!

A:

I really hate it when these "professors" confuse their students by mentioning terms like "Pass transistor logic" without first properly explaining what CMOS logic is.
I have been working with CMOS circuits and CMOS logic circuits since the 1980s when I was a teenager. Yet I had never heard of "Pass transistor logic" before. That gives you an indication how relevant the term "Pass transistor logic" is.
OK, so to educate myself I read the Wikipedia article on Pass transistor logic. Hmm, so it uses the same type of logic gates (same circuits) as standard CMOS logic but the connections between parts of the circuit is made/broken depending on what the circuit should do. This is of limited use but can be convenient for cells that need to memorize a certain value (zero or one).
But before you can understand Pass transistor logic you must first understand "normal" CMOS logic, so go read the Wikipedia article. Only when that 100% is clear to you should you read about Pass transistor logic.
CMOS logic is what is used in nearly all electronics these days. It will be a challenge to find a modern device with a battery, power lead or solar cell that does not contain CMOS logic circuits.
CMOS logic can be used to create a circuit that can memorize a value. In logic a value is either one or zero (a bit). A CMOS flip-flop can memorize a bit.
In order to save a couple of transistors we can arrange them in such a way that we would need less transistors (to make that flip-flop) yet still be able to memorize that bit. That is what Pass transistor logic is about.
But since modern CMOS transistors can be made so extremely small and cheap it isn't really needed to save those few transistors. Only there where a large number of bits needs to be stored would it make sense to use Pass transistor logic. I would not expect the find Pass transistor logic anywhere else but in memory cells.
So it might have helped if your professor had mentioned that using CMOS transistors we can make "Pass transistor logic cells" and that those are mainly used for memory applications.


Q:

Make number of optional parameters the same in a typesafe way

Is there a way to make the number of optional arguments the same in Typescript?
In the example code a function has two (optional) arguments and the same arguments to the method. Is there a way to make the number of optional arguments the same in a typesafe way?
function withGood<A, T1, T2>(
  fn: (
    v1?: T1,
    v2?: T2,
  ) => A,
  v1?: T1,
  v2?: T2,
): A {

    return
      fn(
        value(v1),
        value(v2),
      );
}

A:

You can type function's parameters in the following way: first parameter is a function and rest parameter is restricted to parameters of the passed function:
function foo<F extends (...args: any[]) => any>(fn: F, ...args: Parameters<F>): ReturnType<F> {
    return fn(...args);
}

function bar(a: number, b?: string) { }

// valid usages

foo(bar, 1, '1');

foo(bar, 1); // optional parameter remains optional

// expect error

foo(bar); // missing required parameter

foo(bar, 1, '1', 'additional parameter'); // not expected extra parameter

foo(bar, 1, true); // wrong type of parameter

Playground


Q:

Vue.js, parent not responding to child event

I've got an issue where a parent component isn't responding to a child's event. Using the Vue Developer Tools, I can see that the events_loading event is being emitted by the <Calendar> component, but the parent just isn't responding.
The parent HTML is...

    <app-header></app-header>

            <date-picker></date-picker>

            <calendar></calendar>

And the JS is...
export default {
    name: 'app',
    methods: {
        test: function() {
            alert('sdfds');
        }
    },
    data: function() {
        return {
            is_loading: false
        }
    },
    components: {
        'app-header': AppHeader,
        'date-picker': DatePicker,
        'calendar': Calendar
    }
}

A:

You want to listen the event from the calendar, so you should write the v-on on the calendar component:
<calendar v-on:events_loaded="test"></calendar>

not on your parent component's container.


Q:

ngOnInit and Constructor are called twice

For some reason I'm getting the function being called twice and I can't seem to figure out why.
I see this question here
why ngOnInit called twice?
Which references this github issue
https://github.com/angular/angular/issues/6782
But that would seem to suggest I'm importing the file in multiple places which I don't believe is the case.
As far as I know I'm taking advantage of Ionic 3's lazy loading.
Here is a link to a stripped down github repo you can run locally to see the issue (I'm sorry I can't figure out the best way to get this to run in plunker or codepen)
https://github.com/Jordan4jc/ionic-init-example
The concept has the main app first load a token out of the store, then verify it and if it's still valid route to the EventsPage but if it's not it would route to a LoginPage
In this example I fake it and just pretend the token is valid and route to the EventsPage, as you'll see in the ngOnInit function (and event if I move it into the Constructortheconsole.log` gets called twice. This will be hitting my server to get the latest data so I really don't want to hit my API twice.
EDIT: This is the content in the app.component.ts
import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import {Storage} from '@ionic/storage';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any;
  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, storage: Storage) {
    platform.ready().then(() => {
      storage.ready().then(()=>{
        // pretend we loaded a JWT and verified it
        this.rootPage = 'EventsPage';
      });
      splashScreen.hide();
    });
  }
}

A:

I believe I have found the answer.
I found this question on stack overflow
why ngOnInit called twice?
One answer referenced a template compilation error, and scrolling through the remaining answers one also references the fact that if a button is present in your template without an explicit type="button" it may be treated as a submit button by your browser and therefore cause the app to execute the code multiple times. Adding this attribute to the buttons I found in my app that did not have it appears to have solved the issue.


Q:

Why no element gets inserted in my BST

Here i am trying to implement a binary search tree.I declared root node in global context.I followed the same idea how i implemented linked list.But this approach doesn't seem like working.I can't figure what is wrong in this code.Can anyone help me figure this out
#include<stdio.h>
struct node {

    int data;
    struct node *left;
    struct node *right;
};
void insert(int value);
void push(struct node *temp,struct node *newNode);

struct node *root;
int main(){
    root= NULL;
    int option,value;
    for(;;){
       printf("Please select an option from below : \n");
       printf("1 for insert\n");
       printf("2 for search\n");
       printf("please enter your option : ");
       scanf("%d",&option);
       printf("\n");
       switch(option){
           case 1:
               printf("you choose to insert\n");
               printf("input your value :");
               scanf("%d",&value);
               insert(value);
               printf("\n");
               break;
           case 2:
               printf("You choose to search\n");
               printf("enter your value : ");
               scanf("%d",&value);
               search(root,value);
               printf("\n");
           default:
               break;

       }
    }
}

void insert(int value){
    struct node *newNode = (struct node *)malloc(sizeof(struct node));

    newNode->data = value;
    newNode->left = NULL;
    newNode->right = NULL;

    push(root,newNode);

}
void push(struct node *root_node,struct node *newNode){

  if(root_node==NULL){
         root_node = newNode;
         printf("inserted\n\n\n");
    }else{
         if(root_node->data > newNode->data){
              push(root_node->left,newNode);
              printf("left\n");
         }else{
            push(root_node->right,newNode);
            printf("right\n");
         }

    }

}

A:

In push(), root_node is a local variable:
void push(struct node *root_node,struct node *newNode){

When you do:
root_node = newNode;

you are only updating the local variable "root_node", not the global:
struct node *root;

Your push() should be something like:
void push(struct node **root_node,struct node *newNode){
    if(*root_node==NULL){
        *root_node = newNode;
        printf("inserted\n\n\n");
    }else{
...

and call:
push(&root, newNode);

In this way, you pass the address of root, and inside you check if the pointed by that address is NULL. If it is null, you assign the address of newNode into the pointer dereferenced.
More explanations:
struct node *root is a pointer: a variable who's type is "pointer/address". And points to a block in memory of data, let's call "A".
struct node *root_node is a pointer, as local variable, it is a COPY, that points to a block in memory of data, and in your case (since you pass "root") points to "A".
When you modify root_node, your copy does not modify root. What you are doing can only be used to modify "A".
You have to pass the address of root, so you can actually modify root's value, which is a pointer to "A". In that way, you have **root_node which is a pointer to root, ACTUAL root, which points to "A", and you can make it point to other place (as you want).
I upload an image to show why your solution is wrong:

As you can see, root is never updated.
(P.S.: You can read "copy the pointer" as "copy the variable", since a pointer is a variable who's value is an address. And you dereference the address with *variable).


Q:

Updating a paid domain or subdomain to a dynamic ip

i was wondering if there was a service that is totaly free that can update the subdomain registered IP adress in the registry automaticly ?
Like if i had a update script on the server that checks in each day or something like that ?

A:

I do a workaround. I use a dydns or noip account linked to me router and on my dns hoster (like godaddy) I forward the traffic to that subdomain.
dyndns or noip offer a windows too in case your router does not suport it.


Q:

How to search by taxonomy terms

I created a taxonomy called tags.  I added terms to the vocabulary list.
Then I created a content type called News Item.   You can apply tags to News Items.
I created a view to list News Items.
How do I set up a search box that let's people search News Items by tags?  they should be able to search by multiple tags.  So if the search words are "tutorial learning-resource", then show all news items that have both the tags tutorial and learning-resource.
How do I do this?

A:

If I understand well, I think that you can do this with Views, so you can expose a filter related with Taxonomy: Term ID related with your Vocabulary. Remember that you can use the operator 'Contains' if you want to be more laxed in the search.


Q:

Flask app dont start on heroku server

I'm trying to deploy a Flask app with Heroku. It's simple API. Works great local with foreman but I get error (log is below) when starts on heroku.
This is my app code (I know it's but looking in one block, but I have problems to split it to files):
import flask
import flask.ext.sqlalchemy
import flask.ext.restless

app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:password@server/db'
db = flask.ext.sqlalchemy.SQLAlchemy(app)

from sqlalchemy import Column, Integer, String, ForeignKey,\
    Date, DateTime, Boolean, Float

class fruits(db.Model):
    __tablename__ = 'fruits'
    id = Column(Integer, primary_key=True)
    name = Column(String(50),nullable=False)
    calories = Column(Integer, nullable=False)
    amount = Column(Integer, nullable=False)
    unit = Column(String(10),nullable=False)
    url = Column(String(100),nullable=True)

@app.route('/')
def hello_world():
    return 'Hello World!'

# Create the database tables.
db.create_all()

# Create the Flask-Restless API manager.
manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)

# Create API endpoints, which will be available at /api/<tablename> by
# default. Allowed HTTP methods can be specified as well.
manager.create_api(fruits, methods=['GET', 'POST', 'DELETE'])
manager.create_api(tmp, methods=['GET', 'POST', 'DELETE'])

# start the flask loop

if __name__ == '__main__':
        import os
        port = int(os.environ.get('PORT', 33507))
        app.run(host='0.0.0.0', port=port)

This is heroku log:
at=error code=H14 desc="No web processes running" method=GET path=/ host=blooming-taiga-1210.herokuapp.com fwd="188.33.19.82" dyno= connect= service= status=503 bytes=

and my Procfile:
web: python __init__.py

A:

Is there actually a running dyno called web? It looks like you might have forgotten to scale your web dyno:
Add an entry like this in your Procfile:
heroku ps:scale web=1

You can use
heroku ps

to confirm that your web dyno is running.


Q:

Significant difference between 28C and 32C tires?

I have a Schwinn Sporterra 2011. It has a 622x20 rim and the default tires are 700x38C. I'm thinking of "upgrading" to thinner tires.
Now, my local cycle shop has Specialized tires that are 32C. They can also get me Schwalbe 28C tires, but in 2-3 weeks time. What I'm trying to understand is, coming from 38C tires, how much of a difference will 28C or 32C make -- Difference to things like speed and handling? Will 28C be much "faster" and worth the long wait time?
(I'm actually thinking of switching to a road bike in 6 months but till the time I save up for that, I want to get thinner tires on the current bike. I was told they'll make quite a difference. Thoughts?)

A:

They will make a significant difference, but the size of the tire alone won't make much of a difference to your speed. If your current tires have a substantial amount of tread on them, you may notice a speed difference since smaller tires tend to have less tread on average.  It's probably not going to be a substantial difference though, even if you have the knobbiest 38's on the market. Your biggest speed limitation is wind resistance, and while the narrower profile of the tires will knock that down a little, it's a small portion of the overall wind resistance that you experience.
Where you'll notice the biggest difference will be in how much harsher the ride will feel with skinnier tires. They run at higher pressures so you end up feeling every bump in the road more.
You'll also notice that the steering feels more nimble due to the lighter weight of the skinnier tires.
You'll also be more prone to pinch flats with skinnier tires. To what extent will depend on the tire pressure that you've been running and the tire pressure you're going to run.

A:

I have tested everything from 35 to 32, 28, 24 and finally to 23 from different brands. The overall experience depends on several factors, most notably the kind of riding you do, your weight, frame design and material etc. For the same tire type (ie a decent road tire) a 32 tire will give good comfort for a heavy rider and is excellent for everyday use. I chose 28 (Continental 4 seasons) for my city/commute bike and I am quite happy but the ride is definitely harder, especially with my aluminium frame. Tires below 28 are only for road bike use, ideally with a carbon frame.
In conclusion, if you are heavy or ride bad roads, get the 32. If you are skinny or ride good quality tarmac, you can consider 28. Invest in good quality, things like tpi (threads per inch) are very important. Make sure you use the correct pressure.

A:

Another answer noted that tread pattern and tire pressure make a larger difference than the width.  If you have a smooth tread pattern at high pressure, you will roll more easily and the tire won't "squirm" going around corners.  Tire compound can also affect handling.  The worst tires I ever rode on were a cheap narrow-ish (maybe 28c) set with raised tread made of a harder rubber compound.  The traction was terrible: I could lock the rear tire even under fairly light breaking.
There is a connection between width and tire pressure.  Generally narrower tires support higher pressures, and also require higher pressures to support the same weight on a smaller volume of air.  Up to a point, running higher pressure will reduce rolling resistance.  If you run the pressure too high it may actually slow you down as small bumps will jostle you more.  You can try running wider tires at their max pressure to reduce rolling resistance and see how they feel, but it will likely give you a rough ride and have fairly poor contact with the road surface, compared with a narrower tire at the same pressure.
The 32C tires will likely give a noticeable difference: the ride may be a little rougher but rolling resistance should be reduced, and you'll probably feel a little more certain on corners.  Contrary to the other poster, rolling resistance is less than air resistance, but is a significant factor at moderate speed: if you're riding at 25MPH, air resistance totally dominates, but at 15MPH, rolling resistance is non-negligible.
I would say just get the 32C tires and start riding on them: it's probably not worth the wait.  There's also a good chance that 28C might be too much of a good thing.


Q:

What is a Shim?

What's the definition of a Shim?

A:

From Wikipedia:

In computer programming, a shim is a small library that transparently intercepts an API, changing the parameters passed, handling the operation itself, or redirecting the operation elsewhere. Shims typically come about when the behaviour of an API changes, thereby causing compatibility issues for older applications that still rely on the older functionality. In these cases, the older API can still be supported by a thin compatibility layer on top of the newer code. Shims can also be used to run programs on different software platforms than they were developed for.

A:

The term "shim" as defined in Wikipedia would technically be classified, based on its definition, as a "Structural" design pattern.  The many types of “Structural” design patterns are quite clearly described in the (some would say defacto) object oriented software design patterns reference "Design Patterns, Elements of Reusable Object-Oriented Software" better known as the "Gang of Four".
The "Gang of Four" text outlines at least 3 well established patterns known as, "Proxy", "Adapter" and "Facade" which all provide “shim” type functionality.  In most fields it’s often times the use and or miss use of different acronyms for the same root concept that causes people confusion.  Using the word “shim” to describe the more specific “Structural” design patterns "Proxy", "Adapter" and "Facade" certainly is a clear example of this type of situation.  A "shim" is simply a more general term for the more specific types of "Structural" patterns "Proxy", "Adapter", "Facade" and possibly others.

A:

Simple Explanation via Cartoon
An example of a shim:

Summary
A shim is some code that takes care of what's asked (by 'interception'), without anyone being any wiser about it. This is the general concept. Now you should be able to read and understand the wikipedia entry on shims.
Note: Like most analogies, this is not perfect: usually Ralph will get EXACTLY what he asked for - but the mechanics of HOW it was obtained is something that he might not expect.


Q:

How to dynamically set headers in Retrofit (Android)

I am using an API that uses an authorization scheme that requires a special "X-Authorization" header to be set to authenticate the request. For example, this Retrofit setup works perfectly for the user whose auth token is abc123:
@Headers("X-Authorization: abc123")
@GET("/posts")
Observable<List<Post>> get_posts();

I cache the user's X-Authorization token, so I have access to that, however, I can't just drop it in the @Headers declaration.
@Headers("X-Authorization: " + token)
@GET("/posts")
Observable<List<Post>> get_posts();

I get a compile error here: Error:(41, 34) error: element value must be a constant expression
Any ideas on how I could get around this?

A:

Since Retrofit 2.0 you have two options

1) Using OkHttp 2.2+ use Interceptor
At the Http level, you have more control over the request, so you could do things like applying headers only to a specific request made to a specific endpoint, and so on.
public class MyOkHttpInterceptor implements Interceptor {

@Override
public Response intercept(Chain chain) throws IOException {
    Request originalRequest = chain.request();
    if (!"/posts".contains(originalRequest.url()) ) {
        return chain.proceed(originalRequest);
    }

    String token = // get token logic

    Request newRequest = originalRequest.newBuilder()
        .header("X-Authorization", token)
        .build();

    return chain.proceed(newRequest);
}

[...]

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.networkInterceptors().add(new MyOkHttpInterceptor());
OkClient okClient = new OkClient(okHttpClient);
YourApi api = new RestAdapter.Builder()
            .setEndpoint(url)
            .setClient(okClient)
            .build()
            .create(YourApi.class);

Edit:
Adding @JakeWarthon comment as another option as is also valid.
2) Put @Header on a method parameter and pass it as a value when invoking.
From the docs:
// Replaces the header with the the value of its target.
@GET("/")
void foo(@Header("Accept-Language") String lang, Callback<Response> cb);

Header parameters may be null which will omit them from the request. Passing a List or array will result in a header for each non-null item.
Note: Headers do not overwrite each other. All headers with the same name will be included in the request.

EDIT: This option should not be considered as Retrofit 2.* dropped support for interceptors.
3) User retrofit RequestInterceptor
From the docs:
Intercept every request before it is executed in order to add additional data.
You could do something like
public class MyRetrofitInterceptor implements RequestInterceptor {

@Override
public void intercept(RequestFacade req) {
    String token = // get token logic
    if (token != null) {
        req.addHeader("X-Authorization", token);
    }
}

[...]

YourApi api = new RestAdapter.Builder()
            .setEndpoint(url)
            .setRequestInterceptor(new MyRetrofitInterceptor())
            .build()
            .create(YourApi.class);

The "problem" with this approach is that the interceptor will get executed on all the endpoints, as it's set at the RestAdapter level, and not per endpoint. Also, the RequestFacade doesn't expose much information about the request, so no chance to add much logic around it.

A:

Passing header in parameter would be helpful. Look to the following code;
 @GET("/posts")
Observable<JsonElement> getDataFromService(
        @HeaderMap Map<String, String> headers,
        @QueryMap HashMap<String, Object> queryParams
);

        hashMap1.put("Authorization", token);
    return ApiService.getAPI_test().getDataFromService(hashMap1, url, hashMap)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io());

Update:
More better would be
 @GET("/posts")
Observable<JsonElement> getDataFromService(
        @Header("Authorization") token: String = "Bearer " + PreferenceUtils.getToken(),
        @QueryMap HashMap<String, Object> queryParams
);

A:

Dynamic Header In Retrofit 2
I have struggled too much to add Dynamic Header In Retrofit 2.
I have gone through so many blogs and StackOver flow. Everyone has shown example with Interceptor.
And it’s not a wise thing ,just for one API call we need to do that much work.
You just have to add @HeaderMap as argument of fun. I have done in very simple way :-
In Kotlin
    val headers = HashMap<String, String>()
    headers["KEY_AUTHORIZATION"] = "paste AUTHORIZATION value here"
    headers["KEY_TOKEN"] = "paste TOKEN value here"

    val jsonObject= JsonObject()

I am passing here header and other data also
Calling of fun:-

postEvent(headers,jsonObject)

API Declaration

    @POST("/v1/post_data")
    fun postEvent(@HeaderMap headers: Map<String, String>, @Body jsonObject: JsonObject): Call<JsonObject>

API Declaration with RxAndroid

    @POST("/v1/post_data")
    fun postEvent(@HeaderMap headers: Map<String, String>, @Body jsonObject: JsonObject): Single<JsonObject>

2nd argument here i have JsonObject. You can replace with anything whatever you need to pass or you can remove it also.
In Java
 HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("KEY_AUTHORIZATION","paste AUTHORIZATION value here");
    headers.put("KEY_TOKEN", "paste TOKEN value here");

    JsonObject jsonObject= new JsonObject();

I am passing here header and other data also

Calling of fun:-
postEvent(headers,jsonObject);

    API Declaration
    @POST("/v1/post_data")
    Call<JsonObject> postEvent(@HeaderMap Map<String, String> headers, @Body JsonObject jsonObject);

API Declaration with RxAndroid

    @POST("/v1/post_data")
    Single<JsonObject> postEvent(@HeaderMap Map<String, String> headers, @Body JsonObject jsonObject);

2nd argument here i have JsonObject. You can replace with anything whatever you need to pass or you can remove it also.


Q:

nightwatch js while loop

I'm new to node and nightwatch. Been working with Selenium for a number of years but my company has moved over to all things node. Anyway, in nightwatch I am trying to click a link while its visible and loop and keep clicking it until it is not. Here is what my code looks like. Any suggestions would be much appreciated!
"Cart Cleanup": function (browser) {
    browser
        .url(environment + '/ShoppingBag')
        .waitForElementVisible('div.cart-top-message', 190000)
        .pause(3000)
        .element('class name', 'delete-form', function (visible) {
            while (visible.status !== -1) {
                console.log(visible.status);
                browser
                    .useXpath() //NOW USING XPATH
                    .click('/html/body/div[5]/div[2]/div/div[2]/div[1]/div/div[3]/div[4]/div[2]/form[2]/input')
                    .useCss()
                    .pause(3000)
                    .element('class name', 'delete-form', function (visible2) {
                        visible = visible2
                    })
            }
        })
}

A:

The best way to solve this problem is to create a custom command.
Nightwatch custom command documentation: http://nightwatchjs.org/guide#writing-custom-commands
In order to make it easier to solve problems such as these, I created a "waitUntil" custom command, which serves as a base for other custom commands:
// WaitUntil.js, in custom commands folder specified in nightwatch.json
var util = require('util');
var events = require('events');
var TIMEOUT_RETRY_INTERVAL = 100;

function waitUntil() {
    events.EventEmitter.call(this);
    this.startTimeInMilliseconds = null;
}

util.inherits(waitUntil, events.EventEmitter);

/**
 * The purpose of this command is to serve as a base for waitUntil_ commands. It will run the getActual function until
 * the predicate funciton returns true or the timeout is reached. At that point, the assertion funciton will be called.
 * @param getActual {Function} - should passe the found value to its callback. The callback will be passed as the only
 *      argument.
 * @param predicate {Function} - the wait will end when this returns true. The actual value is passed as the only
 *      argument.
 * @param assertion {Function} - the assertion to make. The assertion should pass when the predicate returns true. This
 *      function will be passed the actual value and the message.
 * @param timeoutInMilliseconds {number} - the number of milliseconds to wait before timing out and failing.
 * @param message {string} - the message to attach to the assertion. The elapsed time will be appended to this.
 * @returns custom command waitUntil, which can be accessed as browser.waitUntil(args);
 */
waitUntil.prototype.command = function (getActual, predicate, assertion, timeoutInMilliseconds, message) {
    message = message || 'waitUntil';
    this.startTimeInMilliseconds = new Date().getTime();
    var self = this;

    this.check(getActual, predicate, function (actual, loadedTimeInMilliseconds) {
        if (predicate(actual)) {
            message += ': true after '
                + (loadedTimeInMilliseconds - self.startTimeInMilliseconds) + ' ms.';
        } else {
            message += ': timed out after ' + timeoutInMilliseconds + ' ms.';
        }
        assertion(actual, message);
        self.emit('complete');
    }, timeoutInMilliseconds);

    return this;
};

waitUntil.prototype.check = function (getActual, predicate, callback, maxTimeInMilliseconds) {
    var self = this;
    getActual(function (result) {
        // If the argument passed to the callback is an object, it is assumed that the format is of the argument passed
        // to callbacks by the Nightwatch API, in which the object has a "value" attribute with the actual information.
        var resultValue;
        if (typeof result !== 'object') {
            resultValue = result;
        } else if (result.hasOwnProperty('value')) {
            resultValue = result.value;
        } else {
            self.error('Result object does not have a value.');
            return;
        }

        var now = new Date().getTime();
        if (predicate(resultValue)) {
            callback(resultValue, now);
        } else if (now - self.startTimeInMilliseconds < maxTimeInMilliseconds) {
            setTimeout(function () {
                self.check(getActual, predicate, callback, maxTimeInMilliseconds);
            }, TIMEOUT_RETRY_INTERVAL);
        } else {
            callback(resultValue, null);
        }
    });
};

module.exports = waitUntil;

Using this module, it is simple to create commands like waitUntilTrue, waitUntilEqual, etc. You can also create a "clickUntilNotVisible" command to solve your problem (Obviously, this could be combined with the above and simplified if this is your only use case):
// clickUntilNotVisible.js, in custom commands folder specified in nightwatch.json
exports.command = function (clickElementFunction, getVisibilityFunction, assertion, timeout, message) {
    var browser = this;

    function clickAndGetVisiblity (callback) {
        clickElementFunction();
        getVisibilityFunction(callback);
    }

    function isTrue (actual) {
        return !!actual;
    }

    return browser.waitUntil(clickAndGetVisiblity, isTrue, assertion, timeout, message);
};

Now that we have this clickUntilNotVisible command defined, we can tackle your problem:
function clickMyLink() {
    browser
        .useXpath() //NOW USING XPATH
        .click('/html/body/div[5]/div[2]/div/div[2]/div[1]/div/div[3]/div[4]/div[2]/form[2]/input')
        .useCss();
}

function isDeleteFormVisible(callback) {
    browser
        .pause(3000)
        .elements('class name', 'delete-form', function (result) {
            callback(result.status === 0 && result.value.length);
        });
}

function verifyDeleteFormIsNotVisible (actual, message) {
    browser.verify.ok(!actual, message);
}

module.exports = {
    "Cart Cleanup": function (browser) {
        browser
            .url(environment + '/ShoppingBag')
            .waitForElementVisible('div.cart-top-message', 190000)
            .pause(3000)
            .clickUntilNotVisible(clickMyLink, isDeleteFormVisible, verifyDeleteFormIsNotVisible, 190000);
    }
};

Note that this uses what I've done and might not be the most efficient way for you to solve this problem, but hopefully it will give you some idea of how to solve it yourself. Also, all this code, other than the waitUntil module, is untested, so it probably won't work without a bit of debugging.


Q:

Why is the point $x=0$ not a periodic point of $f(x)=1/x$ of period $2$?

In a question I am trying to solve, I am asked to prove that $x=0,1$ and $-1$ are not points of period $2$ for $f(x)=1/x$. I get why $x=1,-1$ aren't points of period $2$ but why is $x=0$ not a periodic point because
$$
f(f(x))=x
$$
and so $f^{[2]}(0)=0$. Why is this wrong?

A:

What is $f(0)$? The way you have defined $f(x)$, $0$ is not in the domain, so it doesn't make sense to talk about periodicity of the point.


Q:

List add function isn't performing correctly

My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BattleCore : MonoBehaviour {

public List<GameObject> Enemy = new List<GameObject> ();
public List<EnemyFollow1> EnemyScript =  new List<EnemyFollow1>();
public List<StatData> stat = new List<StatData> ();
public int length;
public bool canMelee = false;
public List<ParticleSystem> ps = new List<ParticleSystem> ();
public float AttackCooldownT = 0;
public float AttackCooldownTI = 3;

void OnTriggerEnter(Collider other)
{
    Debug.Log("ENTERED!");
    if (other.CompareTag("Enemy"))
    {
        canMelee = true;
        Enemy.Add (other.gameObject);
        for (int i = 0; i < Enemy.Count; i++)
        {
            ps.Add(Enemy[i].GetComponent<ParticleSystem>());
            EnemyScript.Add(Enemy[i].GetComponent<EnemyFollow1>());
            stat.Add(EnemyScript[i].enemyData);
        }
    }
}

void OnTriggerExit(Collider other) {
    if (other.CompareTag("Enemy"))
    {
        canMelee = false;
        for (int i = 0; i < length; i++)
        {
            if (Enemy[i] == other.gameObject)
            {
                Enemy.RemoveAt(i);
                stat.RemoveAt(i);
                EnemyScript.RemoveAt(i);
                ps.RemoveAt (i);
            }
        }
    }
}

void Update()
{
    if (canMelee && Input.GetKeyDown(KeyCode.Q) && Time.time > AttackCooldownT && Enemy.Count > 0)
    {
        for (int i = 0; i < Enemy.Count; i++)
        {
            stat[i].HP -= 20;
            ps [i].Play ();
        }
        AttackCooldownT = Time.time + AttackCooldownTI;
    }
}
}

I created list of some objects(enemys) with some data list which I made with unity's scriptable objects. This script adds and removes enemys and
this script works fine but when there are 2 enemy many enemy's(same game object starts adding multiple times) and when it comes to removing all data doesn't gets removed so even if I killed an enemy, he's still in the scene.
My ItemData:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu]
public class StatData : ScriptableObject {

    public string Name;
    public bool Boss;
    public int HP, MaxHP, Atk, MaxAtk, SpAtk, MaxSpAtk, Def, MaxDef, SpDef, MaxSpDef;
    public Sprite sprite;
}

Also when I try to kill an enemy with same stat data both enemies die together while I only attack one. As the health is global both die. I can't figure out how to fix it.
In my enemy follow I wrote:
enemyStat.HP = enemyStat.MaxHP;

To have enemy alive in a new game.
Please help!

A:

This is an example of the parallel collections anti-pattern:
Enemy.RemoveAt(i);
stat.RemoveAt(i);
EnemyScript.RemoveAt(i);
ps.RemoveAt (i);

You should refrain from doing this, as it creates dependencies in your arrays that is not enforced by anything. For example, if you try to sort one of the arrays, you'll break the relationship between the indices.
You should create a "wrapper" object that binds these different objects together, then have a single list.
class EnemyCollator {
    public GameObject go;
    public EnemyFollow1 script;
    public StatData stats;
    public ParticleSystem particles;
}
...
public List<EnemyCollator> allEnemies;

If you want your data to have a look-up relationship (i.e. "find me the data associated with this GameObject"), use a dictionary:
public Dictionary<GameObject,EnemyCollator> dataLookup;

Or use a Linq query:
GameObject go = allEnemies.Find(x => x.go == someGameObject);

Once you start organizing your code this way, it is likely that the problem you have will go away.


Q:

Obtaining the certificate chain

I am working with X509 certificates in Java. Given a certificate is it possible to find all other certificates in the signing hierarchy until you reach the root certificate?
I have a certificate file (with a .cer extension) and I want to extract the parent signing certificate. I want to keep finding the parent of that certificate untill I get the final root certificate, which is self signed.
I have checked the X509Certificate certificate APIs and relevant APIs in java.security.cert but could not find anything useful.

A:

That is not hard - assuming you've somehow/out of band got all the intermediate certificates and the root cert in one or more keychains.
Have a look at
http://codeautomate.org/blog/2012/02/certificate-validation-using-java/

for a code snipped which does just that. The key bit is in validateKeyChain() and basically consists of
   cert = cert-to-validate
   while(not self signed) {
       extract issuer from cert
       scan keychain(s) to find cert with a subject equal to the issuer
       if none found - error
       check if the signature is correct.
       cert = issuers_cert
   }
   if not at the top/root - error

As to how you get the intermediate/root certificates - that is a different issue. Note that this code is a little bit naive - and does not quite understand cross-signing. The java pkix calls though though - BouncyCastle has an example.
You can generally build the root certs into a key chain; but the intermediate certificates often need to be 'gathered' or discovered more dynamically. This generally requires querying the SSL stack during TLS or similar.


Q:

How to call method of controller in .module file with dependency injection

I have class named Book.
class Popups
{
  private $entityQuery;
  private $entityTypeManager;

  public function __construct(QueryFactory $entityQuery, EntityTypeManagerInterface $entity_type_manager) {
    $this->entityQuery = $entityQuery;
    $this->entityTypeManager = $entity_type_manager;
  }

public function read($cid)
  {
    $nodes = $this->entityTypeManager->getStorage('node')->loadByProperties(['type' => 'book', 'cid' => $cid ]);

    return $nodes;
  }

}

Now I have books.module file where I need to call read method;
how to call that method
$book = new Book();  // what param should i pass here
$book->read($cid)

A:

Add the class to mymodule.services.yml and inject the core services there:
mymodule.services.yml
services:
  mymodule.book:
    class: Drupal\mymodule\Book
    arguments: ['@entity.query', '@entity_type.manager']

Then use the service in procedural code:
\Drupal::service('mymodule.book')->read($cid)


Q:

Access to class inside Union

I have the declaration of class Ainside a third party library, so I can't modify it.
I need to use the declaration of class B to pass it to a method, is there a way to do it without modifying class A?
When I try this:
#include <iostream>
using namespace std;
class A
{
    public:
    union {
        class B
        {
            public:
            int x;
        };
    }un;
};

void foo(A::B & test)
{
}

int main() {
    A::B test;
    test.x=10;
    cout << test.x << endl;
    return 0;
}

I get the error:

error: B is not a member of A

Live Example!
My assumption is that it happens because B is in a unnamed namespace.
PS: If I could modify the declaration of the union
from:
union {...

to:
union T {...

This will be done simple by:
A::T::B test;

A:

You can get the type of the union using decltype, then you can access B:
decltype(std::declval<A&>().un)::B test;

coliru example


Q:

Javascript disable button

I need to disable couple of HTML Buttons on the page based on a boolean variable coming from the server.
I can access the variable on the JSP page. Do I need an event listener for this task? Any similar example would help a lot.

A:

I'm not sure of the exact syntax but you could do something like this..
<input type="button" <%= disableFlag ? "disabled=\"disabled" : "" %> />


Q:

What perfmon counters are useful for identifying ASP.NET bottlenecks?

Given the chart here, what should I be looking at to identify the bottleneck?  As you can see, requests are averaging nearly 14 seconds under load and the bulk of that time is attributed to the CLR in New Relic's profiling data. In the performance breakdown for a particular page, it attributes the bulk of the time to the WebTransaction/.aspx page.

A:

I see that the database is readed also (the orange) and this is seams that one of all pages have delay the rest of pages because of the lock that session make on the pages.
you can read also :
Replacing ASP.Net's session entirely
My suggestion is totally remove the session calls and if this is not possible, find an other way to save them somewhere in database by your self.
Actually in my pages I have made all three possible options. 1. I call the page with out session. 2 I have made totally custom session that are values connected to the user cookie, and last 3. I have made threads that are run away from the session and they make calculations on background, when they finish I show the results.
In some cases the calculations are done on iframe that call a page without session and there later I show the results.


Q:

Vue.js: event after v-for is done

I am trying to build a simple chat app with Vue.js. My problem is that the message area needs to scroll to the bottom when a new message is written.
I looping through the messages with v-for directive. Is there an event when v-for has updated the DOM?
I have made it so that the message area div listens to component's message-array. I tried so that in the same function that I am appending the message to the array, it would set the message area div's scrollTop to 99999. But the problem is that v-for is not done updating the DOM, so it will not scroll to the correct point.

A:

I had a similar issue but I took a different approach using the vue.nextTick(). I needed to be sure the v-for had finished rendering as the component will not re-render immediately, It will update on the next “tick” when the queue is empty.
Vue.component('message', {
  data() {
    return {
      message: []
    }
  },
  methods: {
    updateMessageArray(newMessage) {
      this.message.push(newMessage);

      this.$nextTick(() => {
         // Scroll Down
      })
    }
  }
})

https://vuejs.org/v2/api/#Vue-nextTick
https://vuejs.org/v2/guide/reactivity.html#Async-Update-Queue

A:

Have you tried using watch?
var vm = new Vue({
  data: {
    messages: []
  },
  watch: {
    'messages': function (val, oldVal) {
      //Scroll to bottom
    },
  }
})

Edit: Please see the other answer, as this solution requires using the nextTick function to ensure the DOM is updated.


Q:

No sound is generated when using PlaySound()

Basically I want to use the PlaySound() function in ctypes.

Yes I know winsound module is built on it and I could use that, but I have a reason to not do so :)

In C I would call the function like this:
PlaySound("sound.wav", NULL, SND_FILENAME);

I have my Python script equivalent:
import ctypes

winmm = ctypes.WinDLL('winmm.dll')

winmm.PlaySound("sound.wav", None, 0x20000)

I run it, no error is returned but the sound does not play either.

I suspect that the problem lies with the hex value (0x20000) since everything else seems fine.  I got this value like this:
import winsound
print(hex(winsound.SND_FILENAME))

Or in a different way:
import ctypes, winsound

winmm = ctypes.WinDLL('winmm.dll')

winmm.PlaySound("sound.wav", None, winsound.SND_FILENAME)

So how can I get this working so that my file plays?

A:

In Windows, there are Unicode and ANSI versions of functions.  The documentation indicates the filename is an LPCTSTR.  For the ANSI version that is defined as LPCSTR and for Unicode it is LPCWSTR.
Here's the proper way to call a Windows function.  Generally you want the W version of the function.  Defining .argtypes and .restype will also help with error checking.  As you found, you can pass the wrong type and it will not work.  With .argtypes defined, incompatible types will be caught.
from ctypes import *
from ctypes import wintypes as w

dll = WinDLL('winmm')

dll.PlaySoundW.argtypes = w.LPCWSTR,w.HMODULE,w.DWORD
dll.PlaySoundW.restype = w.BOOL

SND_FILENAME = 0x20000

# Call it with a Unicode string and it works.
dll.PlaySoundW('sound.wav',None,SND_FILENAME)

# Call it with a byte string and get an error since `.argtypes` is defined.
dll.PlaySoundW(b'sound.wav',None,SND_FILENAME)

Output (after sound plays):
Traceback (most recent call last):
  File "C:\test.py", line 15, in <module>
    dll.PlaySoundW(b'sound.wav',None,SND_FILENAME)
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type

Or skip all that work and just use the winsound module:
import winsound
winsound.PlaySound('sound.wav',winsound.SND_FILENAME)


Q:

Could a horseshoe magnet help a satellite stay in orbit?

If a horseshoe magnet was attached to a satellite orbiting the Earth, would the interaction of the Earth's magnetic field and the horseshoe magnet's magnetic field result in the magnet being propelled in the direction of travel and adding momentum to the satellite? If so, this magnet should help the satellite to maintain its orbit over its lifetime.
To illustrate how this propelling force would be created, please reference the drawing below:

The horseshoe magnet shown in the drawing (and the satellite) is moving in a West-to-East orbit around the Earth. This propelling force is created via the magnetic repulsion of the two magnetic fields.
Also, this horseshoe magnet could be mounted to the end of a ten foot plastic rod with the other end of the rod attached to the satellite so the magnet's magnetic field would not interfere with the satellite's electronics.
EDIT
I have thought about the issue of the magnet and satellite being rotated by the Earth's magnetic field instead of the magnet adding force/momentum in a West-to-East direction.
I believe a solution to this issue would be to place a magnet behind the satellite and another one in front of it, with each one being attached to the end of a long plastic rod so its magnetic field would not interfere with the satellite's electronics.
I have illustrated this concept in the new drawing below:

Would this be a viable solution to the rotation issue and would there be a propelling force which would add momentum to the satellite? These two magnets could be either permanent magnets or electromagnets.

A:

No. What can be done with a magnetic field in Earth's orbit is to torque, or rotate the satellite. But for propulsion of some kind, you would actually need to have some kind of a varying magnetic field, and a tether of some kind. This website talks a bit about how such a thing could work.

A:

Dipole-dipole repulsion
The drawing depicts the right idea; if you hold two parallel magnetic dipoles close together there is a strong repulsive force. If you let go, they will fly apart.
In order to imagine what would happen if this was in Earth orbit, let's make the horseshoe magnet an electromagnet. It's the same shape but instead of being made from permanent magnet material plus iron, it's only iron and we wrap a solar powered coil around it so we can turn it on once in its circular orbit.
When that happens there will be a radial force pushing the spacecraft outwards. This doesn't change the velocity because it's perpendicular to it, so now the spacecraft is going too fast for this circular orbit, and it will start rising in altitude until apoapsis, and then will return back to it's original state. You've raised the circular orbit into a slightly elliptical orbit with the same periapsis.
If you ramped up the field slowly, you'd raise the altitude slightly.
It's a little bit like being in a heliocentric orbit and pointing a giant solar sail directly at the Sun. Not the same because the Sun's intensity falls off as $1/r^2$ and the repulsion between two dipoles falls off as $1/r^4$.
Doesn't fight drag
This repulsion has no further effect long term. Once you've slightly raised the orbit you have a new balance between attractive and repulsive forces.
This doesn't stop the drag force from slowly sapping the spacecraft's angular momentum, because drag acts in the direction of motion whereas our repulsion is perpendicular to it. The spacecraft will continue to lose altitude and eventually burn up in the atmosphere. Depending on the kind of magnet used, it might be so large and able to absorb heat that chunks survive reentry and fall on someone's house.
Different but related:

Could a CubeSat be propelled by this low-tech electromagnetic propulsion system?
Is it possible to reach the Sun without expending any fuel/reaction mass

A:

Let me put this in a different frame. First recall that magnetic fields also store magnetic energy:
$$
E_{mag} = \int_V H. B\, dV
$$
Now, from Lagrangian mechanics, note that:
$$
L = U-V = E_{mag}+E_{grav}-\frac{mV^2}{2}-\frac{\omega^TI\omega}{2}
$$
And let's forget some dissipative effects and the angular terms for now.
Recalling Euler-Lagrange's equation:
$$
\frac{\partial L}{\partial r}-\frac{d}{dt}\left( \frac{\partial L}{\partial \dot{r}} \right)=0
$$
And understanding that the energy terms do no depend upon the time-derivative of the generalized coordinate, we have:
$$
\frac{\partial E_{mag}}{\partial r}+\frac{\partial E_{grav}}{\partial r}=m\dot{V}
$$
No news there, the gradient of the gravity potential energy is just the gravitational force everyone here knows well about. The new term, which intuitively we think could provide some orbit control is the derivative of the magnetic field:
$$
\frac{\partial E_{mag}}{\partial r}=\frac{\partial}{\partial r} \left[  \int_V H. B\, dV\right]
$$
Now, this terms represent the instantaneous rate change of magnetic stored energy per unit of length in the position of the spacecraft. So, this disregards changes in attitude of the spacecraft (we know well the effects of magnetic torques on satellites, and dropped any attitude related coordinate before). Thus, we can assume that the magnetic induction field created by the satellite ($B$) is independent of the spacecraft position. So:
$$
\frac{\partial E_{mag}}{\partial r} = \int_V \left[\frac{\partial H}{\partial r}    . B\, dV\right]
$$
And the Earth's magnetic field on its orbit $H$ is not constant over space. Right? Well, I'd like to find a better reference to this value, but picking to this paper ate 324km (which is very low for an orbit) You get at most 0.16nT/km gradient vertical in a magnetic anomaly. Thus, converting to SI base units, we're talking about $1.6 \times 10^{-11}$ T/m. Dividing by the magnetic permeability of vacuum we get 0.042 A/m². So to get the same the average thrust used by GOCE (which I'm assuming around 2mN), we'd need 2mN = 0.042 A/m² * B, resulting in B ~ 47T. Sounds like much to you?
Well, incidentally I had the hunch but not a reference to tell you if this value was big or not. My google search however tells me that the record holder for world's strongest magnet as of 2019 produces "only" a magnetic flux of 45.5 T.
Remember when people tell you not to bring metal objects close to an MRI machine? Well according to this reference "Across the MR industry, most scanners are 1.5T or 3.0T, however there are varying strengths below 1.5T and more recently, up to 7.0T.". They generate force enough to mechanically break components on a spacecraft.
At one hand, my reference for magnetic gradient is not so great, but you can search data for other orbital altitudes and redo the calculations yourself. Maybe one needs less thrust for higher orbit, but then the base magnetic field and its variations are also smaller.
But wait, there's more! (Trust me, I'm an Engineer). Strong magnetic fields especially if varying over time create electromagnetic interference which may mess up every wire onboard the spacecraft. Also, see this question for extended discussion. I'd even wager that a field this strong could mechanically damage the satellite by breaking its structure, I haven't done the math here, but I'm convinced by this video.
So, in summary: In orbit, and over the size of a satellite, and over the variations of the Earth's magnetic fields, magnetic forces (and not only torques) do exist all the time, but they are really small, to the point were any usable effect would require an insane amount of energy to generate an absurdly strong magnetic field which would probably destroy the satellite.


Q:

I am a new to Oracle XE and Oracle . Help me to create my first DB

I have installed  latest Oracle XE  on Windows 8.1 and Oracle Sql developer. Now I have some problem . My client has provided us one Remote Machine and I am using a VPN connection to access it . That machine  has Windows 2003 server and Oracle 11g or something installed . I want to copy a DB from that machine to my machine so that I can connect my local DB ( which should have all the Data and not just schema /( They have provided DDLs but it creates only DB schema which i dont want )/) . I am using ASP.NET 4.5 and VS 2013. I am totally new to Oracle . So my problem is how do I copy that DB on Remote to my Local .

A:

The easiest way would be to use oracle's exp and impfor export and import, but you'll need server side access to the remote db. Another approach, as you have the DDLs allready and if you don't care about a true complete snapshot of the maybe changing remote db would be to copy each tables data i.e. via sqlplus:
copy FROM user1/pwd@db1 TO user2/pwd@db2 INSERT targetTable  USING SELECT * FROM sourceTable;
Though I must say, I'm not sure if this works for clob-columns. And if this is suitable surely depends on the amount of data you have to copy.


Q:

How to change data of Main Activity from Fragment

I Have fragment 1, fragment 2, fragment 3 which are in the Main Activity. there is a TextView in the main Activity, how can the fragments change the text in the text view?
I already did the casting  (Actvity).getActivity but i don't want my app to have error when changing Activities

A:

Write a setter method like setTextViewText(String str) in the activity and from fragment call the method like ((YourActivity)getActivity()).setTexrViewText(str)