text:
Q: Generalised Linear Models: Binary data I am currently working on GLM problem.
My response variable is binary as are some of my explanatory variable,others are categorical i.e. 1-1day, 2- 2-3days, 3-5+days and so forth.
I have coded it into factors.
My question is: I have used the step function and I am left with a model with many insignificant variables, in this case; do I simply drop these variables, if not what do I do ?
Also I tried to do the model selection, manually, using the anova function to test if the differences in the deviance were significant enough, and this gives me an answer that is somewhat different to the automatic model selection. Is this to be expected?
How do i go about my model selection, and how can I test if the functional form of my variables is correct ?
Thanks any help! :)

A: Model selection is an art included numerous statistical skill and analyzing technique. Generally, if you get the correct model form or do the right way of variables selecting, the coefficient in result will be meaningful and the model will predict more correctly the target variables. And you can check it by splitting to the training set, validation set and testing set.
With the GLMs have a general form as $y_i=\beta_0+\sum_{i=1}^n\beta_ix_i+\epsilon$, we focus mostly on how to choose the right distribution of random component $Y$ and how to modify the predictors in the best way.

You can imagine that predicting will be more strict if you have the right distribution for the target variable. E.g, you can check the distribution by using the Tweedie model with the functional parameter can specify types distribution such as discrete (Poisson), continuous (Normal, Gamma) and mixed type (Compound Poisson). You can approach specifically shrinkage methods following each type of distributions.
For the predictors $X$, instead of removing the insignificant feature, you should try to make it better by detecting an anomaly or dropping the outlier. In a common way, plotting covariance matrix to see how relevant btw the features, you can analyze and adjust the threshold of boxplot for the continuous features, and categorical features can be split into the dummy matrix.
After that, you can fit the model and analyze the result. Trying to do several statistical tests to see how well features fit with target variables such as R-square, adjusted-R-square, p-value, do ANOVA testing, do some likelihood test AIC... Using the validation set (or cross-validation set) to improve the model.

Implement the result and testing method, then repeat the model selection steps until you get your expected result.
My resources: Non-Life Insurance Pricing with Generalized Linear Models-Authors: Ohlsson, Esbjörn, Johansson, Björn, and others paper for specific topic.
Hope it is helpful.


text:
Q: Extract EXIF orientation from JPEG without using any libraries I need to extract orientation from EXIF data in a JPEG file but I can't use external libraries like metadata-extractor.
Is it possible?

A: The library you have mentioned includes a lot of work. If you cannot use it then you will have to do the bunch of work yourself.
Short answer: yes, it's possible, but I would suggest you use a third-party library like the one you mentioned.

redpajama_set_name: RedPajamaStackExchange


text:
Q: $\operatorname{supp}(M) \subseteq \operatorname{supp}(N) \iff f_I(M)\subseteq f_I(N) $? Let $ R $ be a commutative unital ring, $ I $ an ideal of $ R $, and $ M $ an $ R $-module. It has proven (here) that if $\operatorname{supp}(M) \subseteq \operatorname{supp}(N)$ then
$\operatorname{cd}(I,M) \leq \operatorname{cd}(I,N)$. From this fact  one guesses that there is a relationship between "$f_I(-)$, the finiteness dimension of modules relative to $I$", and "the support of modules" such as: $$\operatorname{supp}(M) \subseteq \operatorname{supp}(N) \iff f_I(M)\le  f_I(N).  $$

Can anyone prove this relationship or give a counterexample, please? You can add any assumption that helps, such as "being local", or prove it for equality.

$f_I(M) = \inf\ \{i  : H_I^i(M)$ is not finitely generated$\}$ is defined in chapter 9 of the book Local Cohomology. An Algebraic Introduction with Geometric Applications by M. P. BRODMANN and R. Y. SHARP.


text:
Q: How to use aggregate with $lookup in Mongoose with foreign key in sub sub array? I'm trying to JOIN 3 tables in my express-mongo project.
I have a table called Product LIKE this:
Product:

_id:5f92a8dfad47ce1b66d4473b
name:"Freno 1"
createdFrom:5f648f7d642ed7082f5ff91f
category:5f92a00c4637a61a397320a1
description:"Freni di tutti i tipi"
sellingPrice:1050
purchasePrice:350

And I have to extract the available quantity after sum and subtract the quantity from other 2 tables: purchaseorders and salesorders
purchaseorders

_id:5f930c6c6817832c0d5acbb4
items:[
{
_id:5f930c6c6817832c0d5acbb5
product:5f92abaf17ec621c1da4f4f9
quantity:10
purchasingPrice:1500
discount:300
},
{
_id:5f930c6c6817832c0d5acbb6
product:5f92a8dfad47ce1b66d4473b
quantity:7
purchasingPrice:1500
discount:300
}]

salesorders

_id:5f930c6c6817832c0d5acbb4
items:[
{
_id:5f930c6c6817832c0d5acbb5
product:5f92abaf17ec621c1da4f4f9
quantity:3
sellingPrice:1500
discount:300
},
{
_id:5f930c6c6817832c0d5acbb6
product:5f92a8dfad47ce1b66d4473b
quantity:3
sellingPrice:1500
discount:300
}]

Purchaseorders and salesorders have be designed to contains different product in same order.
I'm trying to combine this 3 tables to have a result like this:
[
{_id: 5f92a8dfad47ce1b66d4473b,
name: "Freno 1",
quantity: 4 },
etc.. with all other products
]

I wanna sum all quantities in purchaseorders and subtract the sum of quantity of the salesorders.
I'm trying to use aggregation starting FROM Product table like this:
let result = await Product.aggregate([
        {
            $lookup: {
                from: "purchaseorders",
                localField: "_id",
                foreignField: "items.product",
                as: "purchaseorders"
            }
        },
        {
            $lookup: {
                from: "salesorders",
                localField: "_id",
                foreignField: "items.product",
                as: "salesorders"
            }
        },
        {
            $unwind: "$purchaseorders"
        },
        {
            $unwind: "$purchaseorders.items"
        },
        {
            $unwind: "$salesorders"
        },
        {
            $unwind: "$salesorders.items"
        },
        {
            $group: {
                _id: "$_id"
            }
        }
        ])

Thanks who tries to help me!!

A: You can try,

*

*$addFields to add quantity field,

*$reduce to iterate loop of purchaseorders, $reduce to iterate loop of items and get the matching product's quantity and $add with initial value of reduce

*$reduce to iterate loop of salesorders, $reduce to iterate loop of items and get the matching product's quantity and $add with initial value of reduce

*$subtract purchaseorders's quantity with salesorders'a quantity

let result = await Product.aggregate([
  // skipped { $lookup },
  // skipped { $lookup },
  {
    $project: {
      _id: 1,
      name: 1,
      quantity: {
        $subtract: [
          {
            $reduce: {
              input: "$purchaseorders",
              initialValue: 0,
              in: {
                $add: [
                  "$$value",
                  {
                    $reduce: {
                      input: "$$this.items",
                      initialValue: 0,
                      in: {
                        $cond: [
                          { $eq: ["$$this.product", "$_id"] },
                          { $add: ["$$value", "$$this.quantity"] },
                          "$$value"
                        ]
                      }
                    }
                  }
                ]
              }
            }
          },
          {
            $reduce: {
              input: "$salesorders",
              initialValue: 0,
              in: {
                $add: [
                  "$$value",
                  {
                    $reduce: {
                      input: "$$this.items",
                      initialValue: 0,
                      in: {
                        $cond: [
                          { $eq: ["$$this.product", "$_id"] },
                          { $add: ["$$value", "$$this.quantity"] },
                          "$$value"
                        ]
                      }
                    }
                  }
                ]
              }
            }
          }
        ]
      }
    }
  }
])

Playground


text:
Q: Could I change the save as destination from the document so I receive a pop-up to select the destination? In the moment the following coding is working but it saves automatically in a folder which is defined in the code.
Private Sub CommandButton2_Click()

' Button PDF '

    ActiveDocument.ExportAsFixedFormat OutputFileName:= _
    "\\Desktop\Test_PDF.pdf", ExportFormat:= _
    wdExportFormatPDF, OpenAfterExport:=True, OptimizeFor:= _
    wdExportOptimizeForPrint, Range:=wdExportFromTo, From:=2, To:=7, Item:= _
    wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
    CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
    BitmapMissingFonts:=True, UseISO19005_1:=False

End Sub

I want to change the code that I can select the saving destination, so I receive a pop-up if I press the button.

A: For example:
Private Sub CommandButton2_Click()
Application.ScreenUpdating = False
Dim strFolder As String, strFile As String, strTxt As String
strFolder = GetFolder
If strFolder = "" Then
  MsgBox "No Save Folder Selected!", vbCritical
  Exit Sub
Else
ActiveDocument.ExportAsFixedFormat _
  OutputFileName:=strFolder & "\Test_PDF.pdf", ExportFormat:=wdExportFormatPDF, _
    OpenAfterExport:=True, OptimizeFor:=wdExportOptimizeForPrint, _
    Range:=wdExportFromTo, From:=2, To:=7, Item:=wdExportDocumentContent, _
    IncludeDocProps:=True, KeepIRM:=True, CreateBookmarks:=wdExportCreateNoBookmarks, _
    DocStructureTags:=True, BitmapMissingFonts:=True, UseISO19005_1:=False
End If
Application.ScreenUpdating = True
End Sub

Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose the folder to save in", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function


text:
Q: White spaces in command line arguments. Cannot read "C:\Program Files" properly I need to run silent installation. The command is like this
setup.exe -silent -response <Response File> -jreLoc <jreLoc>

jreLoc is the folder where bin/java needs to be found.
I have installed JRockit as my JDK and it is installed in
"C:\Program Files\Java\jrockit-jre1.6.0_29-R28.2.0"
The problem that I face is the value for jreLoc is read only till "C:\Program" no matter what I do in terms of editing the path or tweaking, double quotes, forward or backward slashes etc.
I use a Python script to set up all the environment and later the Python script calls the setup.exe command.
I have searched online but the workarounds are not working.
Any hints or pointers are greatly appreciated.

