text:
Q: Proof that Christofides Algorithm is a 3/2-approximation for the TSP I have quoted a section of the proof for the above statement, from Williamson and Shmoys. Can someone explain the section in italics?
"We want to show that the edges in the Eulerian Graph produced by the algorithm have total cost at most 3/2 OPT. We know that the minimum spanning tree edges have total cost at most OPT"
Is the fact that the min spanning tree edges have total cost at most OPT an easy result to notice, or is it related to some other theorem/property?

A: Fact 1: Any spanning tree has weight at least of minimum spanning tree.
Fact 2: The best possible Eulerian cycle is of weight OPT, hence the spanning tree it contains is of weight at most OPT.
But the minimum spanning tree has weight less or equal to this OPT.
NB.I assumed, weights are non-negative.


text:
Q: is it posible to config web-push to send notification to a group of users not all of them In our project we need to send notification to many users (even the app is not open in the browser)
Also some times we should send a specific notification just for a group of users not all of them.
And i know, I can do it with firebase cloud message
I know a little about web-push module that use fcm itself, but I am wondering if I can use it instead of fcm?is it posible to config web-push to send notification to a group of users or sending notification for all users in on call?
Can anyone help me in this regard and let me know about the main diffrence between fcm and web-push and which is better or I should use? thanks in advance
//using web-push to notify
//back-end with nod.js:
const webpush = require('web-push');

const vapidKeys = {
publicKey: '\<My_PUBLIC_KEY\>',
privateKey: '\<My_PRIVATE_KEY\>'
};

// get client subscription config from db
const subscription = {
endpoint: '',
expirationTime: null,
keys: {
auth: '',
p256dh: '',
},
};

const payload = {
notification: {
title: 'Title',
body: 'This is my body',
icon: 'assets/icons/icon-384x384.png',
actions: \[
{ action: 'bar', title: 'Focus last' },
{ action: 'baz', title: 'Navigate last' },
\],
data: {
onActionClick: {
default: { operation: 'openWindow' },
bar: {
operation: 'focusLastFocusedOrOpen',
url: '/',
},
baz: {
operation: 'navigateLastFocusedOrOpen',
url: '/',
},
},
},
},
};

const options = {
vapidDetails: {
subject: '',
publicKey: vapidKeys.publicKey,
privateKey: vapidKeys.privateKey,
},
TTL: 60,
};

// send notification
webpush.sendNotification(subscription, JSON.stringify(payload), options)
.then((_) =\> {_
console.log('SENT!!!');
console.log();
})
.catch((_) =\> {_
console.log();
});

A: I use fcm for my notifications as it allows me to send my notifications to an array containing multiple user notification token:

const axios = require('axios');

async function sendNotification({
  token,
  sender,
  requestId,
  amount,
}) {
  try {
    const data = {
      notification: {
        body: `Hi, Please confirm payment of ${amount} from ${sender} to be charged from your account`,
        title: 'Account request',
        click_action: 'Account_request',
      },
      data: {
        sender_phone_number: sender,
        amount,
        body: 'Test',
        title: 'MyMoney',
        request_id: requestId,
        category: 'Account_request',
      },
      to: token,
      sound: 'default',
      category: 'Account_request',
    };

    const resp = await axios.post('https://fcm.googleapis.com/fcm/send', data, {
      headers: {
        Authorization: 'key=AuthorizationKey',
      },
    });

    // If notification failed, log error
    if (resp.data.failure) {
      throw new Error('Failed to send notification');
    }
  } catch (error) {
    console.error(error);
  }
}

module.exports = {
  sendNotification
};

The token can be:
const token = ["firebaseToken1", "firebaseToken2", "firebaseToken3"]

redpajama_set_name: RedPajamaStackExchange


text:
Q: node elasticsearch client causing memory leak In my web application I am using node elasticsearch client.
with rest client I am testing the application.
I sent a request with postman test runner with number of iteration 1000 and observed memory is increase.
Before running any test case app is taking 45MB~.
After running test case with 1000 iterations app is consuming ~90MB.
After re running the same test case memory is growing to ~120MB.
I feel there is a memory leak in the application.
Node version: 0.12.5
Elasticsearch DB version: 1.5.2
Elasticsearch node client: 4.0.2
Sample code:
var client = new elasticsearch.Client({
  hosts: elasticHosts
});

app.all('*', function(req, res, next) {
  validateApiKey(req.headers["apikey"],next,res);
})

function validateApiKey(ApiKey,next,response) {
    var hits;
    var isValidApiKey = false

    client.search({
      index: 'clients',
      type: 'search',
      body: {
        "query":{
        "match":{
          "apikey" : ApiKey
        }
      }
    }
  },function(err,res) {
  response.send(true);
}

I noticed memory leak happening if use node version 0.10.39.
Is it a problem with node version? or Elasticsearch client version? or with my code?
Can some helps to solve this issue.

A: To eyeball if there is even an indication of a memory leak, use process.memoryUsage()
https://nodejs.org/api/process.html#process_process_memoryusage
The output will be in the following format:
{ rss: 4935680,
  heapTotal: 1826816,
  heapUsed: 650472 }

It seems like normal behaviour for the rss (resident set size) to grow consistently if you are buffering up a lot of data (likely the case with Elasticsearch). Therefore the heapTotal and heapUsed metrics are more likely to be better indicators.
If your had app is not hanging or suffering degraded performance over time, it may not indicate a memory leak.
Take a look at http://jayconrod.com/posts/55/a-tour-of-v8-garbage-collection for a bit more of an in depth look at v8 garbage collection.
If you still suspect a memory leak, or your app is showing the telltale signs listed above, you may want to look into tracking the leak with something such as https://www.npmjs.com/package/memwatch


text:
Q: Archive displayed on a custom page to be used in menu structure I would like to direct users to appropriate archive pages from within the menu. If I want this I need a page that I can attach to the menu.
How would I display the exact same stuff as on the archive page (archive.php) on another page so that pagination and functionalities remain the same, but some stuff will be taken from the actual page ? (can create custom page template of course)

*

*I'll still have to show a sidebar for the page that you visited and not archive's sidebar

*Breadcrumbs path will still have to show current menu item position and not archive page path

To show sidebar from the actual page is of most importance here.
EDIT
What I want to achieve is this actually:
Lets say I have a page

http://my.page/subpage/something/notifications/

I want that on this page, I can display exactly the same stuff as on the certain archive page which is here:

http://my.page/subpage/notification/

('notification' is a custom post type here)
I already have a solution that displays all archive stuff on another page (created a page template for that), but its a bit complicated to display title, breadcrumbs and sidebar properly for each page, since some of these should stay the same as they would be, but some should take the value of another site.

A: You can create a custom page template and assign it to a page. On that page you can use get_posts() to query the posts you want, like this:
global $post;
$posts = query_posts( /* Your args here*/ );

foreach($posts as $post) {
    setup_postdata($post);
    // Do your stuff as in archive.php
}

wp_reset_postdata();


text:
Q: Excel automatically performing 2 level sorting I have a very simple list. Column A contains a list of movies and Column B contains their status, either "Watched" or "Not Watched". I want a list sorted alphabetically by movie name. When I click the Sort A to Z button(with active cell in column A), it gives me a alphabetical list of Watched movies first and then an alphabetical list of Not Watched movies. Exactly like if I did 2 level sorting, first by name and then status.
Why is this? How can I get a list sorted only by movie name regardless of if it's status?

A: Figured it out. Turns out that when I copied the data from Notepad, it somehow messed up the data but not visually. Whenever I tried to edit a cell, the text would behave very weirdly. This time, I didn't use the import wizard so it went fine.

A: Just to clarify what you already found,
when I copied the first 14 rows of your spreadsheet
and pasted them into a text window (e.g., Notepad),
I got this:
Movie Name      Status
"                                       10 Cloverfield Lane"    Watched
12 Angry Men    Not Watched
"                                       12 Monkeys"     Watched
"                                       12 Years a Slave"       Watched
"                                       10,000 BC"      Watched
"                                       2 Fast 2 Furious"       Watched
"                                       21 Jump Street" Watched
"                                       22 Jump Street  "       Watched
"                                       28 Days Later           "       Watched
"                                       71      "       Watched
"                                       300     "       Watched
"                                       300: Rise of an Empire" Watched
5 Centimeters Per Second        Not Watched

Every movie that you had watched
had five Tab characters at the beginning of its name.
Every movie that you had not watched was as it appeared.
I got a hunch as to what was happening when I cleared Column B
and still got the same results from sorting Column A
— i.e., Excel wasn't doing two-level sorting1;
it was getting those results just by sorting Column A.
Then I entered =CODE(A2) into cell C2 and dragged down.
All the watched movies displayed 9 (the ASCII value of Tab);
the unwatched movies displayed the ASCII value
of the first character of their name
(i.e., numbers ranging between 49 for 1 to 90 for Z).
I don't know why Excel didn't make the Tabs easier to detect (i.e., visible).
______________
1 By the way, you got it backwards in your question.
The effect you were getting
was as if you were sorting first by status and then by name.


text:
Q: how to implement in app purchase for app on play store in Flutter and Firebase? I am developing app which uses ticket system and users can buy consumable tickets to spend and The ticket data should be saved in firebase firestore into user document so how to implement it?
can I use 3rd party packages like Razorpay or Square ?but by Playstore rules the transaction should be via google play billing api as they take 30% cut!?
all I want to do is when user buy some tickets and transaction is completed then their ticket quantity in firebase firestore should increase so that when the use it I can decrement that value from Firestore.

A: In case when you sell real tickets for some events, you can use third-party acquiring like Stripe or Square and avoid 30% Google commission.
But if you are selling virtual goods or services (including some virtual tickets in your app) you must use Google in-app purchases. Otherwise, your app might be removed from the store.
You can check our service, which makes it easy to implement in-app purchases and subscriptions. It provides simple methods so you don't have to deal with Google Billing or Apple Storekit directly.
Here is a quick start guide


text:
Q: Saving stream(mp4) on iphone I have a problem. I need your help guys.
Im working on an app where the user can either watch a stream(mp4) or download it.
I've succeded to download the stream (mp4) on the iphone simulator and the file is there and it works perfect, but when I try to run the app on the iphone it will not work. The file is there but I can't play it. Please help... (It's done in Monotouch)

A: Pay attention to file encoding iPhone 3G and other iOS device can play only a specific subset of mp4 file.
In Apple documentation of MPMoviePlayerController:

This class plays any movie or audio
  file supported in iOS. This includes
  both streamed content and fixed-length
  files. For movie files, this typically
  means files with the extensions .mov,
  .mp4, .mpv, and .3gp and using one of
  the following compression standards:

*

*H.264 Baseline Profile Level 3.0 video, up to 640 x 480 at 30 fps. (The
  Baseline profile does not support B
  frames.)

*MPEG-4 Part 2 video (Simple Profile)

  If you use this class to play audio
  files, it displays a white screen with
  a QuickTime logo while the audio
  plays. For audio files, this class
  supports AAC-LC audio at up to 48 kHz,
  and MP3 (MPEG-1 Audio Layer 3) up to
  48 kHz, stereo audio.


text:
Q: How to get transparent corner using jquery corner plugin http://jquery.malsup.com/corner/
I tried but it fills color at corners
alt text http://stashbox.org/886089/11046214422-My-Desktop.png
in place of white i need transparent corner with 0 opacity.

A: I recommend you just use the CSS3 border-radius property. For browsers that don't support it, they will have square corners. This is unfortunate, but saves you a lot of trouble. I looked at many rounded-corners jQuery plugins a while ago and the bottom line is, they were all broken in some browsers in one way or another. Using CSS3 border-radius fits the idea of progressive enhancement and is easy to build and maintain.

A: http://methvin.com/jquery/jq-corner.html

Define an explicit background color in a parent element. Safari requires that an ancestor of the element being adorned has a background color set. Just set the body to "background: #fff" if you don't need some other color.
Don't use a background image in the parent. The adorned element effect sets pixels on the corners to the same color as the parent element. Those pixels are not transparent and will not show any background image that is used in the parent element.

A: @metal i found a way... Your back ground color seems to be in red right!..... If so go to corner.js and find #ffffff and replace it with your red color code...
find this line in ,
return '#ffffff'; and change to return '#ff0000';
EDIT:
I found this in forums.asp.net
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="js/jquery.corner.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $("#test").corner();
        });
    </script>

</head>
<body style="background-color: red;">
    <form id="form1" runat="server">
    <div id="test" style="width: 250px; height: 250px;
      background-color: white; opacity: 0.6;
        filter: alpha(opacity=60)">

    </div>
    </form>
</body>
</html>

A: Problem is, that this isn't possible because of the way it set.
It sets a div on top, and then uses a set of borders to create the effect.
You can change the color of the border, but if you make it transparent it will just show the absolutely positioned div below it.


text:
Q: JavaScript Promise Declaration Difference I am a JavaScript learner and have an issue about Promises.
When I use function resolve of Promise object, I got no errors as expected. Like :
var promise1 = Promise.resolve(3);

However, when I use following declaration:
var promise2 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 1000, 'foo');
});
promise2.resolve(4)

Isn't this the same thing? Or if promise2 is also a Promise class object, why do I get an error like :
TypeError: promise2.resolve is not a function
    at Object.<anonymous>

A: No, they are not the same thing.
The resolve method on the Promise (with a capital P) constructor function creates a new promise and immediately resolves it.
Existing promises don't have a resolve method. They can only be resolved by calling the function passed to the first argument of the function you pass to the Promise constructor function.

Or if promise2 is also a Promise class object, why do I get an error like

promise2 is an instance of Promise.
Promise is a constructor function used to create promises, it isn't a promise itself.
Consider the difference between a motor car and a Ford factory.

A: They are different things.
Promise.resolve(3); creates a new promise which is already resolved.
new Promise() also creates a new promise, but you need to call then on promise2 instead of resolve to be able to get the desired output.


text:
Q: Why changing nullable values to double cause Clickhouse tables became read-only frequently? Guys, I have been working with clickhouse for a while and clickhouse is running pretty well on our prod environment, but last week, I tried to change the value of 5 columns from null to a double value, and the affected rows are about 3600, the sql is like 'alter table XXX update columnA = 1.11 where timestamp = '2022-01-01 08:00:00'
Then wired things happen, all the prod clickhouse tables became read-only mode, I checked the log and found the zookeeper is complaining about out of memory, after I increased the jvm of zookeeper, the tables are still kept read-only mode, so I checked the zookeeper nodes and found a mutation znode containing huge amount of data in the table I tried to do mutation operations. After I deleted the mutation znode, clickhouse gradually became stable but still slow.
It's after I checked the replication-queue table in system database, and delete the /queue znode in zookeeper, the clickhouse insert and read speed became much faster, I think it's because too much merging operations stuck in the queue made clickhouse insertion became much slower.
So finally our clickhouse is working well again now in the prod environment, but I still did not get it, why my mutation operations of changing null values to double would cause this tragedy?
Does anyone has any idea about this issue?


text:
Q: Deleting Nodes in a Linked List After a lot of effort, I've managed to piece together a function that deletes some node from my linked list. But, out of sheer interest, I would like to find out how you can go about deleting the first node from the list, i.e. the head.
My program asks for a letter to delete, so for example.
Hello is stored in the list, the user inputs H for deletion, so that now the list is ello
At the moment with my code, the program crashes obviously as if H is deleted, there is no head, and the program doesn't know where to go to look for the list.
Below is my current implementation, any clues or hints on how to modify this code( I would like to keep it similar to how I have) to allow Head Node Deletion would be much appreciated!.
EDIT: In response to below
FullList DeleteNode(FullList temp, char c) {
FullList remember;
FullList ptr;
while (temp.head->c != c) {
    remember.head = temp.head;
    temp.head = temp.head->next;
}
ptr.head = temp.head->next;
free(temp.head);
remember.head->next = ptr.head;
return temp;
}

int main(void) {
FullList List;
char c, s;
List.head = NULL;

while ((c=getchar()) != '.') {
    List = addToEnd(List, c);
}
scanf(" %c", &s);
List = DeleteNode(List, s);
while (List.head != NULL) {
    printf("%c", List.head->c);
    List.head = List.head->next;
}
return 0;
}

typedef struct List {
 char c;
 struct List *next;
}List;

typedef struct {
 List *head;
 List *tail;
}FullList;

 List *insertList(char c, List *t1) {
  List *t = (List*)calloc(1, sizeof(List));
  t->c = c ;
  t->next = t1;
 return t;
 }

FullList addToEnd(FullList c, char element) {
 if (c.head == NULL) {
    c.head = c.tail = insertList(element, NULL);
 }else {
    c.tail->next = insertList(element, NULL);
    c.tail = c.tail->next;
 }
 return c;
}

void DeleteNode(FullList temp, char c) {
 FullList remember;
 FullList ptr;
 while (temp.head->c != c) {
    remember.head = temp.head;
    temp.head = temp.head->next;
 }
 ptr.head = temp.head->next;
 free(temp.head);
 remember.head->next = ptr.head;
}

int main(void) {
 FullList List;
 char c, s;
 List.head = NULL;

 while ((c=getchar()) != '.') {
    List = addToEnd(List, c);
 }
 scanf(" %c", &s);
 DeleteNode(List, s);
 while (List.head != NULL) {
    printf("%c", List.head->c);
    List.head = List.head->next;
 }
 return 0;
}

A: The way it is now, inside DeleteNode, when you change the argument, it only changes the local variable, not the one outside the function.
You either have to pass the FullList to DeleteNode by pointer so that modifications done to it will be visible to the caller, or modify a local one and return it, and the caller must assign the returned FullList to its list.
Either way, the changes made by DeleteNode must become visible to the caller.

A: You can't do it without changing your existing code.
You're passing your FullList struct to your DeleteNode() function. This means that any changes to that struct are not visible back in main - the function is getting a copy of it.
You would need to change DeleteNode() to accept a pointer:
void DeleteNode(FullList *temp, char c)

Then when calling it main() you would do:
DeleteNode(&List, s);

By doing this, you can change the value of temp->head in your function and it will be visible back in main()
temp->head = temp->head->next;

Edit: The logic you'll need is:

*

*Check to see if temp->head->c == c

*If yes, replace temp->head with temp->head->next

*else assign temp->head to a temp pointer *previous. Assign temp->head->next to a pointer *current. Loop through the list, moving both pointers. When you find a match in current->c, assign current->next to previous->next and free() the current node.


text:
Q: Syntax error when include OpenCV core.hpp in SWIG I'm trying to use SWIG to wrap OpenCV's C++ API. However, when I compile, I got this error:
/usr/local/Cellar/opencv/2.4.10.1/include/opencv2/core/core.hpp:123:
Error: Syntax error - possibly a missing semicolon.

and here is my SWIG file
%module example

%{
#include "opencv2/core/core.hpp"
%}

%include "opencv2/core/core.hpp"

I'm not sure if this is an error from SWIG or from OpenCV. Is it OK to only include core.hpp like this?
Thanks.

A: OK, I found the problem might be caused by the nested header including.
In opencv2/core/core.hpp, there is
#include "opencv2/core/types_c.h"
#include "opencv2/core/version.hpp"

and hence if I add these two headers to my swig file:
%include "opencv2/core/types_c.h"
%include "opencv2/core/version.hpp"
%include "opencv2/core/core.hpp"

It will not raise the missing semicolon error.


text:
Q: how do I check if the selenium server is running using bash? How do i check if the selenium server is running using bash? I want to make sure the server has been started up and running? Maybe check if selenium is running on port 4444? How can I do using bash?

A: You can use the following URL to check the status:
http://localhost:4444/wd/hub/status

A: You can do so by hitting the following URL:
"http://SELENIUM_SERVER_IP:4444/selenium-server/driver/?cmd=getLogMessages"
Use bash to hit that and it should return OK if selenium is up and running and an exception otherwise.


text:
Q: How to apply GPUImageMaskFilter on GPUImageGaussianBlurFilter for GPUImageVideoCamera I am trying to apply GPUImageGaussianBlurFilter to live camera feed masking with a PNG image. Also i need to mention that PNG image is not a square or circle but a closed Bezier Path.
Here is my code :
GPUImageVideoCamera *videoCamera;
GPUImageView *view1;

videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
videoCamera.outputImageOrientation = UIInterfaceOrientationLandscapeRight;
CGRect movieFrame = CGRectMake(0.0, 0.0, 640.0, 480.0);

view1 = [[GPUImageView alloc] initWithFrame:movieFrame];
[self.view addSubview:view1];

GPUImageMaskFilter * maskFilter = [[GPUImageMaskFilter alloc] init];

[videoCamera addTarget:maskFilter];

GPUImageGaussianBlurFilter * gaussianBlurFilter = [[GPUImageGaussianBlurFilter alloc] init];
[gaussianBlurFilter setBlurRadiusInPixels:3.0];
[gaussianBlurFilter addTarget:maskFilter];

GPUImagePicture * maskGPUImage = [[GPUImagePicture alloc] initWithImage:[UIImage imageNamed:@"mask2"] smoothlyScaleOutput:YES];
[maskGPUImage addTarget:maskFilter];
[maskGPUImage processImage];

[maskFilter addTarget:view1];

[videoCamera startCameraCapture];

But Xcode 6.0.1 breaks execution after compile in "GPUImageFramebuffer.m" on line :
NSAssert(framebufferReferenceCount > 0, @"Tried to overrelease a framebuffer, did you forget to call -useNextFrameForImageCapture before using -imageFromCurrentFramebuffer?");

Using OSX Mavericks 10.9.5, iPad Air for testing
Regards

A: I found the solution; the references should be strong. Weak references are released early


text:
Q: What can cause a change in the mangled name of a non-virtual thunk to XXX I built a middleware library (wxWidgets) with a set of patches that fix issues and add a few features (for Audacity).
Running a previously built copy of a client application (Audacity) against the patched binaries, I get a missing symbol error concerning a non-virtual thunk to wxTextCtrl::Cut(). The app rebuilt against the patched libraries runs fine, but gives me the same error when I try to run it against the unpatched library.
Turns out that this non-virtual thunk exists in both libraries, but under a different mangled name (_ZThn1344_N10wxTextCtrl3CutEv vs. _ZThn1352_N10wxTextCtrl3CutEv).
As far as I can tell the patches do not touch wxTextCtrl at all.
What can be the cause for this difference?

A: In this case the cause was the activation of the accessibility functionality in wxWidgets. I haven't hunted down exactly what changed; the feature adds methods to a good number of classes.


text:
Q: Trying to reloadData() in viewWillAppear I have a tabBarController and in one of the tabs I can select whatever document to be in my Favourites tab.
So when I go to the Favourites tab, the favourite documents should appear.
I call the reloading after fetching from CoreData the favourite documents:
override func viewWillAppear(_ animated: Bool) {

    languageSelected = UserDefaults().string(forKey: "language")!

    self.title = "favourites".localized(lang: languageSelected)

    // Sets the search Bar in the navigationBar.
    let search = UISearchController(searchResultsController: nil)
    search.searchResultsUpdater = self
    search.obscuresBackgroundDuringPresentation = false
    search.searchBar.placeholder = "searchDocuments".localized(lang: languageSelected)
    navigationItem.searchController = search
    navigationItem.hidesSearchBarWhenScrolling = false

    // Request the documents and reload the tableView.
    fetchDocuments()

    self.tableView.reloadData()

}

The fetchDocuments() function is as follows:
func fetchDocuments() {
    print("fetchDocuments")
    // We make the request to the context to get the documents we want.

    do {

        documentArray = try context.fetchMOs(requestedEntity, sortBy: requestedSortBy, predicate: requestedPredicate)
        ***print(documentArray) // To test it works ok.***
        // Arrange the documentArray per year using the variable documentArrayPerSection.
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy"

        for yearSection in IndexSections.sharedInstance.allSections[0].sections {

            let documentsFilteredPerYear = documentArray.filter { document -> Bool in
                return yearSection == formatter.string(from: document.date!)
            }

            documentArrayPerSection.append(documentsFilteredPerYear)

        }

    } catch {

        print("Error fetching data from context \(error)")

    }

}

From the statement print(documentArray) I see that the function updates the content. However there is no reload of documents in the tableView.
If I close the app and open it again, then it updates.
Don't know what am I doing wrong!!!

A: I assume that reloadData() is called before all data processing is done. To fix this you will have to call completion handler when fetching is done and only then update tableView.
func fetchDocuments(_ completion: @escaping () -> Void) {
   do {
      // Execute all the usual fetching logic
      ...

      completion()
   }
   catch { ... }
}

And call it like that:
fetchDocuments() {
   self.tableView.reloadData()
}

Good luck :)

A: The problem is that you're always appending to documentArrayPerSection but never clearing it so I imagine the array was always getting bigger but only the start of the array which the data source of the tableView was requesting was being used. Been there myself a few times.


text:
Q: SQL based on my Example for Month I am new to SQL and Learning on my own. I was wondering if someone can help guiding me to a write SQL.
I have the below data:

I am using the following query:
SELECT
    TIMESTAMP
    DATEPART(Year, TIMESTAMP) Year,
    DATEPART(Month, TIMESTAMP) Month,
    COUNT(*) [Total Rows]
FROM
    stage.ACTIVITY_ACCUMULATOR_archive
WHERE
    TIMESTAMP BETWEEN '01-Jan-2014' AND '30-June-2014'
GROUP BY
    DATEPART(Year, TIMESTAMP), DATEPART(Month, TIMESTAMP)
ORDER BY
    Year, Month

What I am trying to achieve is to display the Timestamp with year and month between the certain date and group them by month and year.
I get an error:

Msg 102, Level 15, State 1, Line 1
  Incorrect syntax near 'Year'

A: This should work.There was a extra timestamp column in select list.
SELECT
    DATEPART(Year, TIMESTAMP) Year,
    DATEPART(Month, TIMESTAMP) Month,
    COUNT(*) [Total Rows]
FROM
    stage.ACTIVITY_ACCUMULATOR_archive
WHERE
    TIMESTAMP BETWEEN '01-Jan-2014' AND '30-June-2014'
GROUP BY
    DATEPART(Year, TIMESTAMP), DATEPART(Month, TIMESTAMP)
ORDER BY
    Year, Month


text:
Q: What does Diagnostic-Code: SMTP; 573 mean? I am using sendmail to send mail from my Rails application. But, there seems to be a error happening while sending mails to a specific user domain. The error from /var/mail/*** is as follows:
Date: Tue, 11 Oct 2011 16:33:46 GMT
From: Mail Delivery Subsystem <MAILER-DAEMON@*****>
Message-Id: <201110111633.p9BGXkpR010310@******>
To: <****@*****>
MIME-Version: 1.0
Content-Type: multipart/report; report-type=delivery-status;
        boundary="p9BGXkpR010310.1318350826/******"
Subject: Returned mail: see transcript for details
Auto-Submitted: auto-generated (failure)
This is a MIME-encapsulated message

--p9BGXkpR010310.1318350826/*******

The original message was received at Tue, 11 Oct 2011 16:33:42 GMT
from localhost [127.0.0.1]

   ----- The following addresses had permanent fatal errors -----
<****@{domain}.com>
    (reason: 573 ********@****** failed to route the address)
<*****@{domain}.com>
    (reason: 573 *******@****** failed to route the address)
<*****@{domain}.com>
    (reason: 573 *******@******* failed to route the address)

   ----- Transcript of session follows -----
... while talking to *********.com.1.0001.arsmtp.com.:
>>> MAIL From:<*******@*******> SIZE=1273
<<< 573 ********@********* failed to route the address
554 5.0.0 Service unavailable

--p9BGXkpR010310.1318350826/*******
Content-Type: message/delivery-status

Reporting-MTA: dns; StreetSense
Received-From-MTA: DNS; localhost
Arrival-Date: Tue, 11 Oct 2011 16:33:42 GMT

Final-Recipient: RFC822; ****@*******.com
Action: failed
Status: 5.0.0
Diagnostic-Code: SMTP; 573 *******@******* failed to route the address
Last-Attempt-Date: Tue, 11 Oct 2011 16:33:46 GMT

Final-Recipient: RFC822; *******@********.com
Action: failed
Status: 5.0.0
Diagnostic-Code: SMTP; 573 *******@******** failed to route the address
Last-Attempt-Date: Tue, 11 Oct 2011 16:33:46 GMT

Final-Recipient: RFC822; ******@*********.com
Action: failed
Status: 5.0.0
Diagnostic-Code: SMTP; 573 *****@******** failed to route the address
Last-Attempt-Date: Tue, 11 Oct 2011 16:33:46 GMT

The bounced back emails are all from the same domain, and mails are being successfully sent to other domains. When I looked for SMTP 573 diagnostic codes, I got this "573 Internal server error, IP address related.". But I dont know what it means. Can anyone help me?
I ran these commands and I run it and got the following outputs:
# dig streetsense.com MX

; <<>> DiG 9.3.6-P1-RedHat-9.3.6-16.P1.el5 <<>> xxxxx.com MX
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 61139
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 4, ADDITIONAL: 4

;; QUESTION SECTION:
;xxxxx.com.     IN  MX

;; ANSWER SECTION:
xxxxx.com.  3600    IN  MX  10 xxxxx.com.1.0001.arsmtp.com.
xxxxxx.com. 3600    IN  MX  20 xxxxx.com.2.0001.arsmtp.com.

;; AUTHORITY SECTION:
xxxxx.com.  155394  IN  NS  ns04.ntiva.net.
xxxxx.com.  155394  IN  NS  ns01.ntiva.net.
xxxxx.com.  155394  IN  NS  ns02.ntiva.net.
xxxxx.com.  155394  IN  NS  ns03.ntiva.net.

;; ADDITIONAL SECTION:
ns01.ntiva.net.     147 IN  A   xxx.xx.xx.xxx
ns02.ntiva.net.     147 IN  A   xxx.xx.xx.xxx
ns03.ntiva.net.     147 IN  A   xxx.xx.xx.xxx
ns04.ntiva.net.     147 IN  A   xxx.xx.xx.xxx

;; Query time: 45 msec
;; SERVER: xxx.xxx.x.x#xx(xxx.xxx.x.x)
;; WHEN: Tue Oct 11 18:08:23 2011
;; MSG SIZE  rcvd: 262

ping also seem to be working:
# ping xxxxxxx.com
PING xxxxxxxx.com (xxx.xx.xx.xx) xx(xx) bytes of data.
64 bytes from linux06.ntiva.com (xxx.xx.xx.xx): icmp_seq=1 ttl=53 time=29.0 ms
64 bytes from linux06.ntiva.com (xxx.xx.xx.xx): icmp_seq=2 ttl=53 time=27.4 ms
64 bytes from linux06.ntiva.com (xxx.xx.xx.xx): icmp_seq=3 ttl=53 time=27.4 ms
64 bytes from linux06.ntiva.com (xxx.xx.xx.xx): icmp_seq=4 ttl=53 time=27.4 ms

Can anyone help me to find the issue?

A: It means the server encountered an error internally in it's processing that is somehow related to your IP address. Ping is irrelevant - as is what you ate for breakfast. Obviously - the message was not delivered to the server.
Could be a way to tell you to get lost (as in: IP address blacklisted for some reason). Could be a failure to do anything - that will be visible on some error log on the server. Not your problem unless you (a) suspect you are blacklisted or (b) are the server operator so you can check and fix.

A: Any 5xx-errors in SMTP means Permanent Delivery Error.
Here you have a triad of session-parameters, which can correlate with result

*

*From address (e-mail)

*To address (e-mail)

*sender IP (your server IP) or hostname

You have to check all possible variants, changing only one parameter from session to session (gmail test I'll not accept, bc you change both from name and server) and analyze answers
During test we'll identify - is it your ban or misconfiguration of *********.com.1.0001.arsmtp.com (both cases are possible)


text:
Q: Under pressure, why do some things explode and some liquify? For example, diesel under compression (heats and?) explodes; refrigerant under compression cools and turns from a gas into a liquid.
Is it just simply that different fluids behave differently under the same conditions?

A: Compression of a vapour usually results in a rise in temperature (note that in vapour-compression refrigeration  it is not the compression that liquidises the refrigerant, it is the subsequent cooling as the hot vapour releases heat to the surroundings). If the vapour is flammable (like diesel) and if there is a source of oxygen available then the temperature rise from compression alone may be sufficient to cause ignition of the vapour, which is the principle of the diesel engine. Other forms of internal combustion engine, such as the petrol engine, require an additional source of heat such as a spark, to initiate ignition. Being flammable is an undesirable property in refrigerants (although propane was used as an early refrigerant) which is why modern fridges do not tend to go up in flames.
So the short answer is yes, it depends on the chemical composition of the gas/fluid.


text:
Q: Does Ubuntu touch OS uses Compiz to perform animations If so, is it possible to have effects like Wobbly in Ubuntu Touch?

A: Ubuntu Touch uses Unity 8, which uses Mir & Qt rather than Compiz for that

A: No. Ubuntu touch uses Mir as the compositor. There is no clue about having Compiz like effects with Mir.


text:
Q: google-services.json does not exist xamarin I'm writing a cross-platform application in Xamarin. I have a problem with push notification (at the moment with google-services.json),
This is massage with error
enter image description here
These are packages that needed to be installed
enter image description here
I modifyed .csproj file in TextEdit by adding the following line
<ItemGroup> <GoogleServicesJson Include="google-services.json" /> </ItemGroup>

I tried to clean/rebuild project or restart Xamarin IDE many times, but the results are not consistent.


text:
Q: Perform given PHP task if no response from cURL request How can I perform a cURL request and perform a given action if there is no response from the remote machine?
The script is running in the background, and I am not concerned about making the user wait.
<?php
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'http://example.com/bla.php');
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,array('x'=>'cba!','y'=>'abc'));
if($result = curl_exec($ch)) {
    //do this
}
else {
    //do this if no response after 5 seconds
}
curl_close($ch);
?>

A: Use CURLOPT_CONNECTTIMEOUT  and CURLOPT_TIMEOUT
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5); //timeout in seconds


text:
Q: "Aquisition Attempt Failed" exception in logs with no effect on the application (Setup: Hibernate + c3p0) Ok, I got a weird one here. I have a application set up that is using hibernate configured for multi tenancy and C3P0 for connection pooling.
Everthing works fine except that in my logs an exception is thrown and i cannct get to the cause of it... The weird thing is that this exception is in no way bothering my Application it is just working fine even with the exception being thrown (always 4 times and even if I do nothing but start the server and wait. After some seconds they pop up in the log and that is it)
Here is the exception and some basic config that might be useful:
2013-05-28 09:06:02 WARN  BasicResourcePool:1841 - com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@1d926e41 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'dbuser'. ClientConnectionId:07fa33fd-9de8-4235-b991-ac7e9e1ad437
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
    at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:254)
    at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:84)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2908)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2234)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2220)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1326)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
    at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
    at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134)
    at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182)
    at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137)
    at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014)
    at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32)
    at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810)
    at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)

sessionFactory:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="annotatedClasses">
        <list>
            ...
        </list>
    </property>
    <property name="hibernateProperties">
        <value>
            hibernate.multiTenancy=SCHEMA
            hibernate.tenant_identifier_resolver=xxx.xxx.hibernate.CurrentTenantIdentifierResolverImpl
            hibernate.multi_tenant_connection_provider=xxx.xxx.hibernate.MultiTenantConnectionProviderImpl

            hibernate.dialect=${hibernate.dialect}
            hibernate.use_sql_comments=${hibernate.debug}
            hibernate.show_sql=${hibernate.debug}
            hibernate.format_sql=${hibernate.debug}
        </value>
    </property>
</bean>

The c3p0-config.xml:
<c3p0-config>
    <named-config name="c3p0name">
        <property name="acquireIncrement">3</property>
        <!--property name="automaticTestTable">con_test</property-->
        <property name="checkoutTimeout">30</property>
        <property name="idleConnectionTestPeriod">30</property>
        <property name="initialPoolSize">2</property>
        <property name="maxIdleTime">18000</property>
        <property name="maxPoolSize">30</property>
        <property name="minPoolSize">2</property>
        <property name="maxStatements">50</property>
        <property name="testConnectionOnCheckin">true</property>
    </named-config>
</c3p0-config>

Here is the implementation that instantiates the ConnectionPool:
public class MultiTenantConnectionProviderImpl implements MultiTenantConnectionProvider  {

    private static final long serialVersionUID = 8074002161278796379L;

    ComboPooledDataSource cpds;

    public MultiTenantConnectionProviderImpl() throws PropertyVetoException {
        cpds = new ComboPooledDataSource("c3p0name");
        cpds.setDriverClass("jdbc.driver"));
        cpds.setJdbcUrl("jdbc.url"));
        cpds.setUser("dbuser");
        cpds.setPassword("dbuserpassword"));
    }

    @Override
    public Connection getAnyConnection() throws SQLException {
        return cpds.getConnection();
    }

    @Override
    public Connection getConnection(String dbuser) throws SQLException {
        return cpds.getConnection(dbuser, PropertyUtil.getCredential(dbuser));
    }

Even if there is no direct answer available I am happy with any remark or direction that might help my investigation, so just post anything you got. Thank you in advance
Edit:
I found the error at hand for the failing initial connections it was just a misconfiguration of the dbuserpassword for the passwordproperty of the DBConnectionPool....
This solves part of the question and leaves ony the duplicate initaly which if following the discussion below the answer from @Steve Waldman  is most likely just a log4j misconfiguration.

A:
always 4 times and even if I do nothing but start the server and wait.

so, given that you observe this on server restarts, there is nothing very weird about it. while the server is down and restarting, c3p0 tries but fails to acquire database Connections. eventually (by default after ~30 seconds) c3p0 declares a failure, logs the Exception you see, and signals an error to Threads wait()ing on Connections. it sounds like your server restarts take more than ~30 seconds.
that you see this four times probably means that you have four active Connection pools, ie that there are four different dbusers active (including the default user). each c3p0 DataSource potentially manages multiple pools, one for each set of authentication credentials.
if you want to make these messages go away, just increase the time it takes for c3p0 to declare an acquisition failure. see here and acquireRetryAttempts and acquireRetryDelay. if you want to prevent occasional SQLExceptions thrown to clients during the restarts, lengthen the client timeout, checkoutTimeout, which you currently have set to 30 seconds.
a miscellaneous comment: you are using the slow default Connection test. i see you experimented with automatic test table but undid it. you might try setting a preferredTestQuery. maybe just SELECT 1 would be fine as recommended for SQL Server here. this may not matter much, as you are doing all your Connection testing asynchronously, but at least it may reduce the overhead of the tests.
good luck!


text:
Q: How to have multiple versions of an application in visual studios This is hopefully a simple question. I have an application written in vb.net using the visual studios 2010 environment. Every so often I want to make an offshoot of the application (many small changes to the code through the application). Currently my options are duplicating the entire application OR changing the code to allow me to make the choice of what I want to do at runtime. This is annoying an cumbersome. Any advice on how to do this a better way, or what setting I should turn on/use that all ready allows this would be great! Thanks!

A: You can use Visual studio online as a source control. Your code will be stored online and you can connect to it using Team Explorer. It free for upto 5 users.
http://www.visualstudio.com/products/visual-studio-online-overview-vs

A: you best bet is to use a version control system as suggested.
alternatively, if you want to support multiple versions that are mostly the same for a long period of time you can look into pre-processor directives (not sure about vb.net but c# has them):
#ifdef feaure1
some code
#endif

#ifdef another-feature
some other code...
#endif


text:
Q: What properties determine ClientDataSet field sizes? I have an app that uses ClientDataSets and local file storage. Some of the info is displayed in a DB grid, and I found it was getting cut off--the first 500 characters or so of a string were displayed, but the underlying fields needed to be longer. So I went back to my code and increased the size of the underlying FieldDefs and also their display widths. I also created a new dataset (at design time). Finally, I ran the application, and created a new database. Nevertheless, only ~500 chars were displayed.
Where should I look to see what's limiting my field lengths?

A: I'd suspect you're running into an internal limitation of TDBGrid column widths, since a column that displays 500 characters would be more than a typical screen wide. (You can check this if you want to wade through the VCL source; start with Grids.pas.)
Typically, a TDBGrid doesn't display a lot of text in a single column. It leads to a lot of scrolling by the user, and horizontal scrolling to read wide text is extremely annoying to most people.
The usual way of doing this is to use an ftMemo type field, which can contain virtually unlimited text content. When the column is assigned to a TDBGrid, the grid column displays (MEMO), and the application handles a click or double-click on the column to display a secondary form with a TEdit or TRichEdit to display/edit the full contents of the column.
Here's an example of a TDBGrid attached to a TClientDataSet named CDS with the following columns defined (useless, but an example) using CDS.FieldDefs in the Object Inspector:
Column      Persistent Name    FieldType    Size
------      ---------------    ---------    ----
ID          CDSID              ftInteger     0
Name        CDSName            ftString     25
Notes       CDSNotes           ftMemo        0

Since the underlying dataset doesn't exist, I assign a FileName, and use the following code to create it at runtime:
procedure TForm1.FormCreate(Sender: TObject);
begin
  if not FileExists(CDS.FileName) then
  begin
    CDS.CreateDataSet;
    CDS.Active := True;
    CDS.InsertRecord([1, 'John Smith', 'This is some longer text'#13'for testing.']);
    CDS.InsertRecord([2, 'Fred Jones', 'A note about Fred goes'#13'here for now.']);
    CDS.Active := False;
  end;
  CDS.Active := True;
end;

I put a TDataSource on the form, and set it's DataSource to CDS. I added a TDBGrid, and set it's DataSet to DataSource1.
In the Object Inspector, choose the TDBGrid, go to the Events tab, and add the following to the OnCellClick event (just for display, of course):
procedure TForm1.DBGrid1CellClick(Column: TColumn);
begin
  if Column.FieldName := 'CDSNotes' then
    ShowMessage(Column.Field.AsString); // Display other form here instead
end;

Here's the display after clicking the CDSNotes column on row 1 of the TDBGrid:

If you must display partial content of a longer text column in the TDBGrid, you can use something like the following:
procedure TForm2.CDSNotesGetText(Sender: TField; var Text: string;
  DisplayText: Boolean);
begin
  // Again, a trivial example using an arbitrary chunk of the first 20
  // characters just for demo purposes.
  if DisplayText then
    Text := Copy(Sender.AsString, 1, 20)
  else
    // Not for display only; return all the text.
    Text := Sender.AsString;
end;

Doing so with the sample app above changes the display to this:


text:
Q: What does the C++ compiler error "looks like a function definition, but there is no parameter list;" mean? #include <iostream>
#include <fstream>

using namespace std;

int main
{
    int num1, num2;
    ifstream infile;
    ostream outfile;

    infile.open("input.dat");
    outfile.open("output.dat");

    infile >> num 1 >> num 2;

    outfile << "Sum = " << num1 + num2 << endl;

    infile.close()
    outfile.close()
    return 0;
}

This is what I did and when I compile it, I got this error that said
error C2470: 'main' : looks like a function definition, but there is no
parameter list; skipping apparent body

Please don't hate me :( I am new at this computer science....

A: You forgot the parentheses which are required for a function definition.  Change that to:
int main()
{
    ...
}

A: You're missing parentheses after main.
Also, semicolons:
infile.close();
outfile.close();

A: Change that to:
int main(int argc, char *argv[])
{
    ...
}

A: int main()
Welcome to Computer Sc. and Stackoverflow (SO).
Advice: there are already a lot of C++ questions here, so just search before asking a new question :)

A: I don't hate you. ♥
Functions have parameters, such as:
void foo(/* parameters here */);

If your function takes none you don't omit the list, but leave it empty or put void:
int main()
// or:
int main(void)

Which you use is up to you. I prefer explicitly stating void.

Note, there are other variants you'll encounter. This is the second most common variant:
int main(int argc, char *argv[])

It gives you a count of the arguments and what they were. Such as:
myExe andAOne andATwo andIDontHateYou

You would be able to access those arguments. There can be more, but that should cover it for now. Don't worry about that stuff till later. <3

Concerning your code:
int main(void) // no parameters
{
    int num1, num2;
    ifstream infile;
    ostream outfile;

    infile.open("input.dat");
    outfile.open("output.dat");

    infile >> num1 >> num2; // no spaces in you variable names

    outfile << "Sum = " << num1 + num2 << endl;

    infile.close(); // missing semicolon
    outfile.close(); // missing semicolon

    return 0; // fun fact: optional. In C++, return 0 in main is implicit
}

That should get you started.

The rest of this may not make sense, and that's okay. I'm merely including it for completeness. If it doesn't make sense, ignore it for now:
int main(void)
{
    ifstream infile("input.dat"); // use the constructor to open it
    ostream outfile("output.dat");

    int num1, num2; // don't declare variables until you need them
    infile >> num1 >> num2;

    outfile << "Sum = " << num1 + num2 << endl;

    // closing is done automatically in the destructor of the fstream
}


text:
Q: Relation between Fibonacci numbers and Combinations/Counting While doing a counting problem today, I stumbled upon the fact that the $n$th Fibonacci number $F_n$ can be written as: $F_n = \sum^{r \le n/2}_{r=0} {n-r \choose r}$
Does this mean that there is some counting "significance" of Fibonacci numbers?
A way to define or describe them in plain English them rather than just the usual recursive formula or mathematical notation?

A: $F_n$ has a nice combinatorial interpretation; it is the number of ways to tile a $1\times n$ rectangle with any number of squares and dominoes. This assumes the convention $F_0=F_1=1$.
For example, $F_4=5$, because of the five tilings below:
$$
\begin{array}{|c|c|c|c|}\hline \;\;&\;\;&\;\;&\;\;\\\hline\end{array}\qquad
\\
\begin{array}{|cc|c|c|}\hline \;\;&\;\;&\;\;&\;\;\\\hline\end{array}\qquad
\begin{array}{|c|cc|c|}\hline \;\;&\;\;&\;\;&\;\;\\\hline\end{array}\qquad
\begin{array}{|c|c|cc|}\hline \;\;&\;\;&\;\;&\;\;\\\hline\end{array}\qquad
\\
\begin{array}{|cc|cc|}\hline \;\;&\;\;&\;\;&\;\;\\\hline\end{array}\qquad\\
$$
You can prove this combinatorial interpretation for $F_n$ by induction on $n$.
To prove $F_n=\sum_k \binom{n-k}{k}$, note that $\binom{n-k}{k}$ is the number of tilings which use exactly $k$ dominos. Above, we see that $\binom{4}0=1$ tiling uses zero dominos, $\binom31=3$ tilings use one domino, and $\binom22=1$ tiling uses two dominoes.


text:
Q: Relating flux and angular velocity of constantly rotating coil with induced voltage

The flux and angular position of the graph has been recorded as shown in the graph.
and so is induced voltage and angular position.
and my teacher derived the relation between induced voltage and angular position as such:

My question is how he came to this relation. All he said was flux and angular position has a linear relationship we can write the equation for induced voltage as such.
If so does it imply that Flux= BAphi such that derivative of it will be (Flux)'=BA(phi)' and how can I say Flux =BAphi from the flux and angle graph?
I have tried to find linear equations for the different slope of the graph and couldn't arrive at the derivation he made.
My approach:

I find the function for every piecewise continuous graph which gives me the following result: Φ=-B∙A, Φ=((2B∙A)/(π-2θ))∙(φ-π/2), Φ=B∙A,
Φ=-((2B∙A)/(π-2θ))∙(φ-3π/2), Φ=-B∙A and let me find the derivative of flux with respect to angle first which gives me:
dΦ/dϕ=(2B∙A)/(π-2θ), dΦ/dϕ=-(2B∙A)/(π-2θ) for two slopes
and derivative of flux w.r.t time comes out to be:
(dΦ/dϕ)∙(dϕ/dt)=((2B∙A)/(π-2θ))∙dϕ/dt, (dΦ/dϕ)∙(dϕ/dt)=-((2B∙A)/(π-2θ))∙dϕ/dt, where dϕ/dt=2πn.
and it still isn't equal to what the professor derived.
I need insight on it.
Thank you.


text:
Q: Sharepoint 2013 web application migration I want to move my sharepoint webapplication from one server to another.
I have more than 70 pages and 15 visual webparts, which are used in pages.
My question is how can i move application with all pages and webparts and content. Without any loss of content.
Thanks.

A: If you will migrate a web application to another server in another farm, you should first make sure that the SharePoint Build number of destination environment must be higher than or matched with the build number of the source environment, to make sure that check.

*

*Find the latest Cumulative Update / Farm Patch Level that has been installed in a SharePoint Farm

*This content database has a schema version which is not supported in this farm
Second, you have two methods to migrate your web application

*

*Database-upgrade

*

*In source farm, Take a backup of the content database via SQL Management Studio.

*In destination farm, Create A web application, Site Collection.

*In destination farm, Dismount the web application content database, via this command

Dismount-SPContentDatabase "<ContentdBName>"

*

*In destination , via SQL Management Studio , Restore the content database.

*In destination , Mount it to the created web application,

Mount-SPContentDatabase "<ContentDb>" -DatabaseServer "<DbServer>" -WebApplication http://SiteName

*

*In destination farm, Change Site Collection administrator to avoid the access permission issue. by going to site Setting > Site Collection Administrator > Set the site admin account in Dev.

*Finally, deploy your custom web part solutions as mentioned at Install and deploy a SharePoint (WSP) Solution Package using SharePoint Shell
For more details check Restore / Migrate a SharePoint Web Application to another farm from SQL Database Backup
Note: if your web application has multiple content database, you should backup all the content databases via SQL Management Studio and restore them to the new farm then mount them to the new web application.

*BackUp and Restore

*

*Take a backup from the old web application.

Backup-SPFarm -Directory <BackupFolder> -BackupMethod {Full | Differential} -Item <WebApplicationName> for more details check Back up a Web application
Then restore a web application as mentioned at Restore a Web application
If your web application has only one site collection do the following:

*

*Take a backup of site collection from the old web application.

Backup-SPSite -Identity http://siteURL -Path "C:\\MoveSiteCollection.bak"

*

*Create a new web application.

*Restore backup in the new web application.

Restore-SPSite -Identity http://url -Path
  "C:\MoveSiteCollection.bak"

*

*Finally, deploy your custom web part solutions as mentioned at Install and deploy a SharePoint (WSP) Solution Package using SharePoint Shell


text:
Q: Apache Kylin not able to load models/configuration I'm new to hadoop,hive, hbase and kylin. I tried to install thoose first three, and it's seems to be working.
After that I tried to install apache kylin, run the sample.sh and success.
After running the script I restart and open the web interface. Some page cannot be opened ex: /cube, /models, /admin/config
The problem is: I can see there are 5 tables created in hive, and also 2 cubes created. But when I open in web gui, the models is in loading-state and I cannot build the cube.

When I try to build the cube

I cannot find any infomative log (Or maybe there is one, but I don't know about it)
kylin.log
https://pastebin.com/TUZkQepa
hadoop-hadoop-namenode-master.log
https://pastebin.com/T8eNt3PY
hadoop-hadoop-secondarynamenode-master.log
https://pastebin.com/iMJDNFfU
yarn-hadoop-resourcemanager-master.log
https://pastebin.com/TGwJWTRF
hbase-hadoop-zookeeper-master.log
https://pastebin.com/Ym6eky5h
hbase-hadoop-master-master.log
https://pastebin.com/p1ygfw4W
Here is the configuration for hadoop
(yarn-site.xml)
<configuration>
    <property>
        <name>yarn.nodemanager.aux-services</name>
        <value>mapreduce_shuffle</value>
    </property>
    <property>
        <name>yarn.resourcemanager.scheduler.address</name>
        <value>master:8030</value>
    </property>
    <property>
        <name>yarn.resourcemanager.resource-tracker.address</name>
        <value>master:8031</value>
    </property>
    <property>
        <name>yarn.resourcemanager.address</name>
        <value>master:8032</value>
    </property>
</configuration>

hdfs-site.xml
<configuration>
    <property>
        <name>dfs.replication</name>
        <value>1</value>
    </property>
</configuration>

core-site.xml
<configuration>
    <property>
        <name>fs.defaultFS</name>
        <value>hdfs://master:9000</value>
    </property>
    <property>
      <name>hadoop.tmp.dir</name>
      <value>/home/hadoop/tmp</value>
  </property>
</configuration>

mapred-site.xml
<configuration>
    <property>
        <name>mapreduce.framework.name</name>
        <value>yarn</value>
    </property>
</configuration>

Configuration for hbase
regionservers
slave2

hbase-site.xml
<configuration>
    <property>
        <name>hbase.rootdir</name>
        <value>hdfs://master:9000/hbase</value>
    </property>
    <property>
        <name>hbase.cluster.distributed</name>
        <value>true</value>
    </property>
    <property>
        <name>hbase.zookeeper.property.dataDir</name>
        <value>/home/hadoop/datadir</value>
    </property>
    <property>
        <name>hbase.zookeeper.quorum</name>
        <value>master,slave2</value>
    </property>
</configuration>

Configuration for hive
hive-site.xml
<configuration>
  <property>
    <name>javax.jdo.option.ConnectionURL</name>
    <value>jdbc:mysql://master:3306/metastore?createDatabaseIfNotExist=true</value>
    <description>metadata is stored in a MySQL server</description>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionDriverName</name>
    <value>com.mysql.jdbc.Driver</value>
    <description>MySQL JDBC driver class</description>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionUserName</name>
    <value>root</value>
    <description>user name for connecting to mysql server</description>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionPassword</name>
    <value>gwudainget</value>
    <description>password for connecting to mysql server</description>
  </property>
  <property>
    <name>hive.cli.print.current.db</name>
    <value>true</value>
    <description>Whether to include the current database in the Hive prompt.</description>
  </property>
</configuration>

For kylin, I use default configuration, because I don't really know what to do with the kylin configuration.
What i use:
hadoop 2.7.5 binary
hbase 1.2.6 binary
hive 1.2.2 binary
kylin 2.2.0 source (I just add logs)


text:
Q: c# sql parse double value to sql Hello i tried to add a double value from c# to an sql float field in an Table.
SqlConnection SQLConnection = new SqlConnection(String.Format(@"Integrated Security=SSPI;server={0};Initial Catalog={1};", SqlServer, database));

        //For the import
        SQLConnection.Open();
                                                                                //0             1           2           3           4       5           6               7        8        9            10                  11              12               13            14         15          16        17         18        19      20         21        22          23               24          25             26            27         28                                                                                0                                     1                                2                                  3                                 4                             5                                     6                                 7                              8                               9                                    10                                      11                                     12                                 13                                    14                               15                               16                                 17                             18                             19                               20                        21                                22                                 23                                      24                     25                             26                          27                    28
        string stringForInsert = String.Format("INSERT INTO [dbo].[tblSPpowerPlant] ([projectName],[location],[shortName],[numberOfWtgs],[mwWtg],[mwTotal],[projectShareWeb],[mwWeb],[phase],[phaseNumber],[phaseDescription],[projectProgress],[mwDeveloped],[projectManager],[spaceURL],[country],[technology],[state],[allPermits],[cod],[statesince],[spID],[currency],[possibleWtgTypes],[hubHeight],[visibillity],[templateName],[timestamp],[note]) OUTPUT INSERTED.Id VALUES ({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24},{25},{26},{27},{28})", getSqlField(powerPlant.projectName),getSqlField(powerPlant.location),getSqlField(powerPlant.shortName),getSqlField(powerPlant.numberOfWtgs),getSqlField(powerPlant.mwWtg),getSqlField(powerPlant.mwTotal),getSqlField(powerPlant.projectShareWeb),getSqlField(powerPlant.mwWeb),getSqlField(powerPlant.phase),getSqlField(powerPlant.phaseNumber),getSqlField(powerPlant.phaseDescription),getSqlField(powerPlant.projectProgress),getSqlField(powerPlant.mwDeveloped),getSqlField(powerPlant.projectManager),getSqlField(powerPlant.spaceUrl),getSqlField(powerPlant.country),getSqlField(powerPlant.technology),getSqlField(powerPlant.state),getSqlField(powerPlant.allPermits),getSqlField(powerPlant.cod),getSqlField(powerPlant.stateSince),getSqlField(powerPlant.spID),getSqlField(powerPlant.currency),getSqlField(powerPlant.possibleWtgTypes),getSqlField(powerPlant.hubHeight),getSqlField(powerPlant.visibility),getSqlField(powerPlant.templateName),getSqlField(timestamp), getSqlField(note));
        SqlCommand sqlInsertCommand = new SqlCommand(stringForInsert, SQLConnection);                                                                                //VALUES ({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24})
        sqlInsertCommand.CommandType = CommandType.Text;
        SqlDataReader reader;

        sqlInsertCommand.CommandText = stringForInsert;
        reader = sqlInsertCommand.ExecuteReader();

        int id = int.MaxValue;

        while (reader.Read())
        {
            id = reader.GetInt32(0);
        }

        if (id == int.MaxValue)
            throw new Exception("Insert failed.");

        reader.Close();

        SQLConnection.Close();

But when the actual save to the db happens it saves the wrong number. Stuff like 12,3 it makes 12.3..... So my question is how to prevent that from happening? so when i type 12,3 it writes 12,3 to the table. Any advice would be great thx
btw sorry for my english not may native language
EDIT: And about the SQL-Injections i now it but there is no interface for this.
EDIT2: The datatype in the database is float.
EDIT3: 5,1,8,9,0,51,4,59 here is an example of the output. Insted 5.1 it says 5,1 and counts it as two fields. When i try to run it i get an exeption.

A: Parameters is what you want... doing it this was is inviting a SQL Injection attack.
Here's the basic gist of it:
cmd.CommantText = "INSERT INTO Table (Field1, Field2) VALUES(@Param1, @Param2);";
cmd.Parameters.AddWithValue("@Param1", yourObj.Property1);
cmd.Parameters.AddWithValue("@Param2", someMethodToReturnValue(someParam));

Not only does this prevent SQL Injection, but it maps the types of your object properties/values applied to the parameter to the correct SqlDbType.
Regardless of lack of an interface for it, it's still best practice to use parameters and avoid the injection attack (who's to say that there will never be a day in the future when these values aren't supplied elsewhere, or what if some unseasoned developer copies your code?  There's no reason to use string concatenation over parameterized queries, and every reason not to... and of course an added plus is correct type mapping!)
Last edit: AddWithValue doesn't handle possible nulls, so you can write a quick extension method like AddWithNullableValue:
public static SqlParameter AddWithNullableValue(this SqlParameterCollection collection, string parameterName, object value)
{
     if(value == null)
        return collection.AddWithValue(parameterName, DBNull.Value);
     else
        return collection.AddWithValue(parameterName, value);
}

(taken from here: Exception when AddWithValue parameter is NULL)


text:
Q: Python six library error while using spynner I installed python, pip and easy_install on my computer.
and with pip command installed spynner but i've got an error with autopy installation,
but i solved it by using easy_install and after installation, i tried to use spynner but it give me an error with crashing...
Here's what i've got

import spynner
br = spynner.Browser()
br.load("http://www.google.com")
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\spynner\browser.py", line 1674, in createRequest
    url = six.u(toString(request.url()))
  File "C:\Python27\lib\site-packages\six.py", line 589, in u
    return unicode(s.replace(r'\', r'\\'), "unicode_escape")
TypeError: decoding Unicode is not supported

On my Windows 7 64bit Ultimate and Python 2.7.8 64bit
I tried 32bit python also but gave me same error.
Anyone can solve this errror?

A: I had the same problem. My immediate solution was to edit the u() method of the six module.
Originally it was:
def u(s):
    return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")

I changed it to:
def u(s):
    try:
        return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
    except TypeError as e:
        if "decoding Unicode is not supported" in str(e):
            return unicode(s.replace(r'\\', r'\\\\'))

It's just a workaround. Hope it helps.

A: My co-worker found solution.
Changing installation method.

*

*Install Python

*Download setuptools, spynner

*Install setuptools using ez_setup.py

*Install spynner

*Install PyQt4

Maybe PyQt4 should be installed at last


text:
Q: Flink: ProcessWindowFunction I am recently studying ProcessWindowFunction in Flink's new release. It says the ProcessWindowFunction supports global state and window state. I use Scala API to give it a try. I can so far get the global state working but I do no have any luck to make it for the window state. What I'm doing is to process system logs and count the number of logs keyed by hostname and severity level. I would like to calculate the difference in log count between two adjacent windows. Here is my code implementing ProcessWindowFunction.
class LogProcWindowFunction extends ProcessWindowFunction[LogEvent, LogEvent, Tuple, TimeWindow] {
  // Create a descriptor for ValueState
  private final val valueStateWindowDesc = new ValueStateDescriptor[Long](
    "windowCounters",
    createTypeInformation[Long])

  private final val reducingStateGlobalDesc = new ReducingStateDescriptor[Long](
    "globalCounters",
    new SumReduceFunction(),
    createTypeInformation[Long])

  override def process(key: Tuple, context: Context, elements: Iterable[LogEvent], out: Collector[LogEvent]): Unit = {
    // Initialize the per-key and per-window ValueState
    val valueWindowState = context.windowState.getState(valueStateWindowDesc)
    val reducingGlobalState = context.globalState.getReducingState(reducingStateGlobalDesc)
    val latestWindowCount = valueWindowState.value()
    println(s"lastWindowCount: $latestWindowCount ......")
    val latestGlobalCount = if (reducingGlobalState.get() == null) 0L else reducingGlobalState.get()
    // Compute the necessary statistics and determine if we should launch an alarm
    val eventCount = elements.size
    // Update the related state
    valueWindowState.update(eventCount.toLong)
    reducingGlobalState.add(eventCount.toLong)
    for (elem <- elements) {
      out.collect(elem)
    }
  }
}

I always get 0 value from the window state instead of the previous updated count it should be. I've been struggling with such problem for several days. Can someone please help me to figure it out? Thanks.

A: The scope of the per-window state is a single window instance. In the case of your process method above, every time it is called a new window is in scope, and so the latestWindowCount is always zero.
For a normal, vanilla window that is only going to fire once, per-window state is useless. Only if a window somehow has multiple firings (e.g., late firings) can you make good use of the per-window state. If you are trying to remember something from one window to the next, then you can do this with the global window state.
For an example of using per-window state to remember data to use in late firings, see slides 13-19 in Flink's advanced window training.


text:
Q: Multiple Functions and Plots in Manipulate with multiple parameters prod[k_, a_] := a*k^0.5;
depr[k_, d_] := d*k;
Manipulate[
 Column[{
   Plot[prod[k, a], {k, 0, 10}, PlotRange -> {0, 10}],
   Plot[prod[k, a]/k, {k, 0, 10}, PlotRange -> {0, 10}]}],
 {a, 1, 5}]

How do you add the function $depr[k,a]$ in the upper graph? And in the lower graph $depr[k,a]/k$? $d$ should appear with controls to manipulate the value.
I also want to add a function which is a fraction of the $prod[k,a]$-function as $s*prod[k,a]$ with $0<s<1$ in the upper and $s*prod[k,a]/k$ in the lower graph.
$s$ should appear with controls to manipulate the value aswell.

A: If I understand you correctly; you don't necessarily want a and s to take the same values in each of the plots. I'm not a big Manipluate user, so there may well be a better way, but the following should get you pretty close:
Column[{Manipulate[
   Plot[{prod[k, a], depr[k, a], s prod[k, a]}, {k, 0, 10},
    PlotRange -> {0, 10}], {a, 1, 5}, {s, 0, 1}],
  Manipulate[
   Plot[{prod[k, a]/k, depr[k, a]/k, s prod[k, a]/k}, {k, 0, 10},
    PlotRange -> {0, 10}], {a, 1, 5}, {s, 0, 1}]}]

Basically, make the Manipulates and put them in a Column rather than trying to Manipulate a Column of plots.


text:
Q: How can I sort alphanumeric strings in Unix? I have a list of table names, which are out of order. How can I get them in the correct logical order?

$ cat list.txt

TAB1
TAB13
TAB11
TAB19
TAB2
TAB3
TAB16
TAB17
TAB18
TAB9
TAB10
TAB8
TAB12
TAB20

$ cat list.txt | sort -n

TAB1
TAB10
TAB11
TAB12
TAB13
TAB16
TAB17
TAB18
TAB19
TAB2
TAB20
TAB3
TAB8
TAB9

Expected order:
TAB1
TAB2
TAB3
TAB8
TAB9
TAB10
TAB11
TAB12
TAB13
TAB16
TAB17
TAB18
TAB19
TAB20

Any vim short-cuts will also do, I do not necessarily need a separate utility for this.

A: Since this is tagged as a Vim question, I figured it might be worth mentioning the Vim option (even though I would personally use sort since the data's already in a file). It's simply
:sort n

Since Vim's numeric sort ignores up to the first decimal number, one doesn't need to ignore the "TAB" (:sort can take a pattern to ignore, :sort n /TAB/ would work as well, for example). As usual, :h :sort for more information.

A: You can always perform sort with argument -V to sort alphanumeric string..
$ sort -V inputfile > outputfile

$ cat inputfile
TAB1
TAB13
TAB11
TAB19
TAB2
TAB3
TAB16
TAB17
TAB18
TAB9
TAB10
TAB8
TAB12
TAB20

$ cat outputfile
TAB1
TAB2
TAB3
TAB8
TAB9
TAB10
TAB11
TAB12
TAB13
TAB16
TAB17
TAB18
TAB19
TAB20

A: You need to tell it where your sorting key starts:
sort -n -k1.4 list.txt

Otherwise it starts from the beginning, fails to convert a string to a number and falls back to alphabetical comparison.

A: You can do this in Perl or any language where sort lets you specify a comparison operator:
sub numcomp() {
 $a =~ /([0-9]*)$/; $aa = $1;
 $b =~ /([0-9]*)$/; $bb = $1;
 $aa <=> $bb;

}
sort numcomp @mylist...

(Don't bother telling me it's baby Perl. I... um, I wrote it that way on purpose so it would be easy to understand.)
(Don't bother telling me it's wrong. I... um, I wrote it that way on purpose as an exercise for the reader.)


text:
Q: Как остановить уже запущенный ранее таймер? Никак не могу разобраться как остановить уже запущенный таймер.
Смысл в том, что я хочу при повторном нажатии на кнопку сбрасывать предыдущий таймер, и запускать новый. Но у меня запускается одновременно два таймера.
Я попытался объявить переменную timer глобальной, но все равно вне объекта её тип является 'undefined'. Я только начал изучать JS, помогите, пожалуйста.

var buttonOne = document.querySelector('.go');

function Timer(selector, time){

  var elem = document.querySelector(selector);
  window.timer = 0;
  var object = this;

  this.start = function() {
    timer = setInterval(this.tick, 1000);
  }

  this.stop = function() {
    clearInterval(timer);
  }

  this.tick = function() {
    if (time > 0) {
      time--;
      var hours = Math.floor(time / 3600);
      var minutes = Math.floor((time - (3600 * hours))/60);
      var seconds = time - hours * 3600 - minutes * 60;
      text = hours + ':' + minutes + ':' + seconds;
      document.querySelector('.time').innerHTML = text;
    } else {
      object.stop;
    }
  }
}

buttonOne.onclick = function(){
  var userInput = document.querySelector('.seconds');
  var time = userInput.value;
  if (typeof(timer) != "undefined") {
  timer.stop();
 }
  var timer = new Timer('.time', time)
  timer.start();
}
<input class="seconds" value="10">
<button class="go">GO!</button>

A: Проблема несрабатывания условия заключается во всплытии переменных в пределах функции.
При использовании var возможно обращение к переменной до ее инициализации. При этом значением переменной будет undefined.
Это означает, что в следующем коде
if (typeof(timer) != "undefined") {
    timer.stop();
}
var timer = new Timer('.time', time)

В пределах функции выражение в операторе if всегда будет false, так как проверяется именно локальная переменная, которая инициализируется после условия, а значит в момент проверки всегда undefined.

Решить проблему можно простым переименованием (во всех местах использования глобальной переменной) и прямым вызовом clearInterval
if (typeof(timerId) != "undefined") {
    clearInterval(timerId)
}

Так как в глобальную переменную timer на самом деле сохраняется id таймера, а не создаваемый объект.

A: Ошибок много.

*

*Зачем вам глобальная переменная для интервала, если его можно отлично сохранить в классе?

*setInterval(this.tick, 1000); в принципе нормально, но я бы заменил на setInterval(object.tick, 1000);

*text = hours + ':' + minutes + ':' + seconds; Переменная text не объявлена и попадает либо в глобальную область видимости, либо вызывает ошибку. Оно вам надо?

*document.querySelector('.time').innerHTML = text; тут две ошибки

*

*Вы игнорируете переданный снаружи селектор

*У вас уже есть поле elem, соответствующее этому селектору

*object.stop; это не вызов функции. Вызов функции должен быть таким object.stop();

*if (typeof(timer) != "undefined")
  timer.stop();
var timer = new Timer('.time', time);

Проверили нет ли объекта timer в области видимости и создали локальный объект.
Итого:

var buttonOne = document.querySelector('.go');

function Timer(selector, time){
  var elem = document.querySelector(selector);
  var timer = 0;
  var object = this;

  this.start = function() {
    timer = setInterval(object.tick, 1000);
  }

  this.stop = function() {
    clearInterval(timer);
  }

  this.tick = function() {
    if (time > 0) {
      time--;
      var hours = Math.floor(time / 3600);
      var minutes = Math.floor((time - (3600 * hours))/60);
      var seconds = time - hours * 3600 - minutes * 60;
      var text = hours + ':' + minutes + ':' + seconds;
      elem.innerHTML = text;
    } else {
      object.stop();
    }
  }
}

var timer;

buttonOne.onclick = function(){
  var userInput = document.querySelector('.seconds');
  var time = userInput.value;
  if (typeof(timer) != "undefined") {
    timer.stop();
  }
  timer = new Timer('.time', time);
  timer.start();
}
<input class="seconds" value="10">
<button class="go">GO!</button>

A:

var buttonOne = document.querySelector('.go');

function Timer(selector, time){

  var elem = document.querySelector(selector);
  window.timer = 0;
  var object = this;

  this.start = function() {
    timer = setInterval(this.tick, 1000);
  }

  this.stop = function() {
    clearInterval(timer);
  }

  this.tick = function() {
    if (time > 0) {
      time--;
      var hours = Math.floor(time / 3600);
      var minutes = Math.floor((time - (3600 * hours))/60);
      var seconds = time - hours * 3600 - minutes * 60;
      text = hours + ':' + minutes + ':' + seconds;
      document.querySelector('.time').innerHTML = text;
    } else {
      object.stop;
    }
  }
}

buttonOne.onclick = function(){
  var userInput = document.querySelector('.seconds');
  var time = userInput.value;
  if (typeof(timer) != "undefined") {
        timer.stop();
    }
  var timer = new Timer('.time', time)
  timer.start();
}
<input class="seconds" value="10">
<button class="go">GO!</button>


text:
Q: extensions of lebesgue measure The Hahn-Banach theorem implies that Lebesgue measure can be extended give a "measure" on all subsets of [0,1], but this measure is only guaranteed to be finitely additive.  It might magically turn out that this measure is countably additive, but this can only happen if the continuum is a real-valued measurable cardinal, a strong set-theoretic assumption.  My question is: if it turns out that measure is countably additive on the measure zero sets, does this imply that the measure is countably additive everywhere?

A: The answer is no. A proof can be found here.

A: Note that even if the measure is only finitely additive, the ideal of null sets will still be countably saturated. The usual arguments involving Ulam matrices, such as can be found in Jech (Chapter 10) or other texts on set theory, show that if there is a countably additive, countably saturated ideal on some set then there is a weakly inaccessible cardinal. Hence, if no such cardinal exists then, as Emil has corrected me, the Hahn-Banach extension of Lebesgue measure will be countably additive on Lebesgue null sets but not on all nulls. This does not answer your question, but does show that the weaker hypothesis still requires large cardinals.
By the way, you may want to look at the paper by Joan Hart and Ken Kunen titled "Weak Measure Extension Axioms" in Topology and Applications 85 (1998) 219-246 to see what can be said about extensions of measures to measure certain sets.


text:
Q: In vim, how does one apply autocommands for a filetype to a region of a file? I've got a kind of polyglot filetype that can have embedded C, python, ruby, etc in it (think 'wiki page' if it helps). Is there a way to execute the autocommands for a known filetype on a region of the file?
For example, I might have:
#!bash
if [ a = b ]; then
   echo 'equal'
fi

#!python
if a = b:
    print('equal')

And I want to apply bash filetype autocommands to the first part and python filetype autocommands to the latter part.
I can get just syntax hilighting by defining a region using this method, but I don't understand autocommands enough to be able to apply them in a similar way.

A: Doing this automatically is challenging, as the filetype settings are buffer-local; Vim has no notion of regions, so :autocmds need to be used, as you've correctly stated.
Quick and easy
With a plugin like NrrwRgn - A Narrow Region Plugin similar to Emacs, you can clone regions to separate scratch buffers; the plugin automatically syncs them back on write. Each buffer can be given a separate filetype via :setf.
An even simpler approach is to define some mappings to quickly switch filetypes:
:nnoremap <Leader>fp :setf python<CR>
:nnoremap <Leader>fs :setf sh<CR>

Really separate regions in a single buffer
The sketch of this is easy:
:autocmd CursorMoved,CursorMovedI <buffer> if line('.') >= 6 | setf python | else | setf sh | endif

This relies on each filetype plugin doing proper cleanup (or overriding all relevant options).
How to determine the regions
You certainly don't want to specify the line numbers explicitly as in the sketch above. My OnSyntaxChange plugin might help, in case you have / can define proper syntax regions for each block.


text:
Q: add blank space before image I'm drawing two images, one on top and one in the bottom, and I want them to be aligned. One of them has some extra blank space one its left side, so I need to realign it manually:
\begin{minipage}{9em}
    \includegraphics[height=3em]{images/img1.png} \\
    \includegraphics[height=3em]{images/img2.png}
\end{minipage}

I tried to add \hspace{some_number} to either one of them to see the effect, but nothing happened. What should I use?
Thanks.

A: You can use \hspace*{-<length>} to move one of the images to the left (or a postive amount to move to the right) to compensate for the extra space in the image itself:

Code:
\documentclass{article}
\usepackage[demo]{graphicx}% Remove demo option for real use.

\begin{document}
\begin{minipage}{9em}
    \includegraphics[height=3em]{images/img1.png} \\
    \hspace*{-1ex}\includegraphics[height=3em]{images/img2.png}
\end{minipage}
\end{document}

A: \includegraphics of package graphicx knows option trim=<left> <bottom> <right> <top>. Default unit is bp:
\includegraphics[trim=10 0 0 1mm]{img.png}% trims 10bp from the left and 1mm from the top

Or crop the image with image editing software.


text:
Q: Implementing Gson caused error in my build My app was building and running fine previously, but then when I implemented Gson in my gradle, it gave me an error while building
My app's gradle:
apply plugin: 'com.android.application'

android {

    compileSdkVersion 27
    buildToolsVersion "27.0.3"

    defaultConfig {
        applicationId "com.google.sample.cloudvision"
        minSdkVersion 24
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        buildTypes.each {
            it.buildConfigField 'String', 'API_KEY', "\"AIzaSyDHRKU5yH5Tc-IphIYL3TwkSG58uah6e3I\""
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:design:27.1.1'
    implementation 'com.google.api-client:google-api-client-android:1.23.0' exclude module: 'httpclient'
    implementation 'com.google.http-client:google-http-client-gson:1.23.0' exclude module: 'httpclient'
    implementation 'com.google.apis:google-api-services-vision:v1-rev369-1.23.0'
    implementation 'com.google.code.gson:gson:2.8.6'
}

Before adding in that last implementation line, everything was ok.
And when I tried building, it gave an error at "Execute task action 5/5 for :app:transformClassesWithDesugarForDebug"
I'd post the error message here but it exceeded the character count limit, not sure how I can do that
Edit: fixed. Changed to
android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

and
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'


text:
Q: Akka in a nutshell I'm triying to figure out how to work with Akka in Scala. Did I get it right that, what I need to do is instead of this:
class Class1 {
  def someMethod1 = {
    //.... some operations....
    "someStringData"
  }

  def someMethod2(param1: Int, param2: Double, param3: BigInt) = {
    //.... some operations....
    new someClass
  }
}

//.............................
object Application extends App {
  val c = new Class1
  val stringData = c.someMethod1
  val someClass = c.someMethod2
}

I must do this:
case object SomeMethod
case class SomeClass(a: Int, b: Double, c: BigInt)
case class SomeReturnClass(d: Boolean)

class Class1 extends Actor{
  def receive = {
    case SomeMethod => {
      //.... some operation....
      sender ! "someStringData"
    }

    case SomeClass(a, b, c) => {
     //...some operations....
     val result: Boolean = ..... // some operations....
     sender ! new SomeReturnClass(result)
    }
  }
}

//.............................

object Application extends App {
  val system = ActorSystem("HelloSystem")
  val helloActor = system.actorOf(Props[Class1], name = "helloactor")
  val stringData: String = helloActor ! someMethod1
  val someClass: SomeReturnClass = helloActor ! someMethod2
}

A: You have got the basic idea right, the only error is in how you try to get the actor's answer: for that please have a look at the ask pattern. Actors are like "active objects" in a sense, but not every object should be translated into an actor; it is not uncommon to use plain object composition when implementing actors.


text:
Q: Deprecated data when getting longtext from mysql. (php/mysql) I'm using php to retrieve long text files from a mysql database. These files are pdfs encoded into base64 strings. The strings work perfectly fine in the database and produce the pdf I desire, but when I retrieve the data through php there is always a large block of characters missing in the middle of the string.
I've tried this with multiple different strings and it keeps giving me the same result, a large block of characters missing in the middle of the string. Any help would be appreciated.
Here is the code I'm using, my mistake. At the moment I'm just printing the string onto the screen.
    <?php

// Make sure an ID was passed
if(isset($_GET['id'])) {
// Get the ID
    $id = intval($_GET['id']);

    // Make sure the ID is in fact a valid ID
    if($id <= 0) {
        die('The ID is invalid!');
    }
    else {
        // Connect to the database
        $dbLink = new mysqli('***', '***', '***', '***');
        if(mysqli_connect_errno()) {
            die("MySQL connection failed: ". mysqli_connect_error());
        }

        // Fetch the file information
        $query = "SELECT name, data FROM report_storage WHERE `id` = {$id}";
        $result = $dbLink->query($query);

        if($result) {
            // Make sure the result is valid
            if($result->num_rows == 1) {
            // Get the row
                $row = mysqli_fetch_assoc($result);

                // Print headers

                // Print data
                $data = $row['data'];

                //echo strlen($data);
                echo $data;
            }
            else {
                echo 'Error! No image exists with that ID.';
            }

            // Free the mysqli resources
            @mysqli_free_result($result);
        }
        else {
            echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
        }
        @mysqli_close($dbLink);
    }
}
else {
    echo 'Error! No ID was passed.';
}
?>


text:
Q: Program to search for substring in 8086 assembly language does not work Here's my code so far. For some reason I always get NOT FOUND message on running.
I have to check whether a certain substring (HELL) is present in the main string (HELLO). How do I fix my code?
.model small

COMPARE MACRO
LEA DI,SUBSTR
MOV CL,LENSUB
CLD
REPE CMPSB
JZ FOUND
ENDM

.data
STR DB "HELLO"
LENSTR DB $-STR
SUBSTR DB "HELL"
LENSUB DB $-SUBSTR
MSG1 DB "FOUND$"
MSG2 DB "NOT FOUND$"

.code
MOV AX,@Data
MOV DS,AX
MOV CL,LENSTR
LEA SI,STR
UP:
PUSH SI
PUSH CX
COMPARE
POP CX
POP SI
INC SI
LOOP UP

LEA DX,MSG2
UP1:
MOV AH,09H
INT 21H
JMP LAST

FOUND:
LEA DX,MSG1
JMP UP1

LAST:
MOV AH,4CH
INT 21H
END

A: Your COMPARE macro code will never (?) jump to FOUND because of a few errors in your program:

*

*You have setup the DS segment register but since the REPE CMPSB instruction also uses the ES segment register, you still need to setup that one also.
MOV AX, @Data
MOV DS, AX
MOV ES, AX

*The REPE prefix expects to find the repetition count in the CX register, yet you only store a count in the CL register.
LEA DI, SUBSTR
MOV CL, LENSUB
MOV CH, 0
...
...
...
MOV CL, LENSTR
MOV CH, 0
LEA SI, STR

Concerning the LOOP UP instruction!
Since a substring can only appear a limited number of times in the bigger string, you can't just loop for the total length of the bigger string. A correct count is LENSTR-LENSUB+1. Here you have 5-4+1 giving 2 as the correct value to store in CX.
HELLO

HELL            1st is correct
 ELLO           2nd is correct
  LLO?          3rd is wrong
   LO??         4th is wrong
    O???        5th is wrong


text:
Q: read data from HDFS root folder and append it to the Spark DF I am reading JSON files from a HDFS folder in Spark Scala
Code:
val path = "hdfs://year/month/date/*"
var df = spark.read.format("json").load(path)

So it reads all the part--JSON files in the date folder.
But I want to read all the JSON files in the year folder and append it to the DF. Any suggestions please.

A: val path = "hdfs://year/*/*/*"
var df = spark.read.format("json").load(path)

This worked.


text:
Q: Form response blank I have some google script that generates an initial form then gathers a number does a lookup and then is supposed to return a second form (getfamily function). The second form which is dynamically generated returns blank. I can see the formHTML variable with data in the logger, but it comes up blank in the browser. Any suggestions would be appreciated.
var ssID="xxx";

var rows = SpreadsheetApp.openById(ssID).getSheetByName("studentinfo").getDataRange().getValues();

function doGet() {
    var html = HtmlService.createTemplateFromFile('index2').evaluate()
    .setTitle('Lookup').setSandboxMode(HtmlService.SandboxMode.NATIVE);
    return html;
};

function getfamily(form){
    Logger.log(form.familyid);
    var ssID="xxxx";
    var rows = SpreadsheetApp.openById(ssID).getSheetByName("studentinfo").getDataRange().getValues();
    var formHTML = "<!DOCTYPE html>";
    formHTML +="Hello!";
    formHTML += '<form id="students">';

    var filteredRows = rows.filter(function(row){
        var message="made it";
        if (row[0] === form.familyid) {
            Logger.log(row[2]);
            formHTML+= '<input type="checkbox" name ="students value='+ row[1] + '">'+ row[2] + '
';
            return row[2];
        }
    });

    formHTML+='<input type="submit" value="CheckIn">';
    formHTML+='</form>';
    Logger.log(formHTML);
    var output = HtmlService.createHtmlOutput(formHTML).setSandboxMode(HtmlService.SandboxMode.NATIVE);
    return output;
};

A: Your input type="checkbox" line is hard to figure out what you want.  I presume that you plan in insert this form into an already exist DOM so no need the worrying about other tags just stick it in whatever div you have prepared for it.
function getfamily(form){
  var ssID="xxxx";
  var rows = SpreadsheetApp.openById(ssID).getSheetByName("studentinfo").getDataRange().getValues();
  var formHTML='<form id="students">';
  var message="made it";
  rows.forEach(function(row){
    if (row[0]==form.familyid) {
      formHTTML=Utilities.formatString('<input type="checkbox" name="students" value="%s" />
',row[2]);//I presume that you want to change the name but I cant tell how you planned to do it.
    }
  });
  formHTML+='<input type="button" value="CheckIn" onClick="proceesForm(this.parentNode);" />';
  formHTML+='</form>';
  return HtmlService.createHtmlOutput(formHTML);
};

You can use submit if you really must but I find using google.script.run to be a lot easier. We need to see more of what you're doing to provide a complete answer.