Q:

Error in SharePoint 2013 Search service application - ULS log attach

Error details on crawl log -

The item was aborted because the pipeline did not respond within the
  appropriate time. This item will be retried in the next crawl. (
  CSSFeeder generated callback: The system has not received callback for
  the document;)

tried full crawl but getting same error.

ULS log (1) - CTSSession::Init: m_CSSConnection.Service.CreateSession
  threw exception (System.ServiceModel.CommunicationException), message
  = Exception type is System.ServiceModel.FaultException message = The server was unable to process the request due to an internal error.
  For more information about the error, either turn on
  IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute
  or from the  configuration behavior) on the server in
  order to send the exception information back to the client, or turn on
  tracing as per the Microsoft .NET Framework SDK documentation and
  inspect the server trace logs.;, CSSNode =
  net.tcp://servername/DCA91A/ContentProcessingComponent1/ContentSubmissionServices/content,
  Flow = Microsoft.CrawlerFlow
ULS log (2) - CSSFeeder::Run: session is not recreated or lost
  connection - reconnecting
ULS log (3) - w3wp.exe: All query processing components are in
  'Failed' status.

A:

Please try to reset Index in search service application, and restart all SharePoint search services in "Manage services on server".
After the above, start a full crawl for your content source, compare the result.
Thanks,


Q:

Find if 24 hrs have passed between datetimes

I have the following method:
# last_updated is a datetime() object, representing the last time this program ran
def time_diff(last_updated):
    day_period = last_updated.replace(day=last_updated.day + 1,
                                      hour=1,
                                      minute=0,
                                      second=0,
                                      microsecond=0)
    delta_time = day_period - last_updated
    hours = delta_time.seconds // 3600
    # make sure a period of 24hrs have passed before shuffling
    if hours >= 24:
        print "hello"
    else:
        print "do nothing"

I want to find out if 24 hrs have passed since last_updated, how can I do that in Python?

A:

If last_updated is a naive datetime object representing the time in UTC:
from datetime import datetime, timedelta

if (datetime.utcnow() - last_updated) > timedelta(1):
    # more than 24 hours passed

If last_updated is the local time (naive (timezone-unaware) datetime object):
import time

DAY = 86400
now = time.time()
then = time.mktime(last_updated.timetuple())
if (now - then) > DAY:
    # more than 24 hours passed

If last_updated is an ambiguous time e.g., the time during an end-of-DST transition (once a year in many timezones) then there is a fifty-fifty chance that mktime() returns a wrong result (e.g., off by an hour).
time.mktime() may also fail if C time library doesn't use a historical timezone database on a given platform and the UTC offset for the local timezone was different at last_updated time compared to now. It may apply to more than a third of all timezones in the last year. Linux, OS X, the recent versions of Windows have the tz database (I don't know whether old Windows versions would work for such past dates).
Beware: it might be tempting to write datetime.now() - last_updated (similar to the UTC case) but it is guaranteed to fail on all platforms if the UTC offset was different at last_updated time (it is possible in many timezones). mktime()-based solution can utilize the tz database at least on some platforms and therefore it can handle the changes in the UTC offset for whatever reason there.
For portability, you could install the tz database. It is provided by pytz module in Python. tzlocal can return pytz timezone corresponding to the local timezone:
from datetime import datetime, timedelta
from tzlocal import get_localzone # $ pip install tzlocal

tz = get_localzone() # local timezone
then = tz.normalize(tz.localize(last_updated)) # make it timezone-aware
now = datetime.now(tz) # timezone-aware current time in the local timezone
if (now - then) > timedelta(1):
    # more than 24 hours passed

It works even if the UTC offset was different in the past. But it can't (as well as time.mktime()) fix ambiguous times (tz.localize() picks is_dst=False time by default). tz.normalize() is called to adjust non-existing times e.g., those that correspond to a start-of-DST transition (it should not affect the result).
The above code assumes that last_updated is a naive datetime object (no associated timezone info). If last_updated is an aware datetime object then it is easy to convert it to UTC:
from datetime import datetime, timedelta

then_in_utc = last_updated.replace(tzinfo=None) - last_updated.utcoffset()
if (datetime.utcnow() - then_in_utc) > timedelta(1):
    # more than 24 hours passed

General note: you should understand now why people recommend to work with UTC time and to use local time only for display.


Q:

Complicated SQL query help for JD Edwards E1 (DB2)

Let me preface this with the admission that I am not a database or SQL expert by any stretch. I know basic queries and have done some slightly more involved queries, but this is beyond my ken.
Background
My company uses JD Edwards Enterprise One for their ERP application. The tables below are represented by actual tables in this system. I have paraphrased them below for simplicity. The back-end database is DB2 running on an AS/400 platform.
Table Definitions
Table: Item Ledger (IL)
Columns:
Business Unit
Work Center
Order #
Doc Type
Trans. Date
Qty Completed

Table: W/O Time Transactions (WOT)
Columns:
Business Unit
Work Center
Order #
Hours Type
G/L Date
Hours Worked

Notes:

In reality, these tables have many more columns than what is shown
here.
The query needs to filter item ledger such that document type =
“IC”.
The query need to filter time transactions such that hours type
= “3”.

Sample Data
Note: Apologies for the poor formatting, but there seems to be no way to represent a table nicely in this venue.
Item Ledger (IL)
Business Unit   Work Center Order # Doc Type    Trans. Date Qty Completed
BU-1    WC-1    1   IC  8/7/20  20
BU-1    WC-1    1   IC  8/7/20  40
BU-1    WC-1    2   IC  8/7/20  10
BU-1    WC-2    3   IC  8/7/20  40
BU-1    WC-2    3   IC  8/7/20  10
BU-2    WC-4    6   IC  8/7/20  10
BU-2    WC-5    5   IC  8/7/20  60
BU-1    WC-1    2   IC  8/6/20  50
BU-1    WC-3    4   IC  8/6/20  30
BU-2    WC-5    5   IC  8/5/20  50
BU-2    WC-5    7   IC  8/1/20  20
BU-2    WC-5    8   IC  7/26/20 30
BU-2    WC-5    8   IC  7/25/20 50

W/O Time Transactions (WOT)
Business Unit   Work Center Order # Hours Type  G/L Date    Hours Worked
BU-2    WC-4    6   3   8/8/20  7.4
BU-1    WC-1    1   3   8/7/20  3.92
BU-1    WC-2    3   3   8/7/20  8
BU-1    WC-2    3   3   8/7/20  7
BU-1    WC-3    4   3   8/7/20  6.2
BU-2    WC-4    6   3   8/7/20  1.1
BU-1    WC-1    2   3   8/6/20  1.57
BU-2    WC-5    7   3   8/1/20  3.9
BU-2    WC-5    8   3   7/25/20 11.3

Note: No entries for order # 5 in the time transactions table.
Goals
Goal 1:
We are trying to get hours worked and quantities completed, grouped by business unit (e.g. BU-1) and work center (e.g. WC-1), totaled by the week (future: add other time ranges like by the month).
Important things to note are that there may be multiple completions on a given day in the item ledger, and there may be a much smaller (sometimes just one) number of entries in the time transactions for hours worked that correspond to those completions. There are also often situations where the hours worked entry may not be posted until the next day (this is a 24x7 operation with shifts), in which case the related events (completion and hours logging for a given order) are on separate days.
If we were to meld together the data from these two tables, where order number is the common tie:
Note: I assembled this manually, so there could be errors.
Business Unit   Work Center Order # Date    Hours Worked    Qty Completed
BU-2    WC-4    6   8/8/20  7.4 null
BU-1    WC-1    1   8/7/20  3.92    60
BU-1    WC-1    2   8/7/20  null    10
BU-1    WC-2    3   8/7/20  15  50
BU-1    WC-3    4   8/7/20  6.2 null
BU-2    WC-4    6   8/7/20  1.1 10
BU-2    WC-5    5   8/7/20  null    60
BU-1    WC-1    2   8/6/20  1.57    50
BU-1    WC-3    4   8/6/20  null    30
BU-2    WC-5    5   8/5/20  null    50
BU-2    WC-5    7   8/1/20  3.9 20
BU-2    WC-5    8   7/26/20 null    30
BU-2    WC-5    8   7/25/20 11.3    50

Now, grouped by business unit, work center and totaled by the week:
Week    Business Unit   Work Center Hours Worked    Qty Completed
8/2/20 – 8/8/20
    BU-2    WC-4    8.5 10
    BU-1    WC-1    5.49    120
    BU-1    WC-2    15  50
    BU-1    WC-3    6.2 30
    BU-2    WC-5    0   50
7/26/20 – 8/1/20
    BU-2    WC-5    3.9 50
7/19/20 – 7/25/20
    BU-2    WC-5    11.3    50

I do not know the proper SQL query to achieve this result. I thought that this would require a full outer join, but everything I have tried seems to result in some sort of Cartesian product for a result set, and this is just the first step of combining the data from the two tables together, never mind the final aggregation and grouping.
Any help and suggestions on how to write a query (or maybe multiple queries?) to achieve this type of result would be very much appreciated.
Update (8/14/20):
I have tried to implement a query based on https://stackoverflow.com/users/10418264/mark-barinstein (Mark Barinstein) suggestions. I've analyzed the suggested query and I think I understand it for the most part.
I'm struggling with getting the JD Edwards Julian date into a form that can be used to calculate the week of the year. Here is may latest attempt. Note that the actual table and column names are in use here.
SELECT
  COALESCE(ILG.Week, WOG.Week) AS WEEK,
  COALESCE(ILG.BU, WOG.BU) AS BU,
  COALESCE(ILG.WC, WOG.WC) AS WC,
  COALESCE(WOG.Hours, 0) AS HOURS,
  COALESCE(ILG.Qty, 0) AS QTY
FROM
  (
    SELECT
      F31122.WTMMCU AS BU,
      F31122.WTMCU AS WC,
      WEEK(DATE(CAST(1900 + F31122.WTDGL/1000 AS CHAR(4)) || '-01-01') + (MOD(F31122.WTDGL, 1000) - 1) DAYS) AS Week,
      SUM(F31122.WTHRW) AS Hours
    FROM PROD2DTA.F31122 AS F31122
    WHERE
      (F31122.WTTYR IN ('3')) AND
      (F31122.WTDGL BETWEEN 120200 AND 120201)
    GROUP BY
      F31122.WTMMCU,
      F31122.WTMCU
  ) WOG
FULL JOIN
  (
    SELECT
      F4111.ILMCU AS BU,
      F4111.ILLOCN AS WC,
      WEEK(DATE(CAST(1900 + F4111.ILTRDJ/1000 AS CHAR(4)) || '-01-01') + (MOD(F4111.ILTRDJ, 1000) - 1) DAYS) AS Week,
      SUM(F4111.ILTRQT) AS Qty
    FROM PROD2DTA.F4111 AS F4111
    WHERE
      (F4111.ILDCT IN ('IC')) AND
      (F4111.ILTRDJ BETWEEN 120200 AND 120201)
    GROUP BY
      F4111.ILMCU,
      F4111.ILLOCN
  ) ILG
ON ILG.BU = WOG.BU AND ILG.WC = WOG.WC AND ILG.WEEK = WOG.WEEK
ORDER BY 1 DESC, 2, 3

Is there a way to simplify the logic that converts the JDE Julian date to a week number? I understand what's being done, but wish I could break it out as a function and call it.
I'm still getting errors though:
[SQL0122] Column WTDGL or expression in SELECT list not valid. (JdbcException)

Different question: Can the column "alias" (e.g. BU instead of F4111.ILMCU) be used in the GROUP BY clause? It would make it much more readable.

A:

Try this:
SELECT
  COALESCE(ILG.WEEK, WOG.WEEK) AS WEEK
, COALESCE(ILG.BU, WOG.BU) AS BU
, COALESCE(ILG.WC, WOG.WC) AS WC
, COALESCE(WOG.Hours, 0) AS HOURS
, COALESCE(ILG.Qty, 0) AS QTY
FROM
(
SELECT BU, WC, WEEK(TO_DATE(GL_Date, 'MM/DD/YY')) AS Week, SUM(Hours) AS Hours
FROM WO
GROUP BY BU, WC, WEEK(TO_DATE(GL_Date, 'MM/DD/YY'))
) WOG
FULL JOIN
(
SELECT
  BU, WC
, WEEK(TO_DATE(Trans_Date, 'MM/DD/YY')) AS Week
, SUM(Qty) AS Qty
FROM IL
GROUP BY BU, WC, WEEK(TO_DATE(Trans_Date, 'MM/DD/YY'))
) ILG ON ILG.BU = WOG.BU AND ILG.WC = WOG.WC AND ILG.WEEK = WOG.WEEK
ORDER BY 1 DESC, 2, 3

db<>fiddle link to test it.


Q:

How do I respectfully make use of non-Western accents?

I pretty much exclusively alter my voice to represent characters' speech in-game, both as player and GM.  I have a pretty good handle on most of the numerous Western accents - probably due to the wealth of positive representations for those ethnicities in movies and TV - but whenever I imagine myself using accents outside that region...

I'm looking for a strategy that can help me integrate accents that have traditionally been misrepresented and stereotyped in Western media.  For example, I'd love to use characters with respectable Middle Eastern, South Asian, East Asian, and Black Vernacular accents.

A:

I love the idea of using different accents, and I applaud your apparent desire to use them to enhance your game rather than to shortcut to a stereotype caricature. :).
I'd say the easiest way to use an accent respectfully is not to say deliberately stupid or comedic things in that accent.  To learn how to inflect your speech to sound like you're just speaking in an accent, you might hop on YouTube to find news shows or clips from Tv shows where people are speaking to inform or converse, rather than speaking to make Americans laugh at them.
I hope this helps!

A:

You are comfortable with Western Europe, but uncomfortable with every other accent?
First, find a source of people from whatever region whose accent you want to learn talking (be it people conversing, movies, tv, etc.) in the language you will be gaming in (a Russian accent in English is I'm sure different from a Russian accent in Swahili).
Second, you will be very self-conscious if you do not think the accent is good.  Practice the accent until you are comfortable talking in it to a mirror.  I would pick major types of accents first (say Russian), then worry about the smaller distinctions later (Moskow vs. St. Petersburg).  Concentrate here on specific sounds of the accent, not conversatoin
Third, when you think you sound decent enough to pass, try slipping it into a character.  Talk in that character's accent, concentrating on conversational tone.  A great place is to use the time you are commuting to/from work (in a car, by yourself) to talk about what is going on around you in that accent.
Finally, take the plunge with the "new" accent.  I would start off with accents similar to what you are currently comfortable doing.

A:

Would portraying a black man speaking BBC English be disrespectful?  Would portraying a white women speaking Thai with a Cambodian accent be disrespectful? Would portraying a Scot with a Yorkshire accent be disrespectful? Neither Ethnicity nor localisation has a monopoly on stupidity.
Oh sorry, you meant respectful as in good!
^_~
Look at the phonetics of the language/region they are from.  There are things that will always be hard for speakers to adapt provided they did not learn the language early: "p" and "b" in Arabic, "r" and "l" in Japanese.  There are lots of others. Now, look at the grammar of languages: No future tense in Japanese, no pre-positions in Polish (but declinations), no neutral in French.  Those things will seep into the foreign language. Those are little things but they do add up.  So, using those little idiosyncratic elements will add depth to your speakers' narrative.
(Side track) Vocabulary is a great indicator as well: It is possible to get by with 500 words but however good your accent is, you will never pass as a native speaker. Even after years of studies and speaking, you still encounter words that you have no idea about...
Note that accents are dependent on where and who teaches you.  I know some very white folks who speak French with an Algerian accent.  I know black folks who speak Spanish with a Mexican accent.
As for accents, there are millions of them.  The best way is to listen to them but it can be hard to find the right people to listen to!  Going on holiday is a good indicator or hanging out in a tourist attraction close to home.  Feel free to go and ask people to record them.  Say it is for a book/play/project that you are collecting accents.  Most people should be happy with doing it as long as you do not take too much time out of their lives.
If you live near a university with a philology department, pay them a visit and start asking questions.  You will learn a lot.
Edit: I know the OP meant respectful in a racial offensive way. So, instead of using political correctness (read: New Speak), I opted to try science.


Q:

How do I get to the surface at night?

So far in The Legend of Zelda: Skyward Sword the only time of day I can visit the surface is the day. Can I visit at night, and how?

A:

Sadly, you can't.
Unlike most recent or old Zelda games, Skyward Sword doesn't have a traditional day/night cycle.  The only way to switch between day and night are the beds in Skyloft, the bed in the Lumpy Pumpkin, and the bed in Beedle's Air Shop... and Loftwings don't fly at night.
(Don't be like me and try to dive off the side of the Lumpy Pumpkin or Skyloft at night!)

A:

No you can't get to the surface at night.  To be able to get there, you need to be flying on your Skywing and they cannot be flown at night (by you).  You'll need to do it in the day.


Q:

How can I modify the schema for an Access DB in C#

I have a project here the goal is to merge multiple Access DB's into one SQL Server db. Some of the records in the Access DB are autonumber, and will not be unique across all the DB's.
We are currently working on modifying those autonumber fields programmaticaly to being number fields. The adjusting and allowing access to cascade those changes through before appending all those tables through to SQL server.
Im aware of the getSchema() for access, but can we modify the schema to remove an autonumber from a field?
Failing that, does anyone have any brilliant ideas on how to accomplish our task? Or done anything similar?
Regards

A:

You can use DDL:
ALTER TABLE Table1 ALTER COLUMN id long

EDIT re COMMENT
You need to Drop a relationship before you change the field type, but a primary index is fine:
ALTER TABLE Table2 DROP CONSTRAINT Table1Table2

The constraint will probably be called something on these lines, but you can use ADOSchemas to get the names of the constraints (relationships).


Q:

C# Efficiently replacing -Infinity values in a dictionary

I have code that uses LINQ converts an dictionary of string, ints to string, doubles. The following code works fine:
public static void Main(string[] args)
{
    Dictionary<string, int[]> ret = new Dictionary<string, int[]>();

    int[] a = {1,2,0,4,5};
    int[] b = { 0, 6, 9, 0, 12 };
    int[] c = {2,0,3,5,0};
    ret.Add("Al", a);
    ret.Add("Adam", b);
    ret.Add("Axel", c);

    Dictionary<string, double[]> scores = ret.ToDictionary(r=> r.Key,
                         r => r.Value.Select((v, index)=>
                         3 * Math.Log10((double)v / 10)
                         ).ToArray());

    foreach (var item in scores)
    {
        for (int i = 0; i < item.Value.Length; i ++)
        {
            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value[i]);
        }

    }

This code outputs:
Key = Al, Value = -3
Key = Al, Value = -2.09691001300806
Key = Al, Value = -Infinity
Key = Al, Value = -1.19382002601611
Key = Al, Value = -0.903089986991944
Key = Adam, Value = -Infinity
Key = Adam, Value = -0.665546248849069
Key = Adam, Value = -0.137272471682025
Key = Adam, Value = -Infinity
Key = Adam, Value = 0.237543738142874
Key = Axel, Value = -2.09691001300806
Key = Axel, Value = -Infinity
Key = Axel, Value = -1.56863623584101
Key = Axel, Value = -0.903089986991944
Key = Axel, Value = -Infinity

What is the most efficient way to change -Infinity to 0? Would putting a continue or if statement function in the loop work? I know I can just use the replace function and loop through the dictionary, which is not very efficient.

A:

Since you have control of the values being put into the dictionary, I'd change
(v, index) => 3 * Math.Log10((double)v / 10)

to
(v, index) => v == 0 ? 0 : 3 * Math.Log10((double)v / 10)

Otherwise, you can just use the ternary operator:
Console.WriteLine("Key = {0}, Value = {1}", item.Key,
    item.Value[i] == Double.NegativeInfinity ? 0 : item.Value[i]);


Q:

Is there a way to execute php code in a sandbox from within php

I want to execute a php-script from php that will use different constants and different versions of classes that are already defined.
Is there a sandbox php_module where i could just:
sandbox('script.php'); // run in a new php environment

instead of
include('script.php'); // run in the same environment

Or is proc_open() the only option?
PS: The script isn't accessible through the web, so fopen('http://host/script.php') is not an option.

A:

There is runkit, but you may find it simpler to just call the script over the command line (Use shell_exec), if you don't need any interaction between the master and child processes.

A:

The is a class on GitHub that may help, early stages but looks promising.
https://github.com/fregster/PHPSandbox


Q:

How to keep all columns when concatenating rows with dplyr::summarise?

I want to aggregate one column (C) in a data frame according to one grouping variable A, and separate the individual values by a comma while keeping all the other column B. However, B can either have a character (which is always the same for all the rows) or be empty. In this case, I would like to keep the character whenever it is present on one row.
Here is a simplified example:
data <- data.frame(A = c(rep(111, 3), rep(222, 3)), B = c("", "", "", "a" , "", "a"), C = c(5:10))
data

Based on this question Collapse / concatenate / aggregate a column to a single comma separated string within each group, I have the following code:
library(dplyr)
data %>%
  group_by(A) %>%
  summarise(test = toString(C)) %>%
  ungroup()

Here it is what I would like to obtain:
    A B  C
1 111    5,6,7
2 222 a  8,9,10

A:

You could write one function to return unique values
library(dplyr)

get_common_vars <- function(x) {
   if(n_distinct(x) > 1) unique(x[x !='']) else unique(x)
}

and then use it on all columns that you are interested :
data %>%
  group_by(A) %>%
  mutate(C = toString(C)) %>%
  summarise_at(vars(B:C), get_common_vars)
  #                  ^------ Include all columns here

# A tibble: 2 x 3
#     A  B     C
#  <dbl> <fct> <chr>
#1   111 ""    5, 6, 7
#2   222 a     8, 9, 10


Q:

How can I find the inverse Fourier transform of $e^{x^2}$ and similar functions?

I'm honestly clueless; I tried writing it as ${\lmoustache}_{-\infty}^{+\infty} {e^{x^2}} {e^{ix}} {dx}$ , but I don't know where to go from there.

A:

I think this integral does not exist as your function does not stay bounded for $x\to \infty$.
Maybe your are missing a minus sign? If it was a minus you could do the follwing. You are also missing a parameter if this is a fourrier inverse transform (something like time, I will also leave it out as it does not change the method).
But $-x^2+2\frac{i}{2}x=-x^2+2\frac{i}{2}x-\frac{i^2}{4}+\frac{i^2}{4}=-(x-\frac{i}{2})^2-\frac{1}{4}$
Introduce substitution $u=x-\frac{i}{2}$ and $du = dx$. Note also the changed integration bounds. Try to evaluate the integral using contour integration.
$$\int_{-\infty-i/2}^{\infty-i/2}e^{-u^2}e^{-1/4}du$$
This integral should be similar due, to Cauchy's Integral Theorem, to (use a rectangular contour along the real axis that goes down -i/2 and traces along an parallel to the real axis and gets back to the real axis):
$$\int_{-\infty}^{\infty}e^{-u^2}e^{-1/4}du$$
Note that I am not sure if it is exactly the previous integral but it should be something similar.
This can be solved by multipling it by itself and using polar coordinates.


Q:

Javascript only shows values and not XML information

I'm makeing a manufacturing website about what types of cords are used in each country. I need it to show the information called from the XML page once the country has been selected on the dropdown menu but all I can get it to show is the value of the list item. here is my java
 <!DOCTYPE html>

<link href="style.css" rel="stylesheet" />

<form>
<select id="X"  onchange="myFunction ();">
 <option value="X">Please Choose a Country</option>

</select>

A:

Okay, here is what I got.
http://jsfiddle.net/xDaevax/eNwXn/
Basically, I re-created your form, and used JQuery for several purposes:

First, I create two custom JQuery events.  The first one is called when a country is selected, the second one is called when your ajax function returns with data and populates your HTML with the data.
Next, I add an event listener to the select list on change that triggers the event.  This is mostly done to keep the code DRY (http://en.wikipedia.org/wiki/Dont_repeat_yourself)
Then I create a javascript function that serves as a wrapper for the ajax call.  In this code I had to put sample data because I didn't have your actual XML file and jsfiddle does not actually allow external ajax posts.  When you try this locally, uncomment the code below (which is in the fiddle) and comment out my test code.

The basic idea is: When the user selects a country, load the data.  You can filter the data using the selected country and then display it on the page.
//Uncomment these lines in your code
$.ajax({
    url: "cords_data.xml"
        , cache: false
        , type: "get"
        , data: null
}).done(function (xmlData) {
    if (xmlData != undefined && xmlData != null) { // make sure we got data back
        $(document).trigger("display-cord-data", xmlData);
    } else {
        console.log("No data returned.");
        alert("An error occurred while loading data.");
    } // end if/else
}).fail(function (data) {
    console.log(data);
        alert("BOOOM");
});

As a starting point on how to parse XML using JQuery, see this link:
http://api.jquery.com/jquery.parsexml/
Also, here are some ways to target nodes in your XML document
http://api.jquery.com/category/selectors/attribute-selectors/


Q:

MySQL Query to a Zend DB Select

I have a MySQL standard query that I need to convert into a Zend_Db_Select but I can't get it to work.
I get this error:
Select query cannot join with another table

Here's the query:
// THE COUNTER
$subselect = $this->table->select()->from(
        array('x' => 'blog_comments'),
        array('x.post_id', new Zend_Db_Expr('count(*) as comments')))
    ->group('post_id');
// THE TOTAL SELECT
$select->from(array('p' => 'blog_posts'), array('p.*'))
       ->setIntegrityCheck(false)
       ->joinLeft(array(
           'x' => $subselect,
           'x.post_id = p.id',
           array()
           )
       );

If someone can convert this, it would be great because I need that in select() mode because I use Zend_Pagination.
For those who want the full PHP function: Pastebin and the stack traces: Pastebin.

A:

You may need: setIntegrityCheck(false) - review: http://framework.zend.com/manual/1.12/en/zend.db.select.html for more information
$select = $this->select()
->from(params)
->setIntegrityCheck(false)
->joinLeft(params)
->where(params);


Q:

HTML/Angular2 date picker disable to select a future date

I have an issue related to html/angular 2 date picker.
So i have such input tag:
<input #createdAt ngModel type="datetime-local" id="createdAt" name="date" class="form-control" required>

but i don't want allow to a user select future date, so only today and past date is allowed.
How can i achieve such behaviour with angular 2?

A:

One of the option is to leverage the max attribute of <input type="datetime-local such as: <input type="date" name="bday" max="1979-12-31">
An alternative is to use an existing Angular2 component, such as the date picker from  Bootstrap Angular 2. The component is highly customizable and your goal can be achieved by setting the maxDate input.


Q:

check if vector b = [3 2] is in the column space of A

so I'm trying to prove by setting up a augmented matrix with vector b [3 2] is in col(A). I am trying to find if vector b spans col(A).
$$A =\begin{bmatrix} 1 & 0 & -1 \\1 & 1& 1 \end{bmatrix}$$
so the augmented matrix is:
$$\left[\begin{array}{rrr|r} 1 & 0 & -1 & 3\\ 1 & 1 & 1 & 2 \end{array}\right]$$
so what I start by is row reducing and get:
$$\left[\begin{array}{rrr|r} 1 & 0 & -1 & 3\\ 0 & 1 & 2 & -1 \end{array}\right]$$
but from here it looks like I can't get linear independence, but my book says this is in col(A). Can someone show me where I am going wrong?

A:

I'm not sure what linear independence has to do with anything here. You've shown that every row has a pivot, so $\text{Col}(A)$ spans all of $\mathbb R^2$, including $b$. Indeed, we can explicitly express $b$ as a linear combination of the original columns of $A$ by inspection:
$$
\begin{bmatrix}
3 \\ 2
\end{bmatrix}
=
3\begin{bmatrix}
1 \\ 1
\end{bmatrix}
+ (-1)
\begin{bmatrix}
0 \\ 1
\end{bmatrix}
+ 0
\begin{bmatrix}
-1 \\ 1
\end{bmatrix}
$$


Q:

If $K$ is compact then $K\cap Y$ is compact in $Y$ too for any closed $Y\subseteq X$

Definition
A subspace $K$ of a topological space $X$ is compact if every its open cover has a finite subcover.
Lemma
If $X$ is compact then any its closed subspace is compact too.
Proof. Omitted.
Theorem
If $K$ is compact and closed then $K\cap Y$ is compact in $Y$ too for any closed $Y\subseteq X$
Proof. If $K$ is compact and $Y$ is closed then $K\cap Y$ is closed in $K$ so that by previous lemma it is compact too in $K$. Now if $\mathcal{T}$ is the topology of $X$ then we observe that any $A\in\mathcal{T}$ is such that $$(A\cap K)\cap(K\cap Y)=A\cap(K\cap Y)=(A\cap Y)\cap(K\cap Y)$$ so that we conclude $\mathcal{T}|_K|_{K\cap Y}=\mathcal{T}|_{K\cap Y}=\mathcal{T}|_Y|_{K\cap Y}$ and so the theorem holds.
So I ask if the proof of the last theorem is correct and if it is not correct I ask how to prove it: perhaps could it be that the statement is false?

A:

Let $\Omega$ be a topological space and $A$ a subspace of $\Omega$. Then if $F$ is a subset of $A$, $F$ is compact in $A$ iff $F$ is compact in $\Omega$.
Now using the lemma $K\cap Y$ is a compact subset of $K$. The iff condition implies that $K\cap Y$ is compact in $X$ and again the iff condition implies that $K\cap Y$ is compact in $Y$


Q:

As an addendum you'd use my prefix, Almost in your hand you can find my suffix,

OK, let me try my hand at this:

As an addendum you'd use my prefix
  Almost in your hand you can find my suffix
  My infix is even more thin than a hair
  And some might find me on a wing and a prayer

What am I?

A:

The answer is

 PSALM.

As an addendum you'd use my prefix

 PS at the end of a letter.

Almost in your hand you can find my suffix

 ALM is almost like the PALM of your hand.

My infix is even more thin than a hair

 The infix is actually nothing, because there are no letters between PS and ALM in the word.

And some might find me on a wing and a prayer

 PSALM.


Q:

DomDocument - Don't get a closing tag?

This is the first time I am dealing with DomDocument and PHP. I am almost done but somehow the XML is missing a closing tag. I am missing the closing tag for "Sport" in the XML below.
<?xml version="1.0" encoding="UTF-8"?>
<Persons PageCount="1" PageIndex="1" ApplicationId="secret" xmlSchemaVersion="1.0" GenerationDate="2018-11-17T23:10:31" IsIncremental="true">
  <Person CreateDate="2008-08-29T08:39:44" LMDate="2012-08-29T08:39:44" OptionType="Update">
    <PersonId>82</PersonId>
    <PersonalNumber>19660903-xxxx</PersonalNumber>
    <FirstName>Joakim</FirstName>
    <LastName>Krassman</LastName>
    <BirthDate>1966-09-03</BirthDate>
    <Gender>male</Gender>
    <Organisations>
      <Organisation OptionType="Update">
        <OrgID>31215</OrgID>
        <OrganisationRF_NR>45264</OrganisationRF_NR>
        <OrganisationNumber>556717xxxx</OrganisationNumber>
        <Sports>
          <Sport OptionType="Update"/>
          <SportID>43</SportID>
          <IsActive LMDate="2012-08-29T08:39:44">true</IsActive>
        </Sports>
      </Organisation>
    </Organisations>
  </Person>
</Persons>

And this is my PHP code:
<?php
$generate_date = date('Y-m-d\TH:i:s');

$doc = new DOMDocument('1.0', 'UTF-8');
$doc->formatOutput = true;

/* PERSONS */
$r = $doc->createElement( "Persons" );
$attr = $doc->createAttribute('PageCount');
$attrVal = $doc->createTextNode(1);
$attr->appendChild($attrVal);
$r->appendChild($attr);

$attr = $doc->createAttribute('PageIndex');
$attrVal = $doc->createTextNode(1);
$attr->appendChild($attrVal);
$r->appendChild($attr);

$attr = $doc->createAttribute('ApplicationId');
$attrVal = $doc->createTextNode("secret");
$attr->appendChild($attrVal);
$r->appendChild($attr);

$attr = $doc->createAttribute('xmlSchemaVersion');
$attrVal = $doc->createTextNode("1.0");
$attr->appendChild($attrVal);
$r->appendChild($attr);

$attr = $doc->createAttribute('GenerationDate');
$attrVal = $doc->createTextNode($generate_date);
$attr->appendChild($attrVal);
$r->appendChild($attr);

$attr = $doc->createAttribute('IsIncremental');
$attrVal = $doc->createTextNode('true');
$attr->appendChild($attrVal);
$r->appendChild($attr);

$doc->appendChild( $r );

/* PERSON */

$b = $doc->createElement( "Person" );
$attr = $doc->createAttribute('CreateDate');
$attrVal = $doc->createTextNode('2008-08-29T08:39:44');
$attr->appendChild($attrVal);
$b->appendChild($attr);

$attr = $doc->createAttribute('LMDate');
$attrVal = $doc->createTextNode('2012-08-29T08:39:44');
$attr->appendChild($attrVal);
$b->appendChild($attr);

$attr = $doc->createAttribute('OptionType');
$attrVal = $doc->createTextNode('Update');
$attr->appendChild($attrVal);
$b->appendChild($attr);

/* START PERSON SINGULAR */

$person = $doc->createElement( "PersonId" );
$person->appendChild(
$doc->createTextNode( 82 )
);
$b->appendChild( $person );

$person = $doc->createElement( "PersonalNumber" );
$person->appendChild(
$doc->createTextNode( '19660903-xxxx' )
);
$b->appendChild( $person );

$person = $doc->createElement( "FirstName" );
$person->appendChild(
$doc->createTextNode( 'Joakim' )
);
$b->appendChild( $person );

$person = $doc->createElement( "LastName" );
$person->appendChild(
$doc->createTextNode( 'Krassman' )
);
$b->appendChild( $person );

$person = $doc->createElement( "BirthDate" );
$person->appendChild(
$doc->createTextNode( '1966-09-03' )
);
$b->appendChild( $person );

$person = $doc->createElement( "Gender" );
$person->appendChild(
$doc->createTextNode( 'male' )
);
$b->appendChild( $person );

    /* SKJUT IN ORGINISATION */
     $org = $doc->createElement( "Organisations" );
     $b->appendChild($org);
     $subOrg = $doc->createElement( "Organisation" );

     $subOrg->setAttribute("OptionType", "Update");
     $org->appendChild( $subOrg );

     $orgDet = $doc->createElement( "OrgID" );
     $orgDet->appendChild(
     $doc->createTextNode( 31215 ));
     $subOrg->appendChild( $orgDet );

     $orgDet = $doc->createElement( "OrganisationRF_NR" );
     $orgDet->appendChild(
     $doc->createTextNode( 45264 ));
     $subOrg->appendChild( $orgDet );

     $orgDet = $doc->createElement( "OrganisationNumber" );
     $orgDet->appendChild(
     $doc->createTextNode( 556717xxxx ));
     $subOrg->appendChild( $orgDet );

     /* SPORTS */

     $sport = $doc->createElement( "Sports" );
     $subOrg->appendChild($sport);
     $subOrg = $doc->createElement( "Sport" );
     $subOrg->setAttribute("OptionType", "Update");
     $sport->appendChild( $subOrg );

     $sportDet = $doc->createElement( "SportID" );
     $sportDet->appendChild(
     $doc->createTextNode( 43 ));
     $sport->appendChild( $sportDet );

     $sportDet = $doc->createElement( "IsActive" );
     $sportDet->setAttribute("LMDate", "2012-08-29T08:39:44");

     $sportDet->appendChild(
     $doc->createTextNode( 'true' ));

     $sport->appendChild( $sportDet );

    /* SLUT ORGINISATION */

/* SLUT PERSON SINGULAR*/
$r->appendChild( $b );

echo ($doc->saveXML());
?>

I am sure that I am doing some fundamental wrong, can anyone guide me to the solution?

A:

The tag is an empty tag so is closed at the end of the tag (/>) -
<Sport OptionType="Update"/>

If you need to close tag, then change the save with LIBXML_NOEMPTYTAG...
echo ($doc->saveXML(null, LIBXML_NOEMPTYTAG));

Which will give you...
<Sport OptionType="Update"></Sport>

If you need the structure to be ...
  <Sport OptionType="Update">
    <SportID>43</SportID>
    <IsActive LMDate="2012-08-29T08:39:44">true</IsActive>
  </Sport>

Then the code...
 $subOrg = $doc->createElement( "Sport" );
 $subOrg->setAttribute("OptionType", "Update");
 $sport->appendChild( $subOrg );

 $sportDet = $doc->createElement( "SportID" );
 $sportDet->appendChild(
 $doc->createTextNode( 43 ));
 $sport->appendChild( $sportDet );

 $sportDet = $doc->createElement( "IsActive" );
 $sportDet->setAttribute("LMDate", "2012-08-29T08:39:44");

 $sportDet->appendChild(
 $doc->createTextNode( 'true' ));

 $sport->appendChild( $sportDet );

You need to change the two lines with
$sport->appendChild( $sportDet );

to add them to $subOrg instead...
$subOrg->appendChild( $sportDet );


Q:

Rails not connecting on port 3000

I'm not able to connect to localhost:3000 (when I try, it directed me to Google SERP - server log shows the following) but localhost:3001
=> Booting Puma
=> Rails 5.2.1 application starting in development
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.0 (ruby 2.5.1-p57), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop

when sudo nano /etc/hosts, it showed 127.0.0.1 localhost
127.0.0.1:3000 works though
Where did I go wrong?
This happened for the first time for me.
When I tried
    wget http://0.0.0.0:3000
    --2018-09-24 01:46:21--  http://0.0.0.0:3000/
    Connecting to 0.0.0.0:3000... failed: Connection refused.

A:

Could you try start rails server with:
$ bundle exec rails server -b 0

Then go to http://localhost:3000


Q:

mvc show no picture if can't find file

I have a mvc project. there is a column like this

But if no jpg file exists, I wanna show another general picture. How could I do that? Thanks

A:

I figure it could use it like this
@if (System.IO.File.Exists(Server.MapPath("~/Content/photos/" + @item.ID + ".jpg")))
                {

                }
                else
                {

                }


Q:

Deep copying PhraseMatcher object in spacy is not working

I want to run some multiprocessing module to run some phrase matching on documents in parallel. To do this I thought of creating phrase matching object in one process and then share among multiple processes by creating copy of the PhraseMatcher object. The code seems to be failing with out giving anykind of error. To make things easier I have tried this to demonstrate what I am trying to achieve
import copy
import spacy
from spacy.matcher import PhraseMatcher

nlp = spacy.load('en')
color_patterns = [nlp(text) for text in ('red', 'green', 'yellow')]
product_patterns = [nlp(text) for text in ('boots', 'coats', 'bag')]
material_patterns = [nlp(text) for text in ('silk', 'yellow fabric')]

matcher = PhraseMatcher(nlp.vocab)
matcher.add('COLOR', None, *color_patterns)
matcher.add('PRODUCT', None, *product_patterns)
matcher.add('MATERIAL', None, *material_patterns)

matcher2 = copy.deepcopy(matcher)

doc = nlp("yellow fabric")
matches = matcher2(doc)
for match_id, start, end in matches:
    rule_id = nlp.vocab.strings[match_id]  # get the unicode ID, i.e. 'COLOR'
    span = doc[start : end]  # get the matched slice of the doc
    print(rule_id, span.text)

With the matcher2 object it not giving any output, but with matcher object I am able to get the results.
COLOR yellow
MATERIAL yellow fabric

I am stuck at this for couple of days. Any help will be deeply appreciated.
Thank you.

A:

The root of your problem is that PhraseMatcher is a Cython class, defined and implemented in the file matcher.pyx and Cython does not work properly with deepcopy.
Referenced from the accepted answer to this StackOverflow question:

Cython doesn't like deepcopy on Classes which have function/method referenced variables. Those variable copies will fail.

However, there are alternatives to that. If you want to run PhraseMatcher to multiple documents in parallel you can use multithreading with the pipe method of PhraseMatcher.
A possible workaround for your problem:
import copy
import spacy
from spacy.matcher import PhraseMatcher

nlp = spacy.load('en_core_web_sm')
color_patterns = [nlp(text) for text in ('red', 'green', 'yellow')]
product_patterns = [nlp(text) for text in ('boots', 'coats', 'bag')]
material_patterns = [nlp(text) for text in ('silk', 'yellow fabric')]

matcher = PhraseMatcher(nlp.vocab)
matcher.add('COLOR', None, *color_patterns)
matcher.add('PRODUCT', None, *product_patterns)
matcher.add('MATERIAL', None, *material_patterns)

doc1 = nlp('yellow fabric')
doc2 = nlp('red lipstick and big black boots')

for doc in matcher.pipe([doc1, doc2], n_threads=4):
    matches = matcher(doc)
    for match_id, start, end in matches:
        rule_id = nlp.vocab.strings[match_id]
        span = doc[start : end]
        print(rule_id, span.text)

Hope it helps!


Q:

weighted integral of a continuous function

I am not sure about my answer and wanted to  doublecheck  my steps.
Suppose $ f \colon \mathbb{R} \to \mathbb{R} $ is a  continuous and bounded function. Prove that
$\lim_{y \to 0^+} \frac{y}{\pi}\int_{-\infty}^{\infty} \frac{f(x)}{x^2+y^2}\,dx =f(0)$
This is my attempt: Setting $t=arctg(\frac{x}{y})$ , the integral becomes:
$\lim_{y \to 0^+} \pi \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} f(y\tan(t)) \,dt$.
Since $f$ is bounded  I can apply the Lebesgue dominated convergence theorem to bring the limit under the sign of integral and then,since f is continuous at zero, I bring the limit inside the argument of the f, which yelds to the desired result.

A:

Let $ y\in\mathbb{R}_{+} $, we have :
\begin{aligned}\frac{y}{\pi}\int_{-\infty}^{+\infty}{\frac{f\left(x\right)}{x^{2}+y^{2}}\,\mathrm{d}x}&=\frac{1}{y\pi}\int_{-\infty}^{+\infty}{\frac{f\left(x\right)}{1+\left(\frac{x}{y}\right)^{2}}\,\mathrm{d}x}\\ &=\frac{1}{\pi}\int_{-\infty}^{+\infty}{\frac{f\left(xy\right)}{1+x^{2}}\,\mathrm{d}x}\end{aligned}
Since $ \frac{1}{\pi}\int_{-\infty}^{+\infty}{\frac{\mathrm{d}x}{1+x^{2}}}=1 $, and since $ f $ is continuous, given an $ \varepsilon>0 $, there exists some $ \eta>0 $ such that : $$ \left(\forall x\in\mathcal{B}\left(0,\eta\right)\right),\ \left|f\left(x\right)-f\left(0\right)\right|<\varepsilon $$ Thus : \begin{aligned} \small\left|\frac{1}{\pi}\int_{-\infty}^{+\infty}{\frac{f\left(xy\right)}{1+x^{2}}\,\mathrm{d}x}-f\left(0\right)\right|&\small=\left|\frac{1}{\pi}\int_{-\infty}^{+\infty}{\frac{f\left(xy\right)-f\left(0\right)}{1+x^{2}}\,\mathrm{d}x}\right|\\ &\small\leq\frac{1}{\pi}\int_{-\infty}^{+\infty}{\frac{\left|f\left(xy\right)-f\left(0\right)\right|}{1+x^{2}}\,\mathrm{d}x}\\ &\small\leq\frac{1}{\pi}\int_{-\infty}^{-\frac{\eta}{y}}{\frac{\left|f\left(xy\right)-f\left(0\right)\right|}{1+x^{2}}\,\mathrm{d}x}+\frac{1}{\pi}\int_{-\frac{\eta}{y}}^{\frac{\eta}{y}}{\frac{\left|f\left(xy\right)-f\left(0\right)\right|}{1+x^{2}}\,\mathrm{d}x}+\frac{1}{\pi}\int_{\frac{\eta}{y}}^{+\infty}{\frac{\left|f\left(xy\right)-f\left(0\right)\right|}{1+x^{2}}\,\mathrm{d}x}\\ &\small\leq\frac{1}{\pi}\int_{-\infty}^{-\frac{\eta}{y}}{\frac{\left|f\left(xy\right)-f\left(0\right)\right|}{1+x^{2}}\,\mathrm{d}x}+\frac{\varepsilon}{\pi}\int_{-\frac{\eta}{y}}^{\frac{\eta}{y}}{\frac{\mathrm{d}x}{1+x^{2}}}+\frac{1}{\pi}\int_{\frac{\eta}{y}}^{+\infty}{\frac{\left|f\left(xy\right)-f\left(0\right)\right|}{1+x^{2}}\,\mathrm{d}x} \end{aligned}
For the $ y $ that we fixed in the begining, let's denote $ g_{y}:x\mapsto\frac{\left|f\left(xy\right)-f\left(0\right)\right|}{1+x^{2}} \cdot $
For $ \left(a,b\right)\in\left(\mathbb{R}_{+},\mathbb{R}_{-}\right) $, $ \int_{a}^{+\infty}{g_{y}\left(x\right)\mathrm{d}x} $, and $ \int_{-\infty}^{b}{g_{y}\left(x\right)\mathrm{d}x} $ are respectively the remainders of $ \int_{0}^{+\infty}{f_{y}\left(x\right)\mathrm{d}x} $, and $ \int_{-\infty}^{0}{f_{y}\left(x\right)\mathrm{d}x} $ which both converge. Thus, we have : $$ \lim_{a\to +\infty}{\int_{a}^{+\infty}{g_{y}\left(x\right)\mathrm{d}x}}=0 \ \ \ \ \ \textrm{and} \ \ \ \ \ \lim_{b\to -\infty}{\int_{-\infty}^{b}{g_{y}\left(x\right)\mathrm{d}x}}=0 $$
Thus, there exists $ \eta_{1},\eta_{2}\in\mathbb{R}_{+}^{*}=\left(0,+\infty\right) $, such that : $$\small \left(\forall x\in\mathcal{B}\left(0,\eta_{1}\right)\right),\ \int_{-\infty}^{-\frac{\eta}{y}}{\frac{\left|f\left(xy\right)-f\left(0\right)\right|}{1+x^{2}}\,\mathrm{d}x}<\varepsilon \ \ \ \ \ \ \ \textrm{and} \ \ \ \ \ \ \ \left(\forall x\in\mathcal{B}\left(0,\eta_{2}\right)\right),\ \int_{\frac{\eta}{y}}^{+\infty}{\frac{\left|f\left(xy\right)-f\left(0\right)\right|}{1+x^{2}}\,\mathrm{d}x}<\varepsilon $$
Because they both approache $ 0 $ as $ y $ approaches $ 0^{+} \cdot $ We get that $ \left(\forall x\in\mathcal{B}\left(0,\min\left(\eta,\eta_{1},\eta_{2}\right)\right)\right) $ : $$ \left|\frac{1}{\pi}\int_{-\infty}^{+\infty}{\frac{f\left(xy\right)}{1+x^{2}}\,\mathrm{d}x}-f\left(0\right)\right|\leq\frac{2\varepsilon}{\pi}\left(1+\arctan{\left(\frac{\eta}{y}\right)}\right)<\left(\frac{2+\pi}{\pi}\right)\varepsilon $$
Hence : $$ \lim_{y\to 0^{+}}{\frac{y}{\pi}\int_{-\infty}^{+\infty}{\frac{f\left(x\right)}{x^{2}+y^{2}}\,\mathrm{d}x}}=\lim_{y\to 0^{+}}{\frac{1}{\pi}\int_{-\infty}^{+\infty}{\frac{f\left(xy\right)}{1+x^{2}}\,\mathrm{d}x}}=f\left(0\right) $$


Q:

Send event to Google Analytics using API server sided

I have a website where I send events to Google Analytics using javascript function:
ga('send', 'event', 'showphone', 'feedback', 'result');
However I also need to send some similar events from server-side using PHP. I tried this quick start tutorial: Hello Analytics API: PHP quickstart for service accounts and reporting works like a charm, but I have no idea how to send event.
Could you please show me step-by-step what I should code to send exactly same event like mentioned above.

A:

Hello Analytics API: PHP quickstart for service accounts  is not going to help you at all.    That code uses the core reporting API the core reporting API is for requesting data from Google Analytics not sending data to Google Analytics.
To send data to Google Analytics we use the Measurement Protocol. The measurement protocol is used to send information to Google analytics the JS snippet you posted also uses the measurement protocol.
You can use the measurement protocol from any language that supports HTTP post or Http Get.   That being said there is no PHP specific library for sending information to Google analytics you are going to have to format your post yourself.   A tip would be to use Validating hits to check it before you send it to Google while you are developing this.
It will probably look something like this
http://www.google-analytics.com/collect?v=1&tid=UA-XXX-Y&cid=35009a79-1a05-49d7-b876-2b884d0f825b&an=My%20Awesom%20APP&aid=com.daimto.awesom.app&av=1.0.0&aiid=come.daimto.awesom.installer &t=event&ec=list&ea=accounts&userclicked&ev=10

A:

There is a PHP library php-ga-measurement-protocol by theiconic on github which can be used to send data using Measurement Protocal.
use TheIconic\Tracking\GoogleAnalytics\Analytics;

// Instantiate the Analytics object
// optionally pass TRUE in the constructor if you want to connect using HTTPS
$analytics = new Analytics(true);

// Build the GA hit using the Analytics class methods
// they should Autocomplete if you use a PHP IDE
$analytics
    ->setProtocolVersion('1')
    ->setTrackingId('UA-26293728-11')
    ->setClientId('12345678')
    ->setDocumentPath('/mypage')
    ->setIpOverride("202.126.106.175");

// When you finish bulding the payload send a hit (such as an pageview or event)
$analytics->sendPageview();


Q:

Integrating Twitter bootstrap?

Basically, I declare my external CSS on my template within the HEAD tag. Then, if I declare another external CSS file (being TB) in the same tag all hell breaks loose in the page. However, all seems OK if I keep the two CSS file declarations away from each other i.e one in body other in head.
Is this a problem doing things this way? Or should I, ideally merge the two CSS files into one great whopping file.
All I want to do is incorporate some elements of TB into an existing layout that I want to keep, as opposed to re-writing everything from scratch.
Thanks.
- Sample code :

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Test</title>

    <link href="../externalsheet.css" rel="stylesheet" type="text/css" />

    <link rel="stylesheet" type="text/css" href="../cssverticalmenu.css" />

    Club test

Home

Insert and Update

Add member into database

Add event into database

Add member total and comment into database

Update members personal details

Delete

Remove member from database

Remove event from database

Remove member total & comment from database

Show data

Show members on database

Show events on database

Show member totals and comments on database

main box

     <link rel="stylesheet" type="text/css" href="bootstrap.css"> // Attempt here to allow TB to work

A:

I'm making a blind guess here, but you may be importing your CSS incorrectly; here's how your CSS should be imported into the head:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Bootstrap 101 Template</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
        <link href="css/your-css.css" rel="stylesheet">


Q:

Prevent Gnome Terminal From Exiting After Execution

How do you prevent gnome-terminal from exiting after its given command has exited?
I'm calling gnome-terminal from a cronjob, in order to create a terminal accessible to the user. The terminal is initially given a specific program to run. e.g.
gnome-terminal --tab -e "/usr/bin/myprog"

This works fine, except that when "myprog" exits, so does the gnome-terminal. How do I keep it running, but just drop back to a terminal prompt?

A:

Try this:
gnome-terminal --tab -e "/bin/bash -c '/usr/bin/myprog; exec /bin/bash -i'"

A:

Create a profile (i.e. hold), set "When command exits: Hold the terminal open" and then
$ gnome-terminal --tab --profile hold -e /usr/bin/myprog

A:

Create a shell script like this:
#!/bin/bash
# myprog-wrapper.sh - runs /usr/bin/myprog and then starts a new bash session
/usr/bin/myprog
/bin/bash

Give the shell script execute permission.
Then set up your cron job to call this script instead of directly calling myprog:
gnome-terminal --tab -e "/path/to/myprog-wrapper.sh"

Replace /bin/bash with your shell of choice.


Q:

Is it possible to decode xor encoded string from N copys?

Let's say, I've got N strings encoded with "random" bytes using xor.
If I know that the information encoded is the same everywhere, is it possible for me to get at the information itself by doing some sort of manipulation with the data?
I've tried this with 3 strings (xor them with each other and than try to solve equations to get at the random bytes values) and to me it looks like it's impossible. Can anyone confirm or deny this?

A:

No, this is not possible. Encoding a message using XOR and a key of equal length, randomly chosen from a uniform distribution, leaves you with a ciphertext that is equally likely as any other possible ciphertext, regardless of what the original message was. Therefore, without knowledge of the key, the encoded message tells us absolutely nothing about its secret.
The security is not compromised by running the algorithm again. It will yield a second number whose probability is also evenly distributed and more importantly, independant of the first ciphertext, as long as the keys are chosen independantly, even if the message is the same. Once again, these two numbers are equally likely as any other possible combination of two ciphertexts, regardless of the original message. So here too, the message stays a secret.
In fact, if this were not the case and multiple versions of the same message, but encoded with different keys, did reveal information, breaking the encryption would be trivial, even with only one ciphertext. An attacker could easily make more, by XOR'ing the ciphertext with another number, as this is equivalent to XOR'ing the message with a different random number.


Q:

Excel VBA add code userform programmatically

I got a tricky issue with my VBA-code. The situation is that I have a manual created userform. I add controls to the userform with a macro and it works fine for me. But now I also need to add event-code to the userform. Following code I want to add with .CodeModule.InsertLines. The important part is that the textboxes, which I want to call should work variably, but it doesn't work, any ideas how to fix this? (Textboxes are named like this: textbox_0, textbox_1 and following)
Dim iMaxColumns As Integer
Dim iCount As Integer

iMaxColumns = Tabelle4.Cells(8, 2).Value
Dim vArray(0 To iMaxColumns - 1) As String

For iCount = 0 To iMaxColumns - 1
    vArray(iCount) = textbox_ & iCount &.Value
Next

'do sth. with the arrray

I assume the problem is that I can't add variables to my textbox object. I also could work with the complete path to my textbox calling it with .Designer.Controls("textbox_" & iCount & "") but that is a bunch of code and I hope to avoid that.

A:

I figured out a quite easy way to solve my problem. I wrote all the necessary code in a seperate module. There I can address all the variables and information I need. After that when creating the UserForm I just copy all the code into the UserForms code block.
Public Function edit_userform(strUserForm As String, _
strUserFormEvents As String)
    Dim VBProj As VBIDE.VBProject
    Dim VBComp As VBIDE.VBComponent
    Dim VBComp_Event As VBIDE.VBComponent
    Dim strCode As String

    Set VBProj = ActiveWorkbook.VBProject
    Set VBComp = VBProj.VBComponents(strUserForm)
    Set VBComp_Event = VBProj.VBComponents(strUserFormEvents)

    With VBComp_Event.CodeModule
        strCode = .Lines(1, .CountOfLines)
    End With

    VBComp.CodeModule.AddFromString strCode
End Function


Q:

How to tell when a web service client did not successfully receive payload

I need to know if a client of my web service has successfully received a message.  If the client does not receive the message (network goes down for the client in the middle of the call), I want to rollback my changes, so the next call they make will give them the same data that they attempted to get the first time.
Each call to the web service gives them a sequential "page" worth of data, and I don't want them to miss a "page".  If I can't tell when the transmission fails, I will not be able to roll back so the client will potentially have to call support to tell them about the missing "page".
I tried killing the client process in the middle of a lengthy call, while the server was still doing some data processing, but the server just kept right on going and finished successfully.
This is a Java web service using Axis2 and JBoss with SOAP.  I am digging into the documentation for some settings about this, so hopefully it is possible to configure.

A:

I don't think there is a built in way for the client give an Ack that it has received the payload.  So you may need to build it in to your business process.
I have seen this done a few different ways.

Provide the client with an element that specifies it is receiving payload x of y, if the client doesn't pick up a specific payload due to network issues, it can request that specific payload again.
If it is an all or nothing scenario, then have the client request some sort of token from the web service at the beginning of the transaction and then after it has picked up all of its "pages" then the client can make another call that will let the web service know that the transaction was completed.

Hope that helps.


Q:

Unable to find explicit activity class when started from fragment

I have a fragment that I'm trying to start another activity from in a button click like this:
Intent i = new Intent(getActivity(), RoundPagerActivity.class);
// put extras
startActivity(i);

The app crashes on the call to startActivity(i) with a Fatal Exception. Here's the logcat:
08-24 22:08:12.625: D/AndroidRuntime(9865): Shutting down VM
08-24 22:08:12.625: W/dalvikvm(9865): threadid=1: thread exiting with uncaught exception(group=0x40c231f8)
08-24 22:08:12.720: E/AndroidRuntime(9865): FATAL EXCEPTION: main
08-24 22:08:12.720: E/AndroidRuntime(9865): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.wilk.android.tablink/com.wilk.android.tablink.RoundPagerActivity}; have you declared this activity in your AndroidManifest.xml?
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1511)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1387)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.app.Activity.startActivityForResult(Activity.java:3190)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:826)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.support.v4.app.Fragment.startActivity(Fragment.java:838)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at com.wilk.android.tablink.RoundListFragment.onListItemClick(RoundListFragment.java:94)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.support.v4.app.ListFragment$2.onItemClick(ListFragment.java:58)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.widget.AdapterView.performItemClick(AdapterView.java:292)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.widget.AbsListView.performItemClick(AbsListView.java:1175)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2703)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.widget.AbsListView$1.run(AbsListView.java:3456)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.os.Handler.handleCallback(Handler.java:605)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.os.Looper.loop(Looper.java:137)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at android.app.ActivityThread.main(ActivityThread.java:4507)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at java.lang.reflect.Method.invokeNative(Native Method)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at java.lang.reflect.Method.invoke(Method.java:511)
08-24 22:08:12.720: E/AndroidRuntime(9865):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
    08-24 22:08:12.720: E/AndroidRuntime(9865):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
    08-24 22:08:12.720: E/AndroidRuntime(9865):     at dalvik.system.NativeStart.main(Native Method)

Here's my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.wilk.android.tablink"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo" >

        <!-- other activities -->

        <!-- activity that calls the pager activity -->
        <activity
            android:name="com.wilk.android.tablink.RoundListActivity"
            android:label="@string/app_name" >

        </activity>

        <!-- activity that is called -->
        <activity
            android:name="com.wilk.android.tablink.RoundPagerAcivity"
            android:label="@string/app_name" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.wilk.android.tablink.RoundListActivity" />

        </activity>

    </application>

</manifest>

The odd thing is I have another app that does this the same exact way w/o issue.
I've looked at other questions here and am pretty sure I've exhausted those choices, at least the ones that appeared to apply. I've tried to set breaks points in the new activity as well but none are hit. Can anyone see something I've newbly overlooked?

A:

It's misspelled in your manifest. You have: android:name="com.wilk.android.tablink.RoundPagerAcivity" It should be android:name="com.wilk.android.tablink.RoundPagerActivity".
Also, I don't know if it matters, but in my application I also have an attribute on the "detail" activity like this:
    <activity
        android:name="com.wilk.android.tablink.RoundPagerActivity"
        android:label="@string/app_name"
        android:parentActivityName="com.wilk.android.tablink.RoundListActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.wilk.android.tablink.RoundListActivity" />
    </activity>


Q:

Block users that write offensive answers

I reviewed an answer on this question How to best position Swing GUIs? that said:

 its because u have a small p***s

Warning: spoiler
What can you do with this answer? I have flagged it as rude or abusive and added this comment:

it is not respectful for other people! Where is your respect for other people? People like you must be blocked on stackoverflow!

Now I was thinking I need to do more. Can you block that user on Stack Overflow?

A:

Please flag such a post with the rude or abusive option. We'll take it from there.
Moderators can warn or suspend accounts or even delete the account if there has been no positive contributions.
In this case, it was just a troll account, and it has been removed as such.


Q:

How to extract motor from BMW 318 TDS E36 Fuel prepump to clean it

It seems that a clogged motor can make it seem as the prepump (on the pic below) is dead. I noticed that a very small cleanup (external) revived it for a few minutes.
Now I would like to take the motor apart for complete inside cleanup.
I would just need advice on how to actually separate the motor from the enclosure. There are black silicone / rubber mounts around and I can't manage to remove them. I fear I could tear them.
EDIT : I confirm the motor is sealed (cf pics)
I just can't understand how I could actually take the motor out! The tube that goes to it (black) is pressed so tight against the little plastic outlet that it's nearly impossible to take out !
Also I had a bad surprise, the little filter has kind of oxidized and parts of it are going away in little pieces. I fear they could get into the injectors !
Last but not least : I managed to connect the motor itself to a 12V power source. I hear it buzzing !!!!
So I don't understand why it does not work when it is installed inside the car (the relay is ok, the fuses to !).
EDIT 2 : after taking the pump system out, I connected a car battery charger to it (directly). It's also 12V so there was not so much risk of damaging it. The good news ? The pump seems to work perfectly ! I even inverted the voltage and made it a bit turn the "wrong" side, for a few seconds.
So then I just reassembled all the parts and now the car DOES use the pump, after each time I turn it on. So maybe the pump problem was due to a bad electric contact ?
Anyway. So now I also know how to unmount the motor & 2 black silicon dampers from the support. Just had to push them gently but steadily aside thanks to a flat screwdriver.
But I must say that now, I near bubble noise when I turn the pump on (just before turning the engine on). That gives an aquatic atmosphere to my car.

A:

I don't know exactly how the pump comes out of the holder, but if you are saying the black tube is the only thing which is really holding it in, just cut it. You'll get a new hose with your new pump. The pump I just looked at had it in the parts kit. Comes with two hose clamps which connect both ends for you. You'll also get a new strainer for the bottom, so you don't have to worry about that either. Here is a picture from rockauto of one example:


Q:

Using an inverse value of an injective function

I'm trying to prove this lemma:
lemma
  assumes "x = inv f y" and "inj f" and "x ≠ undefined"
  shows "y ∈ range f"
  using assms try

But Nitpick tells me this statement is not true:
Trying "solve_direct", "quickcheck", "try0", "sledgehammer", and "nitpick"...
Nitpick found a counterexample for card 'b = 3
and card 'a = 2:

  Free variables:
    f = (λx. _)(a1 := b1, a2 := b2)
    x = a2
    y = b3

Nitpick's counterexample assumes that y = b3 is not in the range of f. But in that case, how can there be an x = inv f b3 which is not undefined?

A:

The value undefined is an arbitrary unknown value. You cannot use it do check that the result of a function is not defined. All functions in Isabelle are total.
If y is not in the range of f, then inv f y could be any value.
You could work around this by defining your own inverse function that uses an option type.

A:

peq has already provided a good answer. However, I would like to make several side remarks that you may find helpful (i.e. this is not an answer, but an addendum to peq's answer).
Generally, I am aware of two in-built convenience facilities in Isabelle/HOL for mimicking (technically, f::'a=>'b will always be a total function with the domain UNIV::'a set) functions with a restricted domain/codomain:

Tools in the theory Map that are accessible from the theory Main. These tools could supplement peq's suggestion for working with the type constructor option.
Tools in HOL-Library.FuncSet. These tools were developed around the idea of using undefined to "restrict" the domain/range of a function.

Following the second suggestion of using HOL-Library.FuncSet, for example, you could "restrict" inv to the range of the function. In this case, the theorem that you have stated can be proven under the restricted inverse:
theory Scratch
  imports
    Main
    "HOL-Library.FuncSet"
begin

abbreviation inv' where "inv' f ≡ restrict (inv f) (range f)"

lemma
  assumes "x = inv' f y" and "inj f" and "x ≠ undefined"
  shows "y ∈ range f"
  using assms unfolding restrict_def by meson

end

Note, however, that the theorem above is still not very useful as it implicitly omits the possibility that undefined = inv' f y when y is in the range of f.

Having tried both sets of tools that I mentioned above quite extensively, my personal opinion (not that you should assume that it carries any weight) is that often the simplest and the most natural solution is not to use them and merely provide additional assumptions that specify that the set (or particular values) upon which the function or its inverse must act are in the (desired) domain/range of the function.


Q:

Does this simple shuffling algorithm return a randomly shuffled deck of playing cards?

You have a list of 52 cards where the position of the cards in that list does not move.
You have a second list of card positions. At first, the position list is the same as the first list.

Iterate through the first list.
For each card in the first list, generate a number from 1 to 52. Swap its position in the second list with the card in that position.

Does a bias exist? Why?
Update: Never one to believe pure math or logic, I decided to implement this myself. Here are the percent chance of the 5th card (position-wise) to be each number from 1 to 52:
1. 1.9346%
2. 1.9011%
3. 1.8513%
4. 1.8634%
5. 1.8561%
6. 1.8382%
7. 2.5086%
8. 2.4528%
9. 2.4552%
10. 2.3772%
11. 2.3658%
12. 2.3264%
13. 2.3375%
14. 2.287%
15. 2.2627%
16. 2.2151%
17. 2.1846%
18. 2.1776%
19. 2.1441%
20. 2.1103%
21. 2.084%
22. 2.0505%
23. 2.0441%
24. 2.0201%
25. 1.972%
26. 1.9568%
27. 1.9477%
28. 1.9429%
29. 1.9094%
30. 1.8714%
31. 1.8463%
32. 1.8253%
33. 1.8308%
34. 1.8005%
35. 1.7633%
36. 1.7634%
37. 1.769%
38. 1.7269%
39. 1.705%
40. 1.6858%
41. 1.6657%
42. 1.6491%
43. 1.6403%
44. 1.6189%
45. 1.6204%
46. 1.5953%
47. 1.5872%
48. 1.5632%
49. 1.5402%
50. 1.5347%
51. 1.5191%
52. 1.5011%

As you can see, quite un-random. I'd love a mathematician to prove why the 5th card is more likely to be a 7 than anything else, but I'm guessing it has to do with the fact that early cards, like 7, have more opportunities to swap -- which is exactly what the right algorithm prevents, it only lets cards swap once.

A:

This is a common way to botch the Fisher-Yates shuffle algorithm. See What distribution do you get from this broken random shuffle? for a lively discussion on properties of this implementation.

How is this different from Fisher-Yates?
For Fisher-Yates, at the kth card you must choose a random number between k and 52. You are choosing a random number between 1 and 52 each time.

The method you describe is similar to that discussed in What distribution do you get from this broken random shuffle?, but may not be exactly the same. Your implementation is similar to the well studies "Top to Random" shuffle (see Analysis of Top To Random Shuffles by Diaconis, Fill and Pitman) that will eventually give a fully shuffled deck, though not in "one pass". The Top to Random shuffle is described as following:

Choose a random number p from 1 to
  52, and swap the top card with the
  card at position p. Continue until
  the top card is the card originally in
  position 52, and after this is
  randomly placed the deck is in random
  order.

This stop condition is known as a "Stopping Time", and takes quite a while to attain. The Fisher-Yates shuffle is far faster.


Q:

My Listview Returns nothing while using retrofit

I  am new to retrofit,i am just trying to json parsing, i don't know what i missed?
The list view is not displaying. Kindly help me with issue.I am using ListAcivity with List Adapter.This is Strange to me .Please help with this.
This is Client.java
public class UtubeClient {
private static UtubeApiInterface UtubeService;

public static UtubeApiInterface getTwitchTvApiClient() {
    if (UtubeService== null) {
         RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint("http://tamilpasanga.in")
                .build();

        UtubeService = restAdapter.create(UtubeApiInterface.class);
    }

    return UtubeService;
}

public interface UtubeApiInterface {
    @GET("/mytuts/list.json")
    void getStreams(  Callback<List<UtubeChannel>> callback);
}

}
Get the callback in mainActvity
MainActivity.java
public class MainActivity extends ListActivity {

//private ProgressBar mProgressBar;

private List<UtubeChannel> streamData;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    streamData = new ArrayList<UtubeChannel>();

   // mProgressBar = (ProgressBar) findViewById(R.id.progressBar);

    setListAdapter(new MobileArrayAdapter(this,streamData));

    downloadDatainRetrofit();

}

private void downloadDatainRetrofit() {

       // mProgressBar.setVisibility(View.VISIBLE);

        UtubeClient.getTwitchTvApiClient().getStreams(new Callback<List<UtubeChannel>>() {
                                                          @Override
                                                          public void success(List<UtubeChannel> utubeChannels, Response response) {
                                                          streamData.addAll(utubeChannels) ;
                                                          }

                                                          @Override
                                                          public void failure(RetrofitError retrofitError) {
                                                              //
                                                          }

                                                      }
        );
    }
}

UTubeChannel.java
      public class UtubeChannel {
private  String url;
private  String name;
     UtubeChannel(String url,String  name){
 this.url=url;
 this.name=name;
   }

public String getUrl()
{
    return this.url;

}
public  void setUrl(String url)
{
    this.url=url;
}

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

}

}
Mobile Array Adapter
public class MobileArrayAdapter extends ArrayAdapter<UtubeChannel> {
protected static final String TAG = null;
private final Context context;

String outFileName;
private LayoutInflater inflater;

public MobileArrayAdapter(final Context context, List<UtubeChannel > objects) {
    super(context, R.layout.listview_item, objects);
    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.context = context;

}

@Override
public View getView(int position, View rowView, ViewGroup parent) {

    ViewHolder holder = null;
    if (rowView == null) {

        rowView = inflater.inflate(R.layout.listview_item, null);
        holder = new ViewHolder();
        holder.name = (TextView) rowView.findViewById(R.id.name);
        holder.url = (TextView) rowView.findViewById(R.id.url);

        //  viewHolder.button.setTag(viewHolder.text);
        // viewHolder.text.setTag(viewHolder.button);

        rowView.setTag(holder);
    } else {
        holder = (ViewHolder) rowView.getTag();

    }

   UtubeChannel channel= getItem(position);

    holder.name.setText(channel.getName());
    holder.url.setText(channel.getUrl());

    return rowView;
}

static class ViewHolder {
    public TextView url;

    public TextView name;

}

}

A:

you passed empty list to your adapter, then you have tried download data from Internet but as you don't call, notifyDatasetChanged your list not showing anything. so you need change your code too :
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    streamData = new ArrayList<UtubeChannel>();

   // mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    downloadDatainRetrofit();

}

private void downloadDatainRetrofit() {

       // mProgressBar.setVisibility(View.VISIBLE);

 UtubeClient.getTwitchTvApiClient().getStreams(new Callback<List<UtubeChannel>>() {
 @Override
 public void success(List<UtubeChannel> utubeChannels, Response response) {
       streamData.addAll(utubeChannels) ;
       setListAdapter(new MobileArrayAdapter(this,streamData));
 }

 @Override
 public void failure(RetrofitError retrofitError) {
                                                              //
 }

 });
}

or you can use:
1 - create one global value in your class as:
MobileArrayAdapter adapter.

2- in onCreate use:
adapter = new MobileArrayAdapter(this,streamData);
setListAdapter(adapter);

3- after downloading data use:
adapter.notifyDatasetChanged();

for refreshing list data


Q:

What does "rigorous proof" mean?

I have heard several times that some mathematician has given another and more rigorous for an established theorem, but I don't know what does it really mean and what differences makes it to be more 'rigorous'. My understanding of a proof is that a proof is some explanation to convincing others that a statement is true. If some proof is not rigorous, does it mean that while the proof is acceptable for many but it is not for everybody? If so, the proof is not correct since it going to be rejected by some people and it is not a proof at all. Or, does rigorous mean it uses more advanced tools? If so, why not any alternative (but simpler) proof is also acceptable as rigorous (which is more 'valuable' as well since it's simpler!)?
Saying those limited insight of mine, my questions are:
$1-$ What does rigorous proof mean, in general definition?
$2-$ In order to understand your answers, as an example I am re-writing three of the proofs for the compactness of the torus. Which of the following proofs are most rigorous, 'normal' and least rigorous; and why so?

Theorem: The torus $T^2$ is compact.
First proof: The torus is homeomorphic to the product space $S^1 \times S^1$. The circle $S^1$ is compact. Therefore the torus is the product of two compact spaces, and thus it is compact.
Second proof: The torus $T$ is the subspace of $\mathbb{R}^3$ obtained by rotating a circle about the $z$-axis. The torus is closed since given any point in its complement, there is an open ball of sufficiently small radius centered at that point and disjoint from the torus. Also, the torus is bounded since it is contained in the ball of radius $4$ centered at the origin. Since the torus is closed and bounded in $\mathbb{R}^3$, it is compact.
Third proof: The torus is homeomorphic to a space obtained as a quotient
space of the square by identifying opposite edges. The square is a closed and
bounded subset of $\mathbb{R}^3$ and therefore is compact. Furthermore, a quotient map on the square is a continuous function, and the image of a compact space under a continuous function is compact. Therefore the torus is compact.
Thanks a lot for your guidance.

A:

I don't think, that "rigorous" proof necessarily means that you provide a lot of details. It should be very clear, what you assume to be known, and what your definitions are, and how exactly the result is derived from this.
For example, the first proof seems not to be  very rigorous. First of all, we do not know how the torus is defined. If $T^n=S^1\times \cdots \times S^1$, then we also need to say why $S^1$ is compact, in order to conclude that $T^n$ is compact.

A:

A proof is a succession of "trivial" steps, leading from one statement to another. To be perfectly rigorous, the trivial steps should be either axioms, or theorems proven in equally rigorous manner (and references to said proofs).
However, this is clearly impractical, so in the facts most steps are condensed or simply omitted, and it's up to the reader to fill in the gaps. The more gaps, the less rigor you have. It doesn't necessarily mean the steps are less correct: they can be perfectly true, but the reader has a more difficult task to check and understand them.
In your examples about the torus, you clearly use results about compact sets (among others). I don't have enough background here, so it is not detailed enough to convince me. On the other hand, a reader recognizing theorems he has accepted before would be able to fill the gaps and decide that some of them are sufficiently rigorous for him.

A:

A rigorous proof is a proof that can be seen to be valid by means of a valid proof-checking algorithm.  Aristotle and many who followed showed us that certain forms of argument cannot lead from true premises to a false conclusion.  One example of that is that a conclusion is validly deduced if it is true in every row in a truth table in which the premises are true.  Other examples involve what can and what cannot be done with the quantifiers $\exists$ and $\forall$.  There are efficient algorithms for checking validity of proofs, even when actually finding the proof may require insight.
It is said in comments above that a proof is rigorous according to its context.  I think it's more accurate to say a proof omits things assumed already known to the reader.  Published rigorous proofs are not usually rigorous proofs, but rather descriptions of rigorous proofs.  "No generality is lost by assuming blah blab blah" is an assertion requiring proof, but the proof is not given and the reader might feel his time is wasted if such a proof were there.  "Having proved $f$ is continuous [over the past ten pages] we can then deduce the conclusion from the intermediate value theorem." This may omit the simple proof that a certain quantity really is intermediate between two others.
A good description of a rigorous proof is not a rigorous proof itself, but it differs from an intuitive argument.


Q:

What should I check if my chainsaw fails to start?

My chainsaw stopped working and I've got a tree that fell and needs cut up.  Does anybody have any idea what I can do to get my chainsaw started? I've done a bit of stuff on cars so I'm willing to try to take it all apart, though part of me is tempted to just drop $200 for a new one.  Still, an afternoon tinkering isn't going to cost me much.  Here is what I tried:
So Far:

check gas in tank Add Star Tron or Stabil Fuel Additive
check for spark with screwdriver.
Check Air Filter / intake for clogs
Check Fuel Filter / to cylinder.
Check linkages for Start/Stop and choke levers are operating
Clean Magneto of Rust, ensure it holds a screwdriver up.
Clean carburetor and fuel lines, especially if it may contain old fuel.

It's a husqavarna about 5 years old.  I ran it hard 3 years ago when I had another tree topple but it made it through, though I may have vapor locked it once.  It's also not been running since I failed to start it last year and it's been sitting there.  With the spring I need to get on it before the weeds come.

A:

Most two cycle engines are sensitive to the newer gasoline blends that can contain up to 10% ethanol. Get a small bottle of fuel additive for small engines and add a small amount of that into your gas tank. It should run a lot better after that. I had a similar problem with my leaf blower last year and this did the trick.

Star Tron is a much better brand than Stabil by the way.
If you are still having trouble and you have already checked the spark plugs, sometimes the magneto can have a buildup of rust on the surface that prevents it from generating enough current to sustain repeated firing of the spark plug as the engine turns.  Take apart the pull start mechanism on the chainsaw until the magneto is exposed, and take a fine grit sandpaper to it to rub off all the rust that has formed on it by sitting all these years.  To clarify the magneto is the part that is magnetic, it should grab your screwdriver.


Q:

Carrying SmartFoxServer connection across Android Activities

I am using SmartFoxServer for a multiplayer game.  I have it working fine when it loads up in the main chat room.  In my app you an create new game rooms and when you click on one it launches a new activity and enters that room.  It appears I have to connect to the server again after that.  Then I get already logged in error.
How can I maintain the smartfox client throughout my activities?

A:

You can override the Application class and make your server reference a static public variable which will be available from any Activity using ((YourApplication)getApplication()).yourStaticServerReference.
To override your Application class, follow the following steps :

Create a class extending Application, let's call it com.yourpackage.YourApplication
package com.yourpackage;

import android.app.Application;

public class YourApplication extends Application {
    public static SmartFoxServer smartFoxServer;

    @Override
    public void onCreate() {
        smartFoxServer = initSmartFoxServer(); // I don't know SmartFoxServer's API so let's imagine you implement this somewhere in the Application class.
        // Now the smartFoxServer field is like a global variable visible in all your Activities using ((YourApplication)getApplication()).smartFoxServer
    }
}

In your application manifest you have to edit the application declaration :
<application android:icon="@drawable/icon" android:label="@string/app_name"
        android:name="com.yourpackage.YourApplication">

If you often access the smartFoxServer object, you can even use java 1.5 static import feature :
import static com.yourpackage.YourApplication.smartFoxServer;

public Activity myActivity {
    public void anyMethod() {
        // Thanks to the static import, smartFoxServer is directly accessible, without calling getActivity().
        smartFoxServer.doSomething();
    }
}

I wrote this directly here so there might be some things wrong... I will check this in more details when the kids let me more than 2 minutes of free time ;-)


Q:

Will a company's stock price be affected when warrants are issued, or exercised?

A company has 500 million outstanding shares, and it issued 100 million warrants 10 years ago.
Assume that none of the warrants has been exercised yet. If tomorrow all the holders exercised their warrants, the company will have 600 million shares outstanding, and 0 warrants.
Will the company's share price be affected, since there is an increase in supply of 100 million new shares? Or would the share price have been adjusted/factored into consideration, 10 years ago when the warrants were issued?

A:

A company typically issues warrants* to investors & institutions participating in a new share or bond issue. The warrant is a "kicker" to sweeten the deal by granting participants the right, but not the obligation, to acquire stock in the company at a set price, by a given date. (On the surface, warrants are similar to call options, but different in other respects. Perhaps another question.)
Usually, the warrants are priced out of the money, but with ample time before expiration to provide for the possibility that good company performance will raise the underlying share price above the exercise price, making the warrants worth exercising.
Since warrants tend to be issued as one part of a deal, the stock price at the time of the deal will primarily be affected by the principal financial instruments involved. The market will weigh the deal's pricing, reasons for fundraising, and likelihood for positive or negative outcomes. For instance:

If new shares are issued, are they at a steep discount to recent share prices? Shareholders don't like to see new shares issued at a discount, yet sometimes companies do it because they're desperate and nobody would pay a higher price. The market may drive down the share price.
If new shares are issued, are they at a price consistent with recent share prices? Maybe no impact. On the other hand, were the funds raised, say, to pay down high-interest debt, or fund an eagerly-anticipated expansion to fill unmet product demand?  If the reason for raising money has a good probability of growing earnings, the market may react positively, else yawn.
If new bonds are issued, are they at an interest rate higher than expected? Shareholders seeing higher interest costs ahead, or who interpret the higher rate as lower confidence from creditors may drive the share price down. Or, if shareholders had been worried a money-losing company might be unable to raise money at all, i.e. possible bankruptcy, then the shares could have initially been distressed, and success even at the high interest rate might be interpreted as a positive sign.
If new bonds are issued, are they at an interest rate lower than expected? As with the share issuance case, shareholders could react positively because the funds could, say, retire existing higher-interest debt, or fuel growth.

Those aside, let's consider just the warrants:
First, at the time of the deal, yes, the warrants can impact the share price:

If the exercise price is set too close to the current share price, shareholders might assign a higher probability that the warrants will ultimately be exercised, resulting in dilution of earnings per share.  Everything else being equal, high probability of future earnings dilution (and to what extent) is likely to have a negative impact on share price — however, you might not see any drop due to the warrants alone if the deal's primary instruments (above) gave the shares sufficient lift.
If the exercise price is sufficiently higher than the current share price, shareholders might assign a lower probability for exercise, i.e. less likely resulting in dilution.  Everything else being equal, this is unlikely to have much of an impact on the share price — however, you might still see a change in the share price due to the deal's primary instruments (above).

Next, at the time of exercise, yes, the warrants can also impact the share price. Recognize that the warrants are being exercised because the company share price has exceeded the warrant exercise price. These are two direct consequences of the exercise:

The actual increase in the number of shares outstanding, and the resulting dilution of earnings, are weighed more heavily by shareholders than the mere possibility of such. Yet, it's likely this will have been realized gradually by the market as the share price approached the warrant exercise price.
The new shares are being issued at a discount to the current market price. If the price paid by warrant holders to acquire shares is significantly below the company's net assets per share, then shareholders may also see this reduction in net assets per share as a reason to reprice the shares in the market.

There may be other reasons yet, but I hope I convinced that the market is (a) complex, and (b) constantly reassessing what a share might be worth based on a variety of changing factors & expectations.  It's simplistic to assume the impact of a warrant issue will occur all up front, or all upon exercise.

* n.b. I am referring to "warrants" in the traditional sense as used in the question, i.e. "financing warrants", typically issued by the company itself and, when exercised, resulting in issuance of new shares. Contrast with "Australian warrants" which are issued by 3rd party institutional market participants, like a pure derivative product or exchange traded option – i.e. no new shares are created. (Thanks, @Victor, for mentioning the distinction and supplying the link.)


Q:

Instantiating a variable if null

if (x == null) x = new X();

versus
x = x ?? new X();

which of these two is actually more performant? once compiled do they effectively wind up as the same thing (would x = x; be a NO-OP as a result)?

A:

Looking at the intermediate language code there is a difference:
.method private hidebysig instance void Method1() cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldfld class X Program::x
    L_0006: brtrue.s L_0013
    L_0008: ldarg.0
    L_0009: newobj instance void X::.ctor()
    L_000e: stfld class X Program::x
    L_0013: ret
}

.method private hidebysig instance void Method2() cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldarg.0
    L_0002: ldfld class X Program::x
    L_0007: dup
    L_0008: brtrue.s L_0010
    L_000a: pop
    L_000b: newobj instance void X::.ctor()
    L_0010: stfld class X Program::x
    L_0015: ret
}

Here's the code I compiled to get this:
void Method1()
{
    if (x == null) x = new X();
}

void Method2()
{
    x = x ?? new X();
}

To be sure which is faster you should time both.

Method     Initial condition   Iterations per second
---------------------------------------------------
NullCheck  x is null           33 million
Coalesce   x is null           33 million
NullCheck  x is not null       40 million
Coalesce   x is not null       33 million

Conclusion:

They are about the same in this case where the value is initially null.
The method using an if statement is considerably faster than the null coalescing operator when x is already not null.

The difference when x is not null looks like it might be due to the null coalescing operator assigning the value of x back to x (stfld in IL), whereas the null check jumps over the stfld instruction when x is not null.
Both are so fast that you'd have to have a very tight loop to notice the difference. You should only make these sorts of performance optimizations if you have profiled your code with your data. Different situations, different versions of .NET, different compilers, etc. may produce different results.
In case someone wants to know how I got these results or reproduce them, here's the code I used:
using System;

class X { }

class Program
{
    private X x;

    private X xNull = null;
    private X xNotNull = new X();

    private void Method1Null()
    {
        x = xNull;
        if (x == null) x = xNotNull;
    }

    private void Method2Null()
    {
        x = xNull;
        x = x ?? xNotNull;
    }

    private void Method1NotNull()
    {
        x = xNotNull;
        if (x == null) x = xNotNull;
    }

    private void Method2NotNull()
    {
        x = xNotNull;
        x = x ?? xNotNull;
    }

    private const int repetitions = 1000000000;

    private void Time(Action action)
    {
        DateTime start = DateTime.UtcNow;
        for (int i = 0; i < repetitions; ++i)
        {
            action();
        }
        DateTime end = DateTime.UtcNow;
        Console.WriteLine(repetitions / (end - start).TotalSeconds);
    }

    private void Run()
    {
        Time(() => { Method1Null(); });
        Time(() => { Method2Null(); });
        Time(() => { Method1NotNull(); });
        Time(() => { Method2NotNull(); });
        Console.WriteLine("Finished");
        Console.ReadLine();
    }

    private static void Main()
    {
        new Program().Run();
    }
}

Disclaimer: No benchmark is perfect, and this bechmark is far from perfect, mainly to keep things simple. I've run numerous different tests e.g. with the methods in a different order, with and without "warming up" first, over different lengths of time, etc. I get roughly the same results each time. I didn't have anything to prove one way or the other so any bias favoring one method or the other is accidental.

A:

I wouldn't worry about this premature optimization. I'm sure the designers of the C# compiler were smart enough to do this for you.

A:

There is no interresting performance difference at all. The most important thing is that if (x == null) x = new X(); is much more readable.
To answer your original question: a smart, optimizing compiler would compile x = x ?? new X() in the same way as if (x == null) x = new X();.
Hence leave micro-optimizations on the compiler and concentrate on code readability and clarity.

Update: To learn more about optimization practices read this article on wikipedia and then, in respect to the nature of your question, Google for “premature optimization is the root of all evil”.


Q:

Relations between the "$\forall$" quantifier and integration

I'm studying introduction to mathematical logic, we recently began predicate logic and I find similarities between the "$\forall$" predicate and integration:

1. They both have a dummy variable, which they "enumerate" over its possible values

2. The fact that $\forall x \forall y \alpha \vDash \forall y \forall x \alpha$ is similar to Fubini's theorem.
Is there a formalism that relates the two?

A:

I actually suspect there's a closer relation between integration and the existential quantifier.
From the perspective of category theory, summation is an instance of a coproduct, which is in turn closely related to existential quantification. For instance:

Given a family of sets $(X_i \mid i \in I)$, their disjoint union $\sum_{i \in I} X_i$ satisfies the following universal property: functions $f : \sum_{i \in I} X_i \to Y$ correspond with $I$-indexed families of functions $f_i : X_i \to Y$. (More generally, replace 'sets' with 'objects of a category', 'functions' with 'morphisms', and 'disjoint union' with 'coproduct'.)
Given a proposition $\varphi(x)$, where $x$ ranges over some set $I$, proofs of $[(\exists x \in I) \varphi(x)] \Rightarrow \psi$ correspond with proofs of $\varphi(i) \Rightarrow \psi$ for each $i \in I$.

[In fact, from the perspective of Martin-Löf dependent type theory, the notions of 'disjoint union of sets' and 'existentially quantified formula' are identified.]
Another perspective is that indexed disjoint unions and existential quantification are both instances of left adjoints to substitution functors of the appropriate kinds. I'll spare you the details now, but Sections 9.5 and 9.7 of Steve Awodey's textbook on category theory is a good starting point.
Now integration generalises summation and coends generalise coproducts, and these generalisations happen in similar ways (people smarter than myself have studied connections between integrals and coends).
So in conclusion, you're thinking along the right lines, but I think you'll find more parallels between integration and $\exists$ than integration and $\forall$.

Addendum: this blog post by Bartosz Milewski discusses the connection between coends and the existential quantifier as implemented in Haskell. It says:

Just like the end is related to a product, the coend is related to a coproduct, or a sum (in this respect, it resembles an integral, which is a limit of a sum). Rather than having projections, we have injections going from the diagonal elements of the profunctor down to the coend. If it weren’t for the cowedge conditions, we could say that the coend of the profunctor p is either p a a, or p b b, or p c c, and so on. Or we could say that there exists such an a for which the coend is just the set p a a. The universal quantifier that we used in the definition of the end turns into an existential quantifier for the coend.
This is why, in pseudo-Haskell, we would define the coend as:
exists a. p a a


Q:

Make eclipse Syntax Coloring exact as visual studio Syntax Coloring

Don't ask me why but I want to make eclipse Syntax Coloring exact as visual studio 2010 standard C# Syntax Coloring. I know where to change it in eclipse but I can't get the color codes right. Where can I find the visual studio standard C# Syntax Coloring color code to apply to eclipse?
Do you know any template that may already do so?

A:

A quick Web search turns up the Visual Studio styles on eclisecolorthemes.org.
There are instructions on the site on how to apply the theme.