A: All Windows paths containing spaces also have an equivalent path without spaces that you can use if you can't figure out how to get the program to accept the path with spaces.
For your particular example the spaceless path is probably C:\Progra~1\Java\jrockit-jre1.6.0_29-R28.2.0' but if you open a command prompt and usedir /x` on the top level folder that will tell you what it is on your system:
C:\>dir /x c:\progr*
 Volume in drive C is XP System
 Volume Serial Number is D8B8-DBEB

 Directory of c:\

30/01/2012  16:16    <DIR>          PROGRA~1     Program Files
13/02/2012  13:51    <DIR>          PROGRA~2     Program Files (x86)
               0 File(s)              0 bytes
               2 Dir(s)  26,189,307,904 bytes free

A: Try adding another pair of double quotes around the existing quotes:
"\"C:\Program Files\Java\jrockit-jre1.6.0_29-R28.2.0\""

in your Python script. This way one pair will be for Python and other will be for the shell that calls the external executable.


text:
Q: Windows CE simple multithreaded application - thread scheduling I have created simple application for Windows CE 5.0 as a exercise for some multithreaded work.
In WinMain I am calling twice function for creating threads:
 myThread = CreateThread(NULL, 0, myThreadFunc(), NULL, 0, NULL);
 myThread2 = CreateThread(NULL, 0, myThreadFunc2(), NULL, 0, NULL);

And functions executed in threads looks like this:
LPTHREAD_START_ROUTINE myThreadFunc()
{
    Sleep(3000);
    MessageBox(NULL, _T("thread 1"), _T("thread 1"), MB_OK);
    return 0;
}

LPTHREAD_START_ROUTINE myThreadFunc2()
{
    Sleep(2000);
    MessageBox(NULL, _T("thread 2"), _T("thread 2"), MB_OK);
    return 0;
}

I was expecting that program shows dialog box from thread 2 after 2 secs and after next 1 sec show the dialog box from thread 1. But actually when i am running this program it shows at first dialog box from thread 1 after 2 secs and then dialog box from thread 2 after next 3 secs. It seems like this treads are running sequentially and not simultaneously as I expected. Can anybody explain me this behavior, please?
I am using Windows CE 5.0, Windows eMbedded Visual C++ and Emulator for Windows CE STANDARDSDK_500.
Thank you for your help in advance.

A: Edit: Right answer is in comments.
Thank you for your effort. I just realized i have incorrect calling of function createThread(). Instead of:
myThread = CreateThread(NULL, 0, myThreadFunc(), NULL, 0, NULL);

I have to type:
myThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&myThreadFunc, NULL, 0, NULL);


text:
Q: gridline/ticklines in dashed in canvas in flot.js How can I create dashed lines in both x-axis and y-axis in flot.js? I don't know where to change in library. This is my code Of generated graph on canvas using flot.js. But I want the Dashed Lines on x-axis and y-axis on grid background in canvas.  I try markingsStyle: 'dashed' but that did not work.
plot = $.plot("#placeholder", [{
            dashes: { show: true },
            data: data,
            color: "rgb(255, 255, 255)",
            label: $("#hidsymbolid").val(),
        }, {
            data: dataBaseLine,
            color: "rgb(255, 255, 255)",
            lineStyle: "dashed"
        }
        ], {
            series: {
                lines: {
                    lineWidth: 1,
                    show: true,
                    lineJoin: "round",
                    lineCap: "round"
                },
                points: {
                    show: false
                }
            },
            grid: {
                hoverable: true,
                backgroundColor: {
                    colors: ["#3B3B3B", "#3B3B3B"]
                },
                markingsStyle: 'dashed'
            },
            xaxis: {
                show: true,
                tickSize: parseFloat((maxvalue - minvalue) / 6),
                min: minvalue,
                max: maxvalue,
                dashes: { show: true },
                timeformat: "%H:%M:%S",
                tickColor: "rgb(255, 255, 255)",
            },
            yaxis: {
                show: true,
                dashes: { show: true },
                color: "rgb(255, 255, 255)",
                alignTicksWithAxis: 2
            }
});

A: Please try this.
setLineDash([5])
Example:-
var context = document.querySelector("canvas");
var cxt = context..getContext('2d');
cxt.beginPath();
cxt.setLineDash([9]);
cxt.rect(30,15,100,100);
cxt.stroke();


text:
Q: Fresh Magento 2 install admin does not give login box I'm fairly new to Magento 2 and have been attempting to add a copy on my local machine (operating system: Windows 10) so that I can try out some database migration tests.
I have installed XAMPP and proceeded with the installation instructions. I was then rewarded with the following screen:

The actual site address seems to open a follows:

However when I click on "Launch Magento Admin" I get taken to a blank screen:

I've opened the developers console to see if anything is wrong and the following errors seem to be in effect:

Looking at this, I would think that this is an effect of the adminhtml styles not being loaded.
Regardless, does anyone know how I can fix this?

A: Yes, This is the problem with windows. Windows uses "\" as separator, the array "directories" contains entries with "/" as separator, so the check will always fail.
So you need to fix this by replacing the separator in core file:
Magento\Framework\View\Element\Template\File\Validator

function isPathInDirectories replace below code in isPathInDirectories function
$realPath = str_replace('\\', '/', $this->fileDriver->getRealPath($path));


text:
Q: Why there is an redundant variable debugInit in java.security.AccessControlContext? I was going through java.security.AccessControlContext, and encountered below piece of code:
private static boolean debugInit = false;
private static Debug debug = null;

static Debug getDebug()
{
    if (debugInit)
        return debug;
    else {
        if (Policy.isSet()) {
            debug = Debug.getInstance("access");
            debugInit = true;
        }
        return debug;
    }
}

Question: why do we need an additional variable debugInit, when we can simple check for if (debug == null) and getInstance() like below:
static Debug getDebug()
{
    if (debug == null && Policy.isSet()) {
        debug = Debug.getInstance("access");
    }
    return debug;
}

Am I missing something or is there any specific reason to use additional variable debugInit (which is not referenced anywhere else) ?


text:
Q: Trivial and non-trivial solution What is meaning of trivial solution and non-trivial solution?
What is it's relation with homogeneous equation?

Suppose, a question
$2x+y+2z=0$
$x+y+3z=0$
$4x+3y+bz=c$
What is value of $b$ and $c$ for trivial and non-trivial solutions?
How many trivial and non-trivial solution can we get from here?

A: Hy first: if $c\neq 0$ no trivial solution for the system
If $c=0$ solving the first two equations yields $x=z$ and then in the third if $b\neq -4$ no trivial solution $x=y=z=0$ is possible.


text:
Q: Why i get 'Incorrect integer value:' on int field with allow NULL & default NULL I just changed, on phpmyadmin, an int obligatory field to not obligatory (i ticked the empty checkbox) and made default values NULL.
So far so good,
 the problem is when i try to change this value on already exist records (from phpmyadmin) and delete the number value, i get a warning message :
Affected 0 records.
Warning: #1366 Incorrect integer value: '' for column 'fktypeId' at row 1

and it puts 0 on the field value.
I dont want to have any value at all into that field, neither 0 nor NULL, just empty field.
Can this happen? Thanks in advance.
This is definitelly a phpmyadmin way of manipulating the not obligatory Int fields.
We just have to check the checkbox!! otherwise it turns always the field value to 0
Thanks folks, i post the printscreen for those who come up with this 'problem'.

A: An integer column can only store an integer value, or a NULL.  A zero length string cannot be "stored" in an integer column.
The warning is the expected behavior if a string value which can't be converted to an integer value is supplied for an integer column.
If you are running a SQL statement, you can use the keyword NULL
For example:
 UPDATE mytable SET some_int_col = NULL WHERE id = 42 ;

If you are using some kind of "row editor", then there may be a checkbox you need to select for the NULL value.
With a SQL statement, such as this:
 UPDATE mytable SET some_int_col = '' WHERE id = 42 ;

The literal string value (in this case, a zero length string) is being assigned to a column of integer datatype, MySQL will implicitly perform a conversion. In a numeric context, the zero length string evalutes to zero.
For comparison, consider the behavior when different strings are implicitly converted to numeric.
 SELECT '' AS foo,  '' + 0 AS foo_int
 UNION ALL SELECT ' b'     , ' b'      + 0
 UNION ALL SELECT '1A'     , '1A'      + 0
 UNION ALL SELECT ' 23DE78', ' 23DE78' + 0
 UNION ALL SELECT NULL     , NULL      + 0

returns
foo       foo_int
--------  -------
                0
 b              0
1A              1
 23DE78        23
(NULL)     (NULL)


text:
Q: Is Axis2/C still being maintained? I have to write a web-service client and server (a kind of proxy) and was looking at my options.  I narrowed it down to Axis2/C and gSOAP for a number of reasons.  I tended toward Axis2/C mainly because of the more permissive license, but saw that the last version is dated April 2009!
Is it still being maintained?  Has everyone gone to something else (gSOAP or something else entirely)?
PS: I have no experience in WS and got all my info from Google searches.

A: Axis2/C is still maintained but progress is too slow, it has only few commits in last year.
Consider using of Axis2/C-unofficial project which is a fork of Axis2/C-1.6.0.
For details please see this answer.


text:
Q: Is it better to use "static member" in circular linked list or just go by iterative way? Code I made for circular linked list:
#include<iostream>
using namespace std;
class node
{
  public:
  int data;
  node* next;
  node():data(0),next(NULL){}
  node(int x):data(x),next(NULL){}
};
void push(node** head_ref,int val);
void printlist(node* n);
int main()
{
  node* head=NULL;
  push(&head,14);
  push(&head,24);
  push(&head,67);
  push(&head,77);
  printlist(head);
  return 0;
}
void push(node** head_ref,int val)
{
  node* new_node=new node(val);
  static node* temp_head=NULL;
  if(*head_ref==NULL)
  {
     temp_head=new_node;
     *head_ref=new_node;
     new_node->next=*head_ref;
  }
  else
  {
     new_node->next=*head_ref;
     temp_head->next=new_node;
     *head_ref=new_node;
  }
}
void printlist(node* n)
{
   node* head_ref=n;
   while(n!=NULL)
   {
      cout<<n->data<<" ";
      if(n->next!=head_ref){n=n->next;}
      else if (n->next==head_ref){break;}
   }
}

I was trying to write a code for circular linked list.
I have used static node* in void push() is it good method or to go by iterative approach
by using while-for loop?

A: Okay, first of all regarding the static variable it is a pretty good hack to keep the last node (i think you were intending to do that when you started to implement the code). But a quick remark your circular linked list will be reversed in this case because by the idea of the linked list you should add your nodes to the end of the list and not the front(you did just that). I would definitely qualify the code as good if you would have told me this is a code for a reverse linked list.
This is pseudocode for your push function
node* new_node=new node(val);
static node* temp_head=nullptr;
if(*head_ref==nullptr)
  {
     temp_head=new_node;
     *head_ref=new_node;
     new_node->next=*head_ref;
  }
else
{
     temp_head->next = new_node;
     temp_head = temp_head->next;
     temp_head->next = *head_ref;
}

But please look at some other implementations of a circular linked list because this one can't be mark approved. You should have a class CircularLinkedList which will carry on all the action like push or print.


text:
Q: c# linq List property and group by Given this sample code:
var item1 = ("Test1", new List<string>() { "1", "2", "3" });
var item2 = ("Test2", new List<string>() { "1", "2", "3" });
var item3 = ("Test3", new List<string>() { "1", "2", "3" });

var _list = new List<(string ID, List<string> Items)>
{
    item1,
    item2,
    item3
};

var groupby = _list.GroupBy(x => x.Items);

When you call GroupBy here, why isn't the result a single group, since the list of "Items" are all the same?

A: Because the lists contain the same elements in the same order doesn't mean they are the same. The default definition of same for two lists is if they have the same reference, meaning if they point to the same object in the memory.
You have three different references pointing to three different objects.
If you would like to override this behaviour and re-define what "same" means, you can implement an IEqualityComparer for List<string> that checks if the two lists contain same elements in same order. And supply that comparer to GroupBy.


text:
Q: Android connect to google cloud sql with jdbc i'm trying to connect to my database at cloud sql from my android applicion.
initially i try to open connection with the data base and than working with AsyncTask for queries.
While i tried to connect i get this error:
java.sql.SQLException: No suitable driver
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err:
at java.sql.DriverManager.getConnection(DriverManager.java:186)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:213)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at com.example.user.trackyournevi.database.GoogleConnection.initDBConnection(GoogleConnection.java:46)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at com.example.user.trackyournevi.database.GoogleConnection.<init>(GoogleConnection.java:40)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at com.example.user.trackyournevi.database.GoogleConnection.getsInstance(GoogleConnection.java:35)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at com.example.user.trackyournevi.LoginActivity.onCreate(LoginActivity.java:86)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at android.app.Activity.performCreate(Activity.java:6876)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at android.app.ActivityThread.access$1100(ActivityThread.java:221)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at android.os.Looper.loop(Looper.java:158)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7224)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at java.lang.reflect.Method.invoke(Native Method)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
05-08 21:51:29.533 12626-12626/com.example.user.trackyournevi W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

my code is:
package com.example.user.trackyournevi.database;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class GoogleConnection {

private static final String TAG = "GoogleConnection";

private static GoogleConnection mInstance = null;

private Connection connection;
private String DRIVER_CLASS = "com.mysql.jdbc.Driver";

private String DB_NAME = "xxx";
private String DB_USER = "xxx";
private String DB_PASSWORD = "xxx";

private String DB_URL = String.format("jdbc://mysql://xxx.xxx.xxx.xxx:3306/");

public static synchronized GoogleConnection getsInstance() {
    //Use the application context, which will insure that you don't
    //accidentally leak on Activity's context
    if(mInstance == null)
        mInstance = new GoogleConnection();
    return mInstance;
}

private GoogleConnection() {
    initDBConnection();
}

private void initDBConnection() {
    try {
        Class.forName(DRIVER_CLASS);
        this.connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    } catch (SQLException | ClassNotFoundException e){
        //Log.e(TAG, "Can not connect to db");
        e.printStackTrace();
        System.exit(0);
    }
}

I tried to replace mysql-connector.jar but it's not working
Is someone can help me?
Tnx

A: I think you miss to use the DB_NAME in your URL :
private String DB_URL = String.format("jdbc://mysql://xxx.xxx.xxx.xxx:3306/");
//WHERE IS THE DB NAME-----------------------------------------------------^

Second the url should look like this :
jdbc:mysql://<host>:<port>/<database_name>

You have to remove the //:
jdbc://mysql://xxx.xxx.xxx.xxx:3306/
//   ^^------------------------------------------

I think you need something like this :
private String DB_URL = String.format("jdbc:mysql://xxx.xxx.xxx.xxx:3306/" + DB_NAME);

Second :


text:
Q: How do you implement a culture-specific address form using ASP.NET MVC? We currently have a WebForms control with an update panel. The code-behind contains logic to show/hide fields based on the selected country. This is fine for WebForms, but we ware moving to MVC, and I'm having a hard time sorting this out. I also need this to be localized, both in terms of localizable resource strings as well as displaying different form fields for different countries.
We currently store the resource strings in a .resx file in a Resources folder. Our address fields per country is stored in an XML doc that we load and parse when the country changes. This is then used to locate the respective controls and show/hide those necessary. The last bit I'm trying to work out is validation messages. Reflection doesn't work on Resource classes, and I don't know of any utilities to allow variables in an attribute definition.
I've thought of using an XSL transform to create the address bit from our persisted address fields. Is that a valid approach?

A: You should still be able to output the correct language text just by reaching into the resource itself.  A helper method might make it easier to type / more readable, but that will get you your form properly.
For displaying different controls, you could create a partial that pertains to a particular country, and load those up dynamically, something like:
<%= Html.RenderPartial("_addressForm-" + countryCode) %>

Again, a helper method might make this easier / more transparent.
Lastly, what type of validation are you using?  The built-in MVC2 validation attributes off of a a view model?  If so, I believe this is built-in to the attributes that you use to specify required fields, etc.
Hope this helps.

A: I discovered I was trying to use reflection incorrectly against my resource type and was able to create a few methods to get the correct resource:
public string GetLabel(string control)
{
    string strResourceName;
    try
    {
        AddressInfoField field = AddressFields.First(f => f.m_strControl == control);
        strResourceName = field.m_strName;
    }
    catch // Catch everything
    {
        return string.Empty;
    }

    if (string.IsNullOrEmpty(strResourceName))
        return string.Empty;

    return GetResource(strResourceName);
}

public string GetValidationMessage(string control)
{
    string strResourceName;
    try
    {
        AddressInfoField field = AddressFields.First(f => f.m_strControl == control);
        strResourceName = field.m_strName;
    }
    catch // Catch everything
    {
        return Addressing.Required;
    }

    if (string.IsNullOrEmpty(strResourceName))
        return Addressing.Required;

    return GetResource(strResourceName + "Required");
}

private static string GetResource(string strResourceName)
{
    PropertyInfo property = typeof (Addressing).GetProperty(strResourceName, BindingFlags.Public | BindingFlags.Static);
    if (property == null)
        throw new InvalidOperationException("Could not locate a resource for Addressing." + strResourceName);
    if (property.PropertyType != typeof(string))
        throw new InvalidOperationException("The requested resource does not return a string.");
    return (string) property.GetValue(null, null);
}

Then in my Spark view, I can use:

    ${Model.GetLabel("City")}
    ${Html.EditorFor(x => x.City)}
    !{Html.ValidationMessage("City", Model.GetValidationMessage("City"))}


text:
Q: Is $X_t = tW\left(\frac{1}{t}\right)$ a Martingale?If not, how could it be a Brownian Motion? As is proved, $X_t = tW\left(\frac{1}{t}\right)$ is a Brownian motion. For example see Theorem 4.2 in this paper http://math.uchicago.edu/~may/REU2012/REUPapers/Leiner.pdf
I'm just confused because it seems to me that this inverted Brownian Motion is not a  martingale. Take $s>t\ge 1$, then
$$\mathbb{E}_t[X_s] =\mathbb{E}_t\left[sW\left(\frac{1}{s}\right)\right] $$
But isn't $W\left(\frac{1}{s}\right)$ a piece of known information by time $t$? Therefore we can take it out from the expectation, but the past path of Brownian Motion could be anything, and it seems to me that $X_t$ is not a martingale. In my humble knowledge, Brownian Motion has to be a martingale, and it's a contradiction to me. Where was I wrong?


text:
Q: list manipulation in python I have a list with sublists in it. EG: ([1, 2], [1, 56], [2, 787], [2, 98], [3, 90]) which is created by appending values to it while running a for loop.
I am working in python, and i want to add the 2nd element of each sublist where the 1st elements are same. in my eg:
i want to add 2+56 (both have 1st index as 1), 787+98(both have 1st index as 2) and keep 90 as it is because there is just one element with 1st index as 3.
I'm not sure how to do this.
Here is my code:
import urllib, re
from itertools import groupby
import collections
import itertools, operator
text = urllib.urlopen("some html page").read()
data = re.compile(r'.*?<BODY>(.*?)<HR>', re.DOTALL).match(text).group(1)// storing contents from the BODY tag
values = [line.split() for line in data.splitlines()] //List with the BODY data
/* values contain elements like [[65, 67], [112, 123, 12], [387, 198, 09]]
   it contains elements with length 2 and three.
   i am just concerned with elements with length 3
   in the for loop, i am doing this, and passing it to 2 functions.*/

def function1 (docid, doclen, tf):
    new=[];
    avgdoclen = 288;
    tf = float(x[2]);
    doclen = float(x[1]);
    answer1 = tf / (tf + 0.5 + (1.5*doclen/avgdoclen));
    q = function2(docid, doclen, tf)
    production = answer1 * q //this is the production of
    new.append(docid) // i want to add all the production values where docid are same.
    new.append(production)
    return answer1

def function2 (docid, doclen, tf):
    avgdoclen = 288;
    querylen = 12;
    tf= float(x[2]);
    answer2 = tf/(tf + 0.5 + (1.5*querylen/avgdoclen));
    return answer2

for x in values:
    if len(x)==3:
        okapi_doc(x[0], x[1], x[2])
        okapi_query(x[0], x[1], x[2])

I want to add all the production values where the docid are same. Now when i print new, i get the following output:
['112', 0.3559469323909391]
['150', 0.31715060007742935]
['158', 0.122025819265144]
['176', 0.3862207694241891]
['188', 0.5057900225015092]
['236', 0.12628982528263102]
['251', 0.12166336633663369]

this is not a list. when i print new[0][0] i get 1. I want to get 112 when i print new[0][0]. Is there something wrong with append?
    ['334', 0.5851519557155408]

A: This might be a job for itertools:
>>> import itertools, operator
>>> l = sorted([[1, 2], [1, 56], [2, 787], [2, 98], [3, 90]])
>>> keys_groups = itertools.groupby(l, key=operator.itemgetter(0))
>>> sums = [[key, sum(i[1] for i in group)] for key, group in keys_groups]
>>> sums
[[1, 58], [2, 885], [3, 90]]

Note that for groupby to work as expected, the items have to be sorted by the key given. In this case, since the key is the first item in the pair, I didn't have to do this, but for a more general solution, you should use a key parameter to sort the list.
>>> l2 = [[787, 2], [98, 2], [90, 3], [2, 1], [56, 1]]
>>> l2.sort(key=operator.itemgetter(1))
>>> l2
[[2, 1], [56, 1], [787, 2], [98, 2], [90, 3]]
>>> keys_groups = itertools.groupby(l2, key=operator.itemgetter(1))
>>> sums = [[key, sum(i[0] for i in group)] for key, group in keys_groups]
>>> sums
[[1, 58], [2, 885], [3, 90]]

Works fine with the data you posted. I edited it a bit to make the example more realistic.
>>> l = [['112', 0.3559469323909391], ['150', 0.31715060007742935],
         ['158',0.122025819265144], ['176', 0.3862207694241891],
         ['188', 0.5057900225015092], ['377', 0.12628982528263102],
         ['251', 0.12166336633663369], ['334', 0.5851519557155408],
         ['334', 0.14663484486873507], ['112', 0.2345038167938931],
         ['377', 0.10694516971279373], ['112', 0.28981132075471694]]
>>> l.sort(key=operator.itemgetter(0))
>>> keys_groups = itertools.groupby(l, key=operator.itemgetter(0))
>>> sums = [[key, sum(i[1] for i in group)] for key, group in keys_groups]
>>> sums
[['112', 0.88026206993954914], ['150', 0.31715060007742935],
 ['158', 0.122025819265144], ['176', 0.38622076942418909],
 ['188', 0.50579002250150917], ['251', 0.12166336633663369],
 ['334', 0.73178680058427581], ['377', 0.23323499499542477]]

Note that as WolframH points out, sorting will generally increase the time complexity; but Python's sort algorithm is smart enough to make use of runs in data, so it might not -- it all depends on the data. Still, if your data is highly anti-sorted, Winston Ewert's defaultdict-based solution may be better. (But ignore that first Counter snippet -- I have no idea what's going on there.)
A couple of notes on how to create a list -- there are lots of ways, but the two basic ways in Python are as follows -- first a list comprehension:
>>> def simple_function(x):
...     return [x, x ** 2]
...
>>> in_data = range(10)
>>> out_data = [simple_function(x) for x in in_data]
>>> out_data
[[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

And second, a for loop:
>>> out_data = []
>>> for x in in_data:
...     out_data.append(simple_function(x))
...
>>> out_data
[[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

A: This is pretty straightforward. dict.get(key, default) returns the value if the key exists, or a default.
totals = {}
for k,v in data:
    totals[k] = totals.get(k, 0) + v

A: import collections
result = collections.defaultdict(int) # works like a dictionary
# but all keys have a default value of zero
for key, value in mylist:
    result[key] += value

print result

A: The fact that you:

want to add the 2nd element of each sublist where the 1st elements are same

makes me think that you want to be using a dict rather than a list - a dict is optimised for retrieving the 2nd value based on the 1st
Some code along the lines of:
oldvalue = mydict.get(firstvalue, 0)
newvalue = oldvalue + secondvalue
mydict[firstvalue] = newvalue

would let you build up the dict as you go - or if that's not feasible, it will let you calculate the sums in only a single pass over the list.
Quick spin in the interpreter just to test this out:
>>> l = [[1, 2], [1, 56], [2, 787], [2, 98], [3, 90]]
>>> mydict = {}
>>> for firstvalue, secondvalue in l:
...   oldvalue = mydict.get(firstvalue, 0)
...   newvalue = oldvalue + secondvalue
...   mydict[firstvalue] = newvalue
...
>>> print mydict
{1: 58, 2: 885, 3: 90}

Looks fairly close to what you want.


text: Q: No "Date and Time" Gui Tab The time is displayed on the top panel on my Ubuntu 13.10. When I click there, a menu opens as usual. But, when I click on "Date and Time Settings", it does not open "Date and Time" window, rather "All Settings" window opens. I found that there is no "Date and Time" option under "All Settings". I can find many commands on internet to change date and time from terminal. But how to bring the "Time and Date" tab back?


text:
Q: Contribution fault current data to CSV I am using IEEE39 bus data.If only bus_1 fault in system. I can use pssarrays.ascc_currents to see the contribution current of other buses.But I don't know how to use python to save other buses contribution current one by one data to CSV.
I use psse ver34 & python 2.7.
I have this small code:
psspy.short_circuit_units(1)
psspy.short_circuit_coordinates(1)
sid = 3
all = 0
rprtyp = 2 # or 3
rprlvl = 0 # number of contribution levels
fltbuses=[1]
psspy.bsys(sid,0,[0.0,0.0],0,[],len(fltbuses),fltbuses,0,[],0,[])
rlst = pssarrays.ascc_currents(sid,all,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1.0,"","","",rprtyp,rprlvl)

In psse the answer is:
    AT BUS_1  /FAULTED BUS IS:  1 / 0 LEVELS AWAY
     FROM                /I+/       AN(I+)
SYNCHRONOUS MACHINE      /1898.3/   -63.96
      2                  /3332.5/  -102.76
     39                  /6649.2/   -87.59
 INITIAL SYM. S.C. CURRENT(I''k) /11605.3/   -88.14

I know total three phase fault current api is rlst.flt3ph.values()
fault bus api is rlst.fltbus
I can't find the corresponding api code about contribution current.
I want to print these data to csv.
    [SYNCHRONOUS MACHINE][1898.3][-63.96]
          [2][3332.5][-102.76]
         [39][6649.2][-87.59]
[total 3ph fault current][11605.3][-88.14]

Thanks in advance!


text:
Q: Search button - Twitter Search API I'm trying to create a button that takes a subject you've typed in and pulls the relevant tweets using the Twitter Search API.
I've seen something similar with the jTwitter plugin, but I'm not sure on how to do it myself, and can't seem to find any documentation on it.
Here's the jQuery:
twitterUrl = "http://search.twitter.com/search.json?"+ q +"&rpp=1500&page=2&result_type=recent&callback=?";
       twitterList = $( "
" );
       twitterFunction = function( data ) {
             $.each( data.results, function( i, item ) {
                   $( "
", { "text" : item.text } )
                        .appendTo( twitterList );
                   });
             $( "#twit" ).fadeOut( "fast", function(){
                   $( this ).empty()
                        .append( twitterList )
                        .fadeIn( "slow" );
                   });
             };
$.getJSON( twitterUrl, twitterFunction );

And the HTML:

        <form>
            <input type="text" id="subject" name="q" placeholder="subject..." >
            <input type="button" id="start" value="start" >
        </form>

And a working jsFiddle.
Thanks for your help.

A: Check the implementation @ http://jsfiddle.net/Jayendra/reVy7/10/
Customize the results handling.

A: I'll suggest you to use  jQuery Twitter Search Plugin


text:
Q: boost signal double free? I'm having a hell of a time trying to debug some kind of memory access error, which I believe is a double free. The code is too complex to post, but I can try to describe it.
Basically, I have two threads. When the worker thread is created, it instantiates a new boost::signal object, and stores it in a shared_ptr. The parent then queries the thread for the signal, and the parent connect()s the shared_ptr signal to a handler function.
This all works, up until the point where the thread is finished and tries to clean up. Here is a snip of the call stack, in the hopes that someone might see something I missed.
ntdll.dll!7c90120e()
ntdll.dll!7c96e139()
ntdll.dll!7c96e576()
ntdll.dll!7c9622e8()
kernel32.dll!7c85f8d7()
Worker.dll!_CrtIsValidHeapPointer(const void * pUserData=0x01788aa8)  Line 1807 C
Worker.dll!_free_dbg_lk(void * pUserData=0x01788aa8, int nBlockUse=1)  Line 1132 + 0x9  C
Worker.dll!_free_dbg(void * pUserData=0x01788aa8, int nBlockUse=1)  Line 1070 + 0xd C
Worker.dll!operator delete(void * pUserData=0x01788aa8)  Line 54 + 0x10 C++
Worker.dll!std::allocator<std::_List_nod<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >::_Node>::deallocate(std::_List_nod<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >::_Node * _Ptr=0x01788aa8, unsigned int __formal=1)  Line 132 + 0x9  C++
Worker.dll!std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >::clear()  Line 622 C++
Worker.dll!std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >::_Tidy()  Line 931 C++
Worker.dll!std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >::~list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >()  Line 366 C++
Worker.dll!std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > >::~pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > >()  + 0x2e   C++
Worker.dll!std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node::~_Node()  + 0x12  C++
Worker.dll!std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node::`scalar deleting destructor'()  + 0xf C++
Worker.dll!std::_Destroy<std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node>(std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node * _Ptr=0x013a3008)  Line 50   C++
Worker.dll!std::allocator<std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node>::destroy(std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node * _Ptr=0x013a3008)  Line 152 + 0x9  C++
Worker.dll!std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Erase(std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node * _Rootnode=0x013a3008)  Line 896   C++
Worker.dll!std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Erase(std::_Tree_nod<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Node * _Rootnode=0x013a2f48)  Line 894   C++
Worker.dll!std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::clear()  Line 782    C++
Worker.dll!std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::erase(std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::iterator _First={...}, std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::iterator _Last={...})  Line 754 C++
Worker.dll!std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::_Tidy()  Line 1144   C++
Worker.dll!std::_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >::~_Tree<std::_Tmap_traits<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > >,0> >()  Line 393   C++
Worker.dll!std::map<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > > >::~map<boost::signals::detail::stored_group,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> >,boost::function2<bool,boost::signals::detail::stored_group,boost::signals::detail::stored_group,std::allocator<boost::function_base> >,std::allocator<std::pair<boost::signals::detail::stored_group const ,std::list<boost::signals::detail::connection_slot_pair,std::allocator<boost::signals::detail::connection_slot_pair> > > > >()  + 0xf    C++
Worker.dll!boost::signals::detail::named_slot_map::~named_slot_map()  + 0xf C++
Worker.dll!boost::signals::detail::signal_base_impl::~signal_base_impl()  Line 33 + 0x1d    C++
Worker.dll!boost::signals::detail::signal_base_impl::`scalar deleting destructor'()  + 0xf  C++
Worker.dll!boost::checked_delete<boost::signals::detail::signal_base_impl>(boost::signals::detail::signal_base_impl * x=0x013a2d98)  Line 34 + 0x1c C++
Worker.dll!boost::detail::sp_counted_impl_p<boost::signals::detail::signal_base_impl>::dispose()  Line 79 + 0xc C++
Worker.dll!boost::detail::sp_counted_base::release()  Line 102 + 0xd    C++
Worker.dll!boost::detail::shared_count::~shared_count()  Line 209   C++
Worker.dll!boost::shared_ptr<boost::signals::detail::signal_base_impl>::~shared_ptr<boost::signals::detail::signal_base_impl>()  + 0x12 C++
Worker.dll!boost::signals::detail::signal_base::~signal_base()  Line 184 + 0x8  C++
Worker.dll!boost::signal2<void,enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >,boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > >::~signal2<void,enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >,boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > >()  + 0x77 C++
Worker.dll!boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > >::~signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > >()  + 0x2b C++
Worker.dll!boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > >::`scalar deleting destructor'()  + 0x2b  C++
Worker.dll!boost::checked_delete<boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > > >(boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > > * x=0x013a2cf8)  Line 34 + 0x2b  C++
Worker.dll!boost::detail::sp_counted_impl_p<boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > > >::dispose()  Line 79 + 0xc C++
Worker.dll!boost::detail::sp_counted_base::release()  Line 102 + 0xd    C++
Worker.dll!boost::detail::shared_count::~shared_count()  Line 209   C++
Worker.dll!boost::shared_ptr<boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > > >::~shared_ptr<boost::signal<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),boost::last_value<void>,int,std::less<int>,boost::function<void __cdecl(enum signal_e,std::basic_string<char,std::char_traits<char>,std::allocator<char> >),std::allocator<void> > > >()  + 0x2e C++
Worker.dll!CWorker::~CWorker()  Line 77 + 0x24  C++
Worker.dll!CWorker::`scalar deleting destructor'()  + 0x2b  C++
Worker.dll!boost::checked_delete<CSubclass>(CSubclass* x=0x013a2ab0)  Line 34 + 0x32    C++
Worker.dll!boost::detail::sp_counted_impl_p<CSubclass>::dispose()  Line 79 + 0xc    C++
Parent.exe!boost::detail::sp_counted_base::release()  Line 102 + 0xd    C++
Parent.exe!boost::detail::shared_count::~shared_count()  Line 209   C++
Parent.exe!boost::shared_ptr<void>::~shared_ptr<void>()  + 0x19 C++
Parent.exe!CWorker::~CWorker()  Line 33 + 0x20  C++

Any advice would be appreciated. I've been going over this for a few days but can't figure out the issue.

A: I ran into this a year or two ago and, IIRC, it was caused by not explicitly managing the connections using boost::signals::connection objects.

A: I know this really isn't helpful, but invest in a tool like Purify.  It's really worth it's weight in gold tracking down memory leaks.  It probably would have paid for itself by now.

A: Re: Purify -- it's a great tool, although with some significant limitations (basically it needs to instrument EVERY shared library the application uses, at least on Linux).
If you can't afford Purify and/or have problems with its limitations give valgrind a go (valgrind.org).  It uses a different approach to the problem (i.e., it runs an emulated machine, so you don't need to instrument anything -- otoh, it can be ssssllllloooooowwwwwww)


text:
Q: Error on tensorflow: Shape must be rank 2 but is rank 1 for 'MatMul_25' I'm trying to create a conditional GAN. However, i'm stuck as to why no matter what i do, it appears the same error over and over again.
Here's the code:
image_dim = 784  #28 * 28
Y_dimension = 10
gen_hidd_dim = 256
disc_hidd_dim = 256
z_noise_dim =100 #input noise datapoint

def xavier_init(shape):
  return tf.random_normal(shape = shape, stddev = 1/tf.sqrt(shape[0]/2.0))

weights = {
    'disc_H' : tf.Variable(xavier_init([image_dim + Y_dimension, disc_hidd_dim])),
    'disc_final' : tf.Variable(xavier_init([disc_hidd_dim, 1])),
    'gen_H': tf.Variable([z_noise_dim + Y_dimension, gen_hidd_dim]),
    'gen_final': tf.Variable(xavier_init([gen_hidd_dim, image_dim]))
}

bias = {
    'disc_H': tf.Variable(xavier_init([disc_hidd_dim])),
    'disc_final': tf.Variable(xavier_init([1])),
    'gen_H': tf.Variable(xavier_init([gen_hidd_dim])),
    'gen_final': tf.Variable(xavier_init([image_dim]))
}

Z_input = tf.placeholder(tf.float32, shape= [None, z_noise_dim ], name = 'input_noise')
Y_input = tf.placeholder(tf.float32, shape= [None, Y_dimension], name='Labels')
X_input = tf.placeholder(tf.float32, shape=[None, image_dim], name = 'real_input')

def Discriminator(x,y):
  inputs = tf.concat(axis = 1, values = [x,y])
  hidden_layer = tf.nn.relu(tf.add(tf.matmul(inputs, weights['disc_H']), bias['disc_H']))
  final_layer = tf.add(tf.matmul(hidden_layer, weights['disc_final']), bias['disc_final'])
  disc_output = tf.nn.sigmoid(final_layer)
  return final_layer, disc_output

def Generator(x,y):
  inputs = tf.concat(axis=1, values=[x,y])
  hidden_layer = tf.nn.relu(tf.add(tf.matmul(tf.cast(inputs, tf.float32), tf.cast(weights['gen_H'], tf.float32)), tf.cast(bias['gen_H'],tf.float32)))
  final_layer = tf.add(tf.matmul(hidden_layer, weights['gen_final']), bias['gen_final'])
  gen_output = tf.nn.sigmoid(final_layer)
  return gen_output

output_Gen = Generator(Z_input, Y_input)

Right after executing the Generator i get the following error:
 ValueError: Shape must be rank 2 but is rank 1 for 'MatMul_25' (op: 'MatMul') with input shapes: [?,110], [2].

What to do?

A: I think you just missed one call to xavier_init() when initialising your weights.
You have this:
weights = {
    'disc_H' : tf.Variable(xavier_init([image_dim + Y_dimension, disc_hidd_dim])),
    'disc_final' : tf.Variable(xavier_init([disc_hidd_dim, 1])),
    'gen_H': tf.Variable([z_noise_dim + Y_dimension, gen_hidd_dim]),
    'gen_final': tf.Variable(xavier_init([gen_hidd_dim, image_dim]))
}

but I think you want this:
weights = {
    'disc_H' : tf.Variable(xavier_init([image_dim + Y_dimension, disc_hidd_dim])),
    'disc_final' : tf.Variable(xavier_init([disc_hidd_dim, 1])),
    'gen_H': tf.Variable(xavier_init([z_noise_dim + Y_dimension, gen_hidd_dim])),
    'gen_final': tf.Variable(xavier_init([gen_hidd_dim, image_dim]))
}

The error message was because weights['gen_H'] had shape [2] whereas you expected it to have shape [110, 256]. This meant that the call to tf.matmul() failed because it's impossible to matrix multiply a matrix with shape [m, 110] by a matrix of shape [2]


text:
Q: A polynomial whose integral with higher powers of $x$ vanishes Let $p(x)$ be a polynomial of degree $7$ with real coefficients such that $p(π) = \sqrt{3}$ and $$\int_{-\pi}^{\pi}x^kp(x)dx = 0\ \  \text{for}\  0 \le k \le 6$$.
What are the values of $p(0)$ and $p(−π)$?
Does Riemann-Lebesgue lemma have any role to play here? Or the Weierstrass approximation theorem? Thanks beforehand.

A: Hint Let
$$p(x)=a_7X^7+...+a_1x+a_0$$
Then
$$p(\pi)=\sqrt{3} \\
\int_{-\pi}^{\pi}x^kp(x)dx = 0\ \  \text{for}\  0 \le k \le 6$$
is a system of 8 equations with 8 unknowns. The solution can be made shorter by applying Gram-Smidt to $1,X,X^2,..,X^7$.

A: As already remarked the problem boils down to the inversion of a $8\times 8$ matrix.
A more efficient approach comes from noticing that the rescaled Legendre polynomials $R_n(x)=P_n(x/\pi)$ are orthogonal with respect to the standard inner product of $L^2(-\pi,\pi)$.
In particular a solution is clearly given by $p(x)=\sqrt{3}\,P_7(x/\pi)$, which can be efficiently computed from Rodrigues formula. In such a case $p(0)=0$ and $p(-\pi)=-\sqrt{3}$. It only remains to prove that the solution is unique.


text:
Q: Data structure for range query I was recently asked a coding question on the below problem.
I have some solution to this problem but I am not very sure if those are most efficient.

Problem:
Write a program to track set of text ranges. Start point and end point will be string.
Text range example : [AbA-Ef]
 Aa would fall before this range
 AB would fall inside this range
 etc.

String comparison would be like  'A' < 'a' < 'B' < 'b' ... 'Z' < 'z'
We need to support following operations on this range

*

*Add range - this should merge the ranges if applicable

*Delete range - this deletes range from tracked ranges and recompute the ranges

*Query range - Given a character, function should return whether it is part of any of tracked ranges or not.

Note that tracked ranges can be dis-continuous.

My solutions:
I came up with two approaches.

*

*Store ranges as doubly linked list or

*Store ranges as some sort of balanced tree with leaf node having actual data and they are inter-connected as linked list.

Do you think that this solution are good enough or you can think of any better way of doing this so that those three API gives your best performance ?

A: You are probably looking for an interval tree.
Use the data structure with your custom comparator to indicate "What's on range", and you will be able to do the required operations efficiently.
Note, an interval tree is actually an efficient way to implement your 2nd idea (Store ranges as a some sort of balanced tree)

A: I'm not clear on what the "delete range" operation is supposed to do. Does it;

*

*Delete a previously inserted range, and recompute the merge of the remaining ranges?

*Stop tracking the deleted range, regardless of how many times parts of it have been added.
That doesn't make a huge difference algorithmically; it's just bookkeeping. But it's important to clarify. Also, are the ranges closed or half-open? (Another detail which doesn't affect the algorithm but does affect the implementation).
The basic approach to this problem is to merge the tracked set into a sorted list of disjoint (non-overlapping) ranges; either as a vector or a binary search tree, or basically any structure which supports O(log n) searching.
One approach is to put both endpoints of every disjoint range into the datastructure. To find out if a target value is in a range, find the index of the smallest endpoint greater than the target. If the index is odd the target is in some range; even means it's outside.
Alternatively, index all the disjoint ranges by their start points; find the target by searching for the largest start-point not greater than the target, and then compare the target with the associated end-point.
I usually use the first approach with sorted vectors, which are plausible if (a) space utilization is important and (b) insert and merge are relatively rare. With binary search trees, I go for the second approach. But they differ only in details and constants.
Merging and deleting are not difficult, but there are an annoying number of cases. You start by finding the ranges corresponding to the endpoints of the range to be inserted/deleted (using the standard find operation), remove all the ranges in between the two, and fiddle with the endpoints to correct the partially overlapping ranges. While the find operation is always O(log n), the tree/vector manipulation is o(n) (if the inserted/deleted range is large, anyway).

A: Most languages, including Java and C++, have a some sort of ordered map or ordered set in which you can both look up a value and find the next value after or the first value before a value. You could use this as a building block - If it contains a set of disjoint ranges then it will have a least element of a range followed by a greatest element of a range followed by the least element of a range followed by the greatest element of a range and so on. When you add a range you can check to see if you have preserved this property. If not, you need to merge ranges. Similarly, you want to preserve this when you delete. Then you can query by just looking to see if there is a least element just before your query point and a greatest element just after.
If you want to create your own datastructure from scratch, I would think about some sort of radix trie structure, because this avoids doing lots of repeated string comparisons.

A: I think you would go for B+ tree it's the same which you have mentioned as your second approach.
Here are some properties of B+ tree:

*

*All data is stored leaf nodes.

*Every leaf is at the same level.

*All leaf nodes have links to other leaf nodes.

Here are few applications B+ tree:

*

*It reduces the number of I/O operations required to find an element in the tree.

*Often used in the implementation of database indexes.

*The primary value of a B+ tree is in storing data for efficient retrieval in a block-oriented storage context — in particular, file systems.

*NTFS uses B+ trees for directory indexing.

Basically it helps for range queries look ups, minimizes tree traversing.


text:
Q: Inserting GWT widget into a div element I'm using a GWT library (gwt-openlayers) which allows me to create a map popup containing arbitrary HTML, similar to Google Maps. I need this HTML to contain a GWT Button widget.
I'm creating some HTML elements on-the-fly like this:
Element outerDiv = DOM.createDiv();
outerDiv.getStyle().setOverflow(Overflow.HIDDEN);
outerDiv.getStyle().setWidth(100, Unit.PCT);
outerDiv.appendChild(new HTML(mapPOI.getHtmlDetails()).getElement());
Button popupButton = new Button("View Property");
popupButton.getElement().getStyle().setFloat(com.google.gwt.dom.client.Style.Float.RIGHT);
outerDiv.appendChild(popupButton.getElement());

Then I'm getting the source HTML for these elements by calling
String src = outerDiv.toString();

and inserting this html into my map marker. Now my map marker displays the content ok, including the button. However, the button won't respond to any events! From what I can gather, this is because the buttons onAttach() method is never being called.
Is there a better way to do this?
Thanks,
Jon
~~~~EDIT~~~~
I'm now trying a new way of doing this, which seems to be the accepted method looking at other similar posts.
First I'm creating my div:
String divId = "popup-" + ref;
String innerHTML = "

";

Then I'm adding this to my map popup and displaying it (which adds it to the DOM). After the popup has been displayed, I'm getting the Element as follows and trying to wrap a HTMLPanel around it:
Element element = Document.get().getElementById(divId);
HTMLPanel popupHTML = HTMLPanel.wrap(element);

My div element is successfully retrieved. However, HTMLPanel.wrap(element); doesn't complete. The reason for this is that wrap(..) calls RootPanel.detachOnWindowClose(Widget widget), which includes the following assertions:
assert !widgetsToDetach.contains(widget) : "detachOnUnload() called twice "
    + "for the same widget";
assert !isElementChildOfWidget(widget.getElement()) : "A widget that has "
    + "an existing parent widget may not be added to the detach list";

I put some breakpoints in and it seems that the 2nd assertion is failing!
Does anybody have any idea why this might be the case? Should failing this assertion really result in a complete failure of the method (no return)?

A: Your first approach is good, you just need to register onClick event for your button like this:
DOM.sinkEvents(popupButton.getElement(), Event.ONCLICK);
DOM.setEventListener(popupButton.getElement(), new EventListener() {
    @Override
    public void onBrowserEvent(Event event) {
        //implement the logic after click
    }
});

I have checked this, it works 100%!

A: You might try something like
RootPanel.get("idOfYourMapMarker").add(popupButton);

See RootPanel.get()
Unfortunately, RootPanels are AbsolutePanels which aren't so nice for layout but could work if you just have a simple button to add.  You could also try RootLayoutPanel which will give you a LayoutPanel (also not so nice when you just want things to flow).  You might end up creating a container widget that does the layout for you, and adding that to the RootPanel.

A: SimplePanel is a DIV. Perhaps that can be used instead?

A: You added the element, but you have to keep the hierarchy of the actual GWT Widgets too.
I don't see a clean way to do this, but you could use something like jQuery to grab the button by and ID and add a click handler back to it that would call the original click handler.
private static native void registerEvents(String buttonId, MyClass instance)/*-{
    var $ = $wnd.$;

    //check click
    $('#'+buttonId).live('click', function(e) {
        e.preventDefault();
        instance.@com.package.MyClass::handleButtonClick(Lcom/google/gwt/event/dom/client/ClickEvent;)(null);
    });
}-*/;

Call this registerEvents() either in your onAttach or constructor.

A: I once had a similar problem. You can use the gwt-openlayer's MapWidget as follows:
private MapWidget createMapWidget() {
    final MapOptions defaultMapOptions = new MapOptions();
    defaultMapOptions.setDisplayProjection(DEFAULT_PROJECTION);
    defaultMapOptions.setNumZoomLevels(TOTAL_ZOOM_LEVELS);

    MapWidget mapWidget = new MapWidget(MAP_WIDGET_WIDTH, MAP_WIDGET_HEIGHT, defaultMapOptions);

    map = mapWidget.getMap();

    return mapWidget;
}

And then add it to any panel be it vertical or horizontal.
MapWidget mapWgt = createMapWidget();

VerticalPanel mainPanel = new VerticalPanel();
mainPanel.add(mapWgt);
...
... add whatever you want
...

You can finally add the created Panel(containing the MapWidget and the gwt widget) to the PopupPanel. Also, you should now be able to add handlers to the gwt button.


text:
Q: Semantic UI Dropdown: Change the hidden field values? I am working with semantic-ui dropdown. I am wondering on how to change the values in hidden field based on user selection from the dropdown list ? Related Question may be!.

    <input name="language" type="hidden" value="Alpha-Male">

Gender

Male

Female

A: I checked out the source code of SemanticUI library and I found that the module functions are stored in data() using jQuery.
So, to access dropdown methods for your element you will do:
 $(".ui.selection").data().moduleDropdown

Change value is actually action.activate(text, value) function.
For example, to set Alpha-Female value you will do:
 $(".ui.selection")
   .data()
   .moduleDropdown
   .action
   .activate(undefined, "Alpha-Female")
 ;

JSFIDDLE


text:
Q: $\lim_{R\mapsto\infty}\int_{-R}^{+R}\frac{1}{x+i}\text{d}x=?$ I need help to solve the following integral:
$$\lim_{R\mapsto\infty}\int_{-R}^{+R}\frac{1}{x+i}\text{d}x.$$
None of the explicit formulas (with residues) of my course seems to apply directly. Can somebody help me please? Is the result simply $2\pi i$ by Cauchy's integral formula? Thanks for your help!

A: \begin{align}
\int_{-R}^R\frac 1{x+i}\mathrm dx
&=\int_{-R}^R\frac{x-i}{x^2+1}\mathrm dx\\
&=\frac 12\int_{-R}^R\frac{2x}{x^2+1}\mathrm dx-i\int_{-R}^R\frac 1{x^2+1}\mathrm dx\\
&=\frac 12\left[\log(1+x^2)\right]_{-R}^R-i\left[\arctan(x)\right]_{-R}^R\\
&=-2i\arctan(R)\\
&\xrightarrow{R\to+\infty}-i\pi
\end{align}

A: If you consider that $f(x)=x+i$ then the numerator is equal to $f'(x)$. The indefinite integral is than
\begin{equation}
\int_{}^{}\frac{1}{x+i}\text{d}x= log(x+i) + constant
\end{equation}
The indefinite integral is
\begin{equation}
\int_{-R}^{+R}\frac{1}{x+i}\text{d}x = log(R+i)-log(-R+i)
\end{equation}
for ($ Im(R) \geq -1$ or $Re(R)>0$) and ($Re(R) < 0$ or $Im(R)\leq 1$) and ($Re(R) \neq 0$ or $-1 < Im(R) < 0$ or $0 < Im(R) < 1$).
If tou assume that R is positive you get $-2 i \arctan(R)$. You can then compute the limit which is $-i \pi$.


text:
Q: What is "couldn't communicate with a helper application" error in Macox I'm trying to "zip" (by using the compress option in Finder) a few files that are in my icloud directory, but it is stalling with the error in the title:

After getting this error, Finder freezes and must be restarted by force in Activity Monitor.
What's up?
fyi, I can zip just fine from the command line via zip


text:
Q: Disable hover effect on icons when they are at bottom of page, else enable hover effect I have some icons that are always going to be fixed at the bottom (bottom of the screen, not the end of the page). I want all these icons to be translucent when thy are not at the bottom. They become  opaque when they are at the bottom, and then translucent again when the user scrolls up.
Also, when the icons are translucent and the user hovers over an icon, only that particular icon should become opaque. And there should not be any hover effect when the icons are at the bottom (since the icons are always opaque then).
I made an attempt here but I am unable to disable the hover when icons are at the bottom.
A little off-topic here but is there a way to only detect when the user has scrolled to the bottom of the page. I have commented out an alert in the code. What happens is that the alert is called every time I scroll. I just want the alert to be called once.
Haha. I'm sorry if the question is too twisted. I can rephrase it again if needed. :)
Heres my code below -
HTML -

CSS -
#main {
    border: solid 1px green;
    height: 800px;
    position: relative;
}
#iconTray {
    position: fixed;
    bottom: 0;
}
#iconTray img {
    opacity: 0.4;
}

jQuery -
$('#iconTray img').hover(function () {
    $(this).css('opacity', '1');
}, function () {
    $(this).css('opacity', '0.4');
});

$(window).scroll(function () {
    if ($(window).scrollTop() + $(window).height() == $(document).height()) {
        //bottom of page
        $('#iconTray img').css('opacity', 1);
        // i basically want to disable hover here when the user is
        //at the bottom of the page, but i really dont know how to :P
    } else {
        // this alert is called everytime the user scrolls
        //alert('yo');
        $('#iconTray img').css('opacity', 0.4);
    }
});

A: Store something in data() that you can check on hover :
$('#iconTray img').on('mouseenter mouseleave', function (e) {
    if (!$(this).data('bottom'))
        $(this).css('opacity', e.type=='mouseenter'? 1 : 0.4);
});

$(window).scroll(function () {
    var isBottom = $(window).scrollTop() + $(window).height() == $(document).height();

    $('#iconTray img').css('opacity', isBottom ? 1 : 0.4).data('bottom', isBottom)
});

The "scrolled to bottom" check seems a little too accurate, but if it's work ...


text:
Q: how to scroll the page? when I run the below code, the page doesn't scroll, and doesn't show all of my page container. first I used Ajax but my menu didn't work. then I had to use Iframe tag. but it has a problem too. I try to discover the problem but I didn't succeed. can anybody help me to solve this?

                صفحه اصلی
                پروفایل

                        مدیریت مدیران

                        مدیریت فرم ها

                        مدیریت فرهنگی

                        مدیریت آپلود سنتر

                        مدیریت اخبار

                    Please enable JavaScript to get the full experience.

مديريت کاربران

کاربران فعال

کاربران بلاک

تمام کاربران

کاربران تایید نشده

                    مديريت آپلودسنتر

نمایه جدید

لیست نمایه ها

دسته بندی جدید

لیست دسته ها

آیتم جدید

لیست آیتم ها

<%--

--%>

            Copyright (c)

                     برنامه امروز

A: Please, just remove the css property position: fixed; from maincontainer div.
As you can see at this sample that I made from you sample html code, I just remove that property.
You could also play around with the css property overflow:auto; that controls when to show the scroll, or show/hide the content beyond the limited area of a div.


text:
Q: Mathematical expression with booleans Our tutor has given us the following piece of code in a quiz and I'm at a loss to work out what is going on. In the absence of hearing back from her so far, can anyone throw any light on it?  I haven't seen an expression like this so far in my programming study
var a = 3;
var b = 5;
var c = 7;
var d = 8;
var e;

e = a < b && c++ > d;

document.write(c);

answer is 7
e = a > b && c++ > d;

document.write(c);

answer is 8

A: var a = 3;
var b = 5;
var c = 7;
var d = 8;
var e;

e = a < b && c++ > d;

document.write(c);

the important part is c=7
e = a < b && c++ > d;

That makes c=8 (c++)
The second one
    e = a > b && c++ > d;
because a is not greater than b, Javascript doesnt work out the second part (as regardless of its result, e's result will be false)
So the second one should be 7 and the top should be 8 given the values you have given it
http://jsfiddle.net/ZYVrH/1/ as an example

A: *

*a < b == true, javascript VM computes the next part of boolean expression and increases c variable.

*a > b == false, javascript VM don't computes the next part, cause there is no need to do that when the first argument of logical expression and is false.

A: e = a > b && c++ > d;
condition like this- (exp1 && exp2), exp2 is never calculated when exp1 results in false. So in the expression above, u have a > b && c++ > d. As a is not greater than b so, c is never incremented even if there is ++ operator. So when you print c, its 7.
Whereas, e = a < b && c++ > d; as a is less than b, calculation goes forward to compute c++ > d, as a result c is incremented and its value is 8.


text:
Q: How can I replace CGAffineTransform scale and alpha animations using CABasicAnimations and Auto Layout? As far as I can see, Apple wants us to move away from CGAffineTransform animations and into animations using:
myView.layoutConstraint.constant = someNewValue;

[myView layoutIfNeeded];

for animations that involve a translation of a view.
It also seems we should be now using CABasicAnimation animations for scale and rotation (and sometimes opacity) because it animates the view's layer and not the view and in doing so, plays nicely with auto layout.
I used the following code to apply an opacity and scale animation that worked beautifully:
[UIView animateWithDuration:0.1f animations:^{
//        first animation
self.myMeButton.alpha = 1;
self.myMeButton.transform = CGAffineTransformMakeScale(1.1, 1.1);

} completion:^(BOOL finished) {
    [UIView animateWithDuration:0.2f animations:^{
        //        second animation
        self.myButton.transform = CGAffineTransformMakeScale(1, 1);
    }];
}];

Of course auto layout plays havoc with the scale animation and so I am trying to find an alternative way to do it. So far, I have come up with this:
    [CATransaction begin]; {
    [CATransaction setCompletionBlock:^{
        //            code for when animation completes
        self.pickMeButton.alpha = 1;

        CABasicAnimation *scaleDown = [CABasicAnimation animationWithKeyPath:@"scale"];
        scaleDown.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1)];
        scaleDown.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1)];
        scaleDown.duration = 0.1;

        [self.myButton.layer addAnimation:scaleDown forKey:nil];

    }];
    //  describe animations:
    CABasicAnimation* scaleUp = [CABasicAnimation animationWithKeyPath:@"scale"];
    scaleUp.autoreverses = NO;
    scaleUp.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1)];
    scaleUp.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1)];

    CABasicAnimation *fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeAnim.fromValue=[NSNumber numberWithDouble:0.0];
    fadeAnim.toValue=[NSNumber numberWithDouble:1.0];

    // Customization for all animations:
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.duration = 0.2f;
    group.repeatCount = 1;
    group.autoreverses = NO;
    group.animations = @[scaleUp, fadeAnim];

    // add animations to the view's layer:
    [self.myButton.layer addAnimation:group forKey:@"allMyAnimations"];

} [CATransaction commit];

As you can see the code almost 3 times as long as before and the animation on the device is noticeably less 'smooth' than it was previously.
Is there any way to do this better?
Thanks in advance for your response.
EDIT: This seems to have done the trick in that the animations are smooth, but I still feel like the code for this could be a lot more succinct.
[UIView animateWithDuration:0.2f animations:^{

    self.pickMeButton.alpha = 1;

    CABasicAnimation* scaleUp = [CABasicAnimation animationWithKeyPath:@"transform"];
    scaleUp.duration = 0.2;
    scaleUp.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1)];
    scaleUp.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1)];
    [self.pickMeButton.layer addAnimation:scaleUp forKey:nil];

}completion:^(BOOL finished) {

    CABasicAnimation* scaleDown = [CABasicAnimation animationWithKeyPath:@"transform"];
    scaleDown.duration = 0.1;
    scaleDown.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1)];
    scaleDown.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1)];
    [self.pickMeButton.layer addAnimation:scaleDown forKey:nil];

}];

A: I don't know why you want to do it with CABasicAnimation for scale. You can do it like you mention at the top of your question. Set a new value for the view's width and height constraint constant values and then use [myView layoutIfNeeded] inside animateWithDuration. If the view doesn't have height and width constraints, but has constants to the top and bottom and/or left and right edges of the superview, change those values instead.


text:
Q: Conjecture about product of lengths in a circle In a circle of radius $r>1$, point $P$ is a distance $\sqrt{r^2-1}$ from the centre of the circle. From $P$, draw $n$ line segments to the circle, such that the angles between neighboring line segments are equal. (There is more than one way to do this, because all the line segments can be rotated together; any of these ways will do.)
Here is an example with $r=\sqrt2$ and $n=12$.

Call the lengths of the line segments $l_1, l_2, l_3, ..., l_n$.
I am trying to prove (or disprove) the following conjecture:

$\lim\limits_{n\to\infty}\prod\limits_{k=1}^n l_k=1$

My attempt
If $n$ is even, then consider an arbitrary chord $AB$ through $P$, and diameter $CD$ through $P$. Using the intersecting chords theorem, we have
$$(AP)(PB)=(CP)(PD)=(r-\sqrt{r^2-1})(r+\sqrt{r^2-1})=1$$
$$\therefore\prod\limits_{k=1}^n l_k=1$$
$$\therefore \lim\limits_{n\to\infty}\prod\limits_{k=1}^n l_k=1$$
If $n$ is odd, then we can easily verify that $\prod\limits_{k=1}^n l_k$ does not always equal $1$. For example, let $r=\sqrt2$ and $n=3$, and let one of the line segments go through the centre of the circle. We can easily calculate that $\prod\limits_{k=1}^n l_k=\frac{1}{2}(3+3\sqrt2-\sqrt5-\sqrt{10})\approx 0.922$.
But since the product with even $n$ always equals $1$ (with or without taking the limit), it seems plausible that the product with odd $n$ approaches $1$ as $n\to\infty$. But I have not found a convincing way to prove this.
(This question was inspired by this related question and @person's answer.)

A: We can calculate the line segment lengths as $x_k=l_{k+1}=\sqrt{1+(r^2-1)\cos^2(\frac{2\pi k}{n})}-\sqrt{r^2-1}\cos(\frac{2\pi k}{n})$ where $k=0,1,2,...,n-1$.
For $n=4m+1$, I wrote the product in the form:
$$\prod_{k=0}^{n-1}x_k=x_{\frac{n-1}{4}}\prod_{k=0}^{\frac{n-5}{4}}x_{k}x_{k+\frac{n+1}{2}}\prod_{k=\frac{n+3}{4}}^{\frac{n-1}{2}}x_{k}x_{k+\frac{n-1}{2}}.$$
Notice that $x_{\frac{n-1}{4}}\rightarrow 1$ as $n\rightarrow\infty$.
Now, it is enough to show that
$$x_{k+\frac{n\pm 1}{2}}=x_{k+\frac{n}{2}}+O(\frac{1}{n^2}),\tag{1}$$
since then $\prod_{k=0}^{n-1}x_k=(1+O(\frac{1}{n^2}))^{\frac{n-1}{2}}$ and when $n\rightarrow\infty$, it tends to $1$.
We can show that
$$\cos(\frac{2\pi}{n}(k+\frac{n\pm 1}{2}))=-\cos(\frac{2\pi k}{n})+O(\frac{1}{n^2})$$
and since also $\sqrt{1+\frac{1}{n^2}}=1+O(\frac{1}{n^2})$, $(1)$ holds.
$n=4m+3$ case is similar.


text:
Q: SQL Query on Field Name passed into stored procedure I have a stored procedure in SQL Server which takes 3 parameters and returns a list of Orders like this:
@fieldToFilter VARCHAR(100), --Will only be 1 of these values 'Order Date', 'Delivery Date' or 'Dispatch Date'
@StartDate DATE,
@EndDate DATE

SELECT
    o.Number, o.Customer
FROM
    Order o
WHERE
    (o.OrderDate > @StartDate)
    AND (o.OrderDate < @EndDate)
    AND (SoftDeleted = 0)

The problem with the query above is that I have hard-coded the column OrderDate in the WHERE clause.
What I want to do is use the value in @fieldToFilter to determine what column should be filtered on. e.g.

*

*If @fieldToFilter is Order Date then filter on the OrderDate column

*if @fieldToFilter is Delivery Date then filter on the DeliveryDate column

*if @fieldToFilter is Dispatch Date then filter on the DispatchDate column

What would be the best way to implement something like this?

A: This should get you started. Just replace the other two SELECT statements with the appropriate filters.
IF @fieldToFilter = 'Order Date'
BEGIN
    SELECT o.Number, o.Customer
    FROM Order o
    WHERE (o.OrderDate > @StartDate) and (o.OrderDate < @EndDate) and SoftDeleted=0)
END
ELSE IF @fieldToFilter = 'Delivery Date'
BEGIN
    SELECT '2'
END
ELSE IF @fieldToFilter = 'Dispatch Date'
BEGIN
    SELECT '3'
END

A: I'm not sure if I got the syntax right but something like this should work
SELECT o.Number, o.Customer
    FROM Order o
    WHERE (@StartDate < case when @fieldToFilter = 'Order Date' then o.OrderDate
                            when @fieldToFilter = 'Delivery Date' then o.DeliveryDate
                            when  @fieldToFilter = 'Dispatch Date' then o.DispatchDate
                            else o.OrderDate end)
    and (@EndDate > case when @fieldToFilter = 'Order Date' then o.OrderDate
                            when @fieldToFilter = 'Delivery Date' then o.DeliveryDate
                            when  @fieldToFilter = 'Dispatch Date' then o.DispatchDate
                            else o.OrderDate end)
    and (SoftDeleted=0)

A: There are two possible ways of doing it.
1 - You pass the column name to procedure and build the query dynamically .
CREATE PROCEDURE Get_Data
 @fieldToFilter SYSNAME --Will only be 1 of these values 'Order Date', 'Delivery Date' or 'Dispatch Date'
,@StartDate     DATE
,@EndDate       DATE
AS
BEGIN
  SET NOCOUNT ON;
   Declare @Sql NVARCHAR(MAX);

SET @Sql = N' SELECT o.Number, o.Customer
              FROM [Order] o
              WHERE (o.'+QUOTENAME(@fieldToFilter)+' > @StartDate)
                and (o.'+QUOTENAME(@fieldToFilter)+' < @EndDate)
                and (SoftDeleted=0) '

  Exec sp_executesql @Sql
                    ,N'@StartDate DATE, @EndDate DATE'
                    ,@StartDate
                    ,@EndDate
END

2 - You Add paramaeter for each column , set value to 1 for the filter you want to apply , this also gives you the option of applying multiple filter or none at all.
CREATE PROCEDURE Get_Data
 @FilterOnOrderDate     BIT  = NULL
,@FilterOnDeliveryDate  BIT  = NULL
,@FilterOnDispatchDate  BIT  = NULL
,@StartDate             DATE = NULL
,@EndDate               DATE = NULL
AS
BEGIN
  SET NOCOUNT ON;
   Declare @Sql NVARCHAR(MAX);

SET @Sql = N' SELECT o.Number, o.Customer
              FROM [Order] o
              WHERE (SoftDeleted=0) '
            +  CASE WHEN @FilterOnOrderDate = 1 THEN
              N' AND (o.OrderDate > @StartDate)
                 AND (o.OrderDate < @EndDate) ' ELSE N'' END
            +  CASE WHEN @FilterOnDeliveryDate = 1 THEN
              N' AND (o.DeliveryDate > @StartDate)
                 AND (o.DeliveryDate < @EndDate) ' ELSE N'' END
            +  CASE WHEN @FilterOnDispatchDate = 1 THEN
              N' AND (o.DispatchDate > @StartDate)
                 AND (o.DispatchDate < @EndDate) ' ELSE N'' END

  Exec sp_executesql @Sql
                    ,N'@StartDate DATE, @EndDate DATE'
                    ,@StartDate
                    ,@EndDate
END

A: Please use below will help you out
DECLARE @sql nvarchar(max) = ''

SET @sql = @sql + 'SELECT
    o.Number, o.Customer
FROM
    Order o
WHERE (SoftDeleted = 0) '

if @fieldToFilter = 'Order Date'
begin
    SET @sql = @sql + 'AND  (o.OrderDate > @StartDate) AND (o.OrderDate < @EndDate)'
end
else if @fieldToFilter = 'Delivery Date'
begin
    SET @sql = @sql + 'AND  (o.DeliveryDate > @StartDate) AND (o.DeliveryDate < @EndDate)'
end
else if @fieldToFilter = 'Dispatch Date'
begin
    SET @sql = @sql + 'AND  (o.DispatchDate > @StartDate) AND (o.DispatchDate < @EndDate)'
end

exec (@sql)


text:
Q: Google Sheets: Dynamic Generated IMPORTRANGE formula I have a drop down cell in column A with the names of the tabs of another workbook.
In column B, I will manually input a row #.
I want to use the worksheet name from Column A, and the row information from column B in a formula to look up information.
The formula I am currently using is:
=IMPORTRANGE("heresmyworkbookwebaddress", "Drink!A2")
What I am trying to do is: make it so that Drink is generated from the drop down menu cell, and the 2 from A2 is generated from the information contained in the cell from my B column. The A in A2 should always stay as A.
Is there any way to do this?
Is there an easier way to pull information from another workbook?

A: Have you tried to concatenate the second part of your formula like this:
=IMPORTRANGE("heresmyworkbookwebaddress", *cellcontainingdropdown*&"A"&*B-cell*)
Instead of "cellcontainingdropdown" you enter the cell.
Instead of "B-Cell" you insert the rownumber of column B that you need.
Depending on the format of your cell containing the workbook names you have to use "&!A&" instead of "&A&" if those are not used.


text:
Q: Change Access server connection from command line I have inherited an Access 2007 ADP application that uses a SQL Server 2008 backend. Is it possible to change the server connection used by the application from the command line or by some VBScript? At the moment, when I am releasing the application to a test/UAT/production environment, I have to open the project, change the server connection, and save it again.
I am trying to automate the build process as much as possible, and currently this is one of the last remaining manual tasks.

A: Hmm, my Google-fu is weak. I just found an article on MSDN which gives the VBA script to achieve this. I modified it to run as a VBScript below:
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

If (WScript.Arguments.Count = 0) Then
    WScript.Echo "ERROR - the Access project name must be specified"
    WScript.Quit()
End If

Dim sAccessProject
sAccessProject = fso.GetAbsolutePathName(WScript.Arguments(0))

If (fso.FileExists(sAccessProject) = False) Then
    WScript.Echo "ERROR - the Access project could not be located : " & sAccessProject
    WScript.Quit()
End If

If (WScript.Arguments.Count = 1) Then
    WScript.Echo "ERROR - the SQL Server hostname must be specified"
    WScript.Quit()
End If

Dim sServer
sServer = WScript.Arguments(1)

If (WScript.Arguments.Count = 2) Then
    WScript.Echo "ERROR - the SQL Server database name must be specified"
    WScript.Quit()
End If

Dim sDatabase
sDatabase = WScript.Arguments(2)

Dim sUsername
If (WScript.Arguments.Count = 3) Then
    sUsername = ""
Else
    sUsername = WScript.Arguments(3)
End If

Dim sPassword
If (WScript.Arguments.Count >= 3) Then
    sPassword = ""
Else
    sPassword = WScript.Arguments(4)
End If

ChangeADPConnection sAccessProject, sServer, sDatabase, sUsername, sPassword

Function ChangeADPConnection(strProjectName, strServerName, strDBName, strUN , strPW)

    Dim strConnect

    Dim oApplication
    Set oApplication = CreateObject("Access.Application")
    WScript.Echo "Starting MS Access"
    WScript.Echo "Opening " & strProjectName & " ..."
    oApplication.OpenAccessProject strProjectName
    oApplication.Visible = false

    oApplication.CurrentProject.CloseConnection

    'The Provider, Data Source, and Initial Catalog arguments are required.
    strConnect = "Provider=SQLOLEDB.1" & _
    ";Data Source=" & strServerName & _
    ";Initial Catalog=" & strDBName
    If strUN <> "" Then
        strConnect = strConnect & ";User ID=" & strUN
        If strPW <> "" Then
            strConnect = strConnect & ";Password=" & strPW
        End If
    Else  'Try to use integrated security if no username is supplied.
        strConnect = strConnect & ";Integrated Security=SSPI"
    End If

    WScript.Echo "Setting connection string to " & strConnect

    oApplication.CurrentProject.OpenConnection strConnect
    oApplication.Quit()
    Set oApplication = Nothing

End Function

To run it, just use the following from the commandline:
cscript connect.vbs Project.adp, "ServerName", "DatabaseName", "Username", "Password"