text:
Q: Send post request to salesforce in java I have requirement that I need to fetch the data form salesforce DB. My input Ids would be more than 1000+. Hence I would like to pass this list of Ids in post method.
GET method is failing since it exceeds the limit.
Can someone help me on this?

A: I'm assuming from your question that some (but not all) GET requests to SalesForce are already working, so you already have most of the code needed to talk to SalesForce and you just need the gaps filling on how to make a POST request instead of a GET request.
I hope the following code provides some demonstration of this.  Note that it is  untested as I don't presently have access to a SalesForce instance to test it against:
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicNameValuePair;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class HttpPostDemo {

    public static void main(String[] args) throws Exception {

        String url = ... // TODO provide this.

        HttpPost httpPost = new HttpPost(url);
        // Add the header Content-Type: application/x-www-form-urlencoded; charset=UTF-8.
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.withCharset(StandardCharsets.UTF_8).getMimeType());

        // Construct the POST data.
        List<NameValuePair> postData = new ArrayList<>();
        postData.add(new BasicNameValuePair("example_key", "example_value"));
        // add further keys and values, the one above is only an example.

        // Set the POST data in the HTTP request.
        httpPost.setEntity(new UrlEncodedFormEntity(postData, StandardCharsets.UTF_8));

        // TODO make the request...
    }
}

It is perhaps worth pointing out that in essence the code isn't much different to that in a related question which appears in the sidebar.


text:
Q: Angular 2+: Best way to inject large amounts of input data into an application at init time? Imagine that you're developing a simple Angular 4 app which is not a SPA – it's just a widget that adds UI sugar to an HTML form. For the purposes of this question, let's say that it allows the user to edit a restaurant menu.
The usual approach, as I understand it, is this:

*

*The user agent requests the URL /menus/173/edit, and downloads an HTML page containing a <menu-editor menuId="173"></menu-editor> tag, and a <script> tag which loads the transpiled Angular module.

*The app initializes, binds to the DOM, and resolves the value of the menuId input as 173.

*The app then issues a second HTTP request to /api/menus/173 to retrieve the menu details and populate the form.
I'm hoping to eliminate step 3, for the sake of load time / performance.
Is there a best practice for including the menu details in the original page load, and getting that data into my <menu-editor></menu-editor> component?
Of course, I could do something like this:
<menu-editor [menuDetails]="{ id: 174, categories: [ ... ] }"></menu-editor>
...but that feels a little wrong, somehow (especially if the JSON object is large). Is there a tried-and-true way of injecting "inline" data into an Angular 2+ app?
I understand that this approach isn't appropriate for every situation. I'm just looking for ways to improve performance in this specific case (an Angular app which simply adds a rich UI to an otherwise ordinary HTML form).

A: Angular 4+ framework is not designed to cooperate in standard html application. By Angular 4+, you can write only application, no component to be used into html pages. To accomplish your task, i suggest you to use look other libraries/framework like AngularJS or JQuery.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP 5.2 Notice: Use of undefined constant __DIR__ - assumed '__DIR__ In php 5.3 or less it'll provide an error like the following:
Notice: Use of undefined constant __DIR__ - assumed '__DIR__

It's because i'm using the magic constant __DIR__. Is there an alternative to using __DIR__ in 5.3 or less??
Here's the code that's causing it:
<?php
/**
 * Load template files
 *
 * $files   Contains alphabetized list of files that will be required
 */
$files = array(
  'elements.inc',
  'form.inc',
  'menu.inc',
  'theme.inc',
);

function _zurb_foundation_load($files) {
  $tp = drupal_get_path('theme', 'zurb_foundation');
  $file = '';

  // Workaround for magic constant; for now because of php 5.2 issue
  // http://drupal.org/node/1899620#comment-6988766
  if( !defined( __DIR__ ) )define( __DIR__, dirname(__FILE__) );

  // Check file path and '.inc' extension
  foreach($files as $file) {
    $file_path = __DIR__ .'/inc/' . $file;
    if ( strpos($file,'.inc') > 0 && file_exists($file_path)) {
      require_once($file_path);
    }
  }
}

_zurb_foundation_load($files);

A: Use the old trick:
dirname(__FILE__)

But if possible, update to a newer version of PHP.


text:
Q: Firestore: handling concurrency with booking app I've currently got a bookings and a bookable collection. Each document in bookings holds a date range (check-out and check-in) and an array of references to bookable documents.
I'm a bit stumped at how to guarantee two overlapping bookings for the same bookables aren't written at the same time. From what I understand I can't technically lock a collection via something like a transaction, so I'm wondering what my options are (perhaps restructuring how I'm storing data, etc).
Any pointers or advice would be much appreciated.
EDIT:
Say User A wants to make a booking for the same two items as User B does and for the same time range. They both load the booking UI at around the same time and confirm their selection.
Prior to creating a new document inside the bookings collection for each of their requests, the app would perform a get query to check for any overlaps and if none exist insert the new booking documents. That fraction of time between the app's check for overlaps across the booking collection and the creation of new documents is what seems to open up a window for inconsistencies (e.g. potentially allowing two documents with overlapping time ranges and items to be created).
Could a transaction help prevent a new document being written to a collection based the existance of other documents in that collection that fit a specific criteria?

A: To prevent users from accidentally overwriting each other's data, you'll want to use a transaction.
To prevent users from intentionally overwriting each other's data, you'll want to use security rules. Key to this is to use the information that you want to be unique as the ID of the documents.
So say you identify time slots by the date and start time, you could have a document ID "20210420T0900". If a user is trying to write to that document when it already exists, you can reject that write in the security rules of your database.

A: I am facing the exact same problem, and here is my best option at the moment....
I need a collection of all booking (bookingscollection), regardless of date, time, resource booked etc. This collection is usabale in many parts of my UI, as I list upcoming bookingss etc.
I need to avoid writes being made to this collection, where there is an overlap.
I am considering adding an additional collection, where each document descibes the bookings for a specific resource on a specific day (lockcollection). It could be a doc, with the resource id, the date it covers and an array of start,stop times of booking already made.
Then when considering adding a new booking to my bookingscollection, I would make a transaction to the relevant document in the lockcollection, see if there is an overlap in which case I would fail, and if not, I would add the new intervall to the lock document within the transaction.
Once this succeed, I know that I can  just plainly add the booking to the booking collection, as the lock is already there....
Similar logic would be applied to the procedure of deleting or changing bookings.
This idea is new to me, but I wanted to sahre, so I can hear your inputs....?


text:
Q: How to keep a dot drawn on canvas at a fixed point on screen, even when the canvas is pinch zoomed? - Android I have a background image as a drawable in my custom view. This drawable may be pinch zoomed or moved.
Currently I need a green dot that is drawn on the image to be stationary relative to the screen. That is, it should be always at the same position with the pin as shown below. (Of course, the pin is simply an ImageView and does NOT move at all!)

I have successfully made it stationary relative to the screen, when the map behind is moved as follows in my custom view, MapView:
@Override
    public boolean onTouchEvent(MotionEvent ev) {
        // Let the ScaleGestureDetector inspect all events.
        mScaleDetector.onTouchEvent(ev);

        final int action = ev.getAction();
        switch (action & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN: {
            final float x = ev.getX();
            final float y = ev.getY();

            mLastTouchX = x;
            mLastTouchY = y;
            mActivePointerId = ev.getPointerId(0);
            break;
        }

        case MotionEvent.ACTION_MOVE: { // triggered as long as finger movers
            final int pointerIndex = ev.findPointerIndex(mActivePointerId);
            final float x = ev.getX(pointerIndex);
            final float y = ev.getY(pointerIndex);

            // Only move if the ScaleGestureDetector isn't processing a gesture.
            if (!mScaleDetector.isInProgress()) {
                final float dx = x - mLastTouchX;
                final float dy = y - mLastTouchY;

                mPosX += dx;
                mPosY += dy;

                // update the starting point if the 'Start' button is not yet pressed
                // to ensure the screen center (i.e. the pin) is always the starting point
                if (!isStarted) {
                    Constant.setInitialX(Constant.INITIAL_X - dx);
                    Constant.setInitialY(Constant.INITIAL_Y - dy);
                    if ((historyXSeries.size() > 0) && (historyYSeries.size() > 0)) {
                        // new initial starting point
                        historyXSeries.set(0, Constant.INITIAL_X);
                        historyYSeries.set(0, Constant.INITIAL_Y);
                    }
                }

                invalidate();
            }

            mLastTouchX = x;
            mLastTouchY = y;

            break;
        }

By doing that above, my green dot stays there, when the background image is moved.
But I have problems in trying to make it stay there, when the background image is zoomed.
Essentially, I don't really understand how canvas.scale(mScaleFactor, mScaleFactor) works, and therefore I cannot move the green dot accordingly like what I have done in the simple moving case.
I think something should be added in the scale listener handler below, could anybody help me fill that part?
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();

            // Don't let the object get too small or too large.
            mScaleFactor = Math.max(1f, Math.min(mScaleFactor, 10.0f)); // 1 ~ 10

            // HOW TO MOVE THE GREEN DOT HERE??

            invalidate();
            return true;
        }

Or please at least explain how canvas.scale(mScaleFactor, mScaleFactor) works, and how may I move the green dot accordingly?

A: Keep in mind that the canvas is thought to scale everything according to the scale factor, so while going against the zoom is possible, it is probably not the best approach.  However, if this is what you're looking for, I will help you as best as I can.
I am assuming the following:

*

*Scale factor is relative to the current zoom (old zoom is always scale factor 1).  If this is not the case, then you should observe the zoom values after scaling roughly 200% two times and seeing if the resulting scale factor is 4 or 3 (exponential or linear).  You can achieve the results below by normalizing the scale factor to 2 for a zoom factor of 200%, for example.  You'll have to remember the old scale factor in order to do so.

*No rotation is performed

If this is the case then following can be said for a marker with respect to the zoom center.
For every horizonal pixel x away from the zoom center after zoom, its original position could be calculated to be:  zoom_center_x + *x* / scale_factor (or alternatively zoom_center_x + (marker_x - zoom_center_x) / scale_factor).  In other words, if zoom center is (50, 0) and the marker is (100, 0) with a scale factor of 2, then the x position of the marker prior to the zoom was 50 + (100 - 50) / 2 or 75.  Obviously, if the marker is in the same position of the zoom center, then the x position will be the same as the zoom center.  Similarly, if the scale is 1, then the x position for the marker will be the same as it is now.
The same can be applied to the y axis.
While I can't know exactly how to set the position of your marker, I would expect the code to look something like:
Point zoomCenter = detector.getZoomCenter();
// Set marker variable here
marker.setX(Math.round(zoomCenter.getX() + ((double)(marker.getX() - zoomCenter.getX())) / mScaleFactor));
marker.setY(Math.round(zoomCenter.getY() + ((double)(marker.getY() - zoomCenter.getY())) / mScaleFactor));

I hope that helps.


text:
Q: Trying to get a better understanding of ViewModel with MVC I am trying to understand how the binding works with MVC.
Say I have this model.
public class MyObjectModel
{
        public int MyID { get; set; }
        public string Name { get; set; }
        public string Add1 { get; set; }
        public string City { get; set; }
}

In my case I have a controller that just returns a View(). (No model).
However in my view I have grid that makes a call back to the controller and returns a list. List<MyObjectModel> listObject
Now in this grid each row is a MyObjectModel.  So the user goes and either creates or modifies a MyObjectModel object.
When the user clicks save there is a post method.
[AcceptVerbs(HttpVerbs.Post)]
public void CreateMyObject([DataSourceRequest] DataSourceRequest dsRequest, MyObjectModel obj)
{
    if (ModelState.IsValid)
    {
        // Go update the database
    }
}

How does the binding work from initially sending the data to the view and from the view back to the controller?  Can I manually manipulate (via Jquery) the MyObjectModel prior to posting it back to the controller?
Obviously I am having an issue passing data back to the controller, but if had a better understanding how the binding work in general I should hopefully be able to learn as well as resolve my issue.

A: MyObjectModel only ever exists on the server.
You use its properties to help generate HTML text via a View (blahblah.cshtml). The View will usually have a form, and (via the eerie, inhuman magic of the HtmlHelper stuff) the form fields will be given values in their attributes based on properties in MyObjectModel. Then the server sends that HTML as text (a long series of zeroes and ones) through a wire to the client browser.
On the client, the browser renders the HTML page you send it. In that page, there may be JavaScript, which can manipulate form fields in the page, but it can't touch any C# code that exists in a different computer on the other side of the Internet.
When the user submits the form, the browser posts form field values, in the form of text (another long sequence of zeroes and ones) back to the server, which creates a brand new fresh instance of MyObjectModel and initializes it with the form field values from the client, and hands it to your Controller method.
Based on my past exposure to the term "view model", it isn't the right term to use with MVC (note: Some people use the term with MVC. That's a new one on me, but I think I may wish they'd picked a different term to refer to the concept they're talking about). The term "view models" is usually used in environments like WPF, where the UI and the models exist in the same memory space, so you can have a live .NET class instance that interacts with both. You can't do that in a web application like MVC where your model lives on the server. In MVC, if you wanted something to be analagous to a view model, it would have to be written in JavaScript and run on the client.
It's important in web programming to always be cognizant of which code is on the server and which is on the client. Writing server code in C# and client code in JavaScript is a big help in that regard, I find. I've done a little classic ASP and it was too easy to get disoriented, when both ends were written in JavaScript.
You can of course write a full AJAX web application with a view model on the client, and have it use the server as a data store that it talks to via web services. But that's not what you're doing in the MVC code you included in your question.


text:
Q: opening and closing balance query I'm trying to figure out the opening and closing balance based on the customer and their daily wise cr/dr transaction.
closing= opening+db -cr  and
opening should the closing of previous date and if no previous records is available for that customer it should 0.
create table pj_test_cr_dr(
    cst_name varchar2(100),
    txn_dt number(8),
    cr_amt number(22,7),
    dr_amt number(22,7)
    );

insert into pj_test_cr_dr
    values ('c1', to_char(sysdate-5,'yyyymmdd'),200,0);
insert into pj_test_cr_dr
    values ('c1', to_char(sysdate-5,'yyyymmdd'),300,0);
insert into pj_test_cr_dr
    values ('c1', to_char(sysdate-5,'yyyymmdd'),0,2000);
insert into pj_test_cr_dr
    values ('c1', to_char(sysdate-4,'yyyymmdd'),100,0);
insert into pj_test_cr_dr
    values ('c1', to_char(sysdate-4,'yyyymmdd'),400,0);
insert into pj_test_cr_dr
    values ('c1', to_char(sysdate-4,'yyyymmdd'),0,2000);
insert into pj_test_cr_dr
    values ('c1', to_char(sysdate-3,'yyyymmdd'),2000,2000);
insert into pj_test_cr_dr
    values ('c1', to_char(sysdate-3,'yyyymmdd'),4000,2000);
insert into pj_test_cr_dr
    values ('c1', to_char(sysdate-2,'yyyymmdd'),5000,0);
commit;

select  cst_name, txn_dt, sum(dr_amt) dr,sum(cr_amt) cr
    from pj_test_cr_dr
    group by cst_name, txn_dt
    order by 1,2;

query output

expected result :

Regards

A: Here is one way to do this - all in one query (no subqueries) and only with analytic functions (not mixing with aggregates - other than selecting distinct which is needed because there may be multiple transactions per day).
select distinct cst_name, txn_dt,
         coalesce( sum(dr_amt - cr_amt) over (partition by cst_name order by txn_dt
             range between unbounded preceding and 1 preceding), 0 )       as op_bal,
         sum(dr_amt) over (partition by cst_name, txn_dt)                  as daily_dr,
         sum(cr_amt) over (partition by cst_name, txn_dt)                  as daily_cr,
         sum(dr_amt - cr_amt) over (partition by cst_name order by txn_dt) as cl_bal
from     pj_test_cr_dr
order by cst_name, txn_dt   --   if needed
;

CST_NAME     TXN_DT     OP_BAL   DAILY_DR   DAILY_CR     CL_BAL
-------- ---------- ---------- ---------- ---------- ----------
c1         20170131          0       2000        500       1500
c1         20170201       1500       2000        500       3000
c1         20170202       3000       4000       6000       1000
c1         20170203       1000          0       5000      -4000

A: Try this:
select
    cst_name,
    debit,
    credit,
    lag(closing,1,0) over (partition by cst_name order by txn_dt) opening,
    closing
from (
    select
        cst_name,
        txn_dt,
        sum(dr_amt) debit,
        sum(cr_amt) credit,
        sum(sum(dr_amt - cr_amt)) over (partition by cst_name order by txn_dt) closing
    from pj_test_cr_dr
    where txn_dt > 20170130
    group by cst_name, txn_dt
) t;

Also notice the partition by cst_name. I think you want to keep values of different customers separate.


text:
Q: dataprep.eda TypeError: Please provide npartitions as an int, or possibly as None if you specify chunksize Struggling to understand this TypeError coming out of the dataprep package. My setup is very simple and as follows:
import pandas as pd
import numpy as np

df = pd.DataFrame(
    {
        "phone": [
            "555-234-5678",
            "(555) 234-5678",
            "555.234.5678",
            "555/234/5678",
            15551234567,
            "(1) 555-234-5678",
            "+1 (234) 567-8901 x. 1234",
            "2345678901 extension 1234",
            "2345678",
            "800-299-JUNK",
            "1-866-4ZIPCAR",
            "123 ABC COMPANY",
            "+66 91 889 8948",
            "hello",
            np.nan,
            "NULL",
        ]
    }
)

from dataprep.clean import clean_phone
clean_phone(df, "phone")

The resulting error message gets thrown in the terminal (I've omitted file paths and replaced sensitive values with x for security purposes) :
Traceback (most recent call last):
  File "c:\Users\x\x\Documents\Repositories\test.py", line 14, in <module>
    clean_phone(df, "phone")
  File "C:\Users\x\Anaconda3\envs\myenv\lib\site-packages\dataprep\clean\clean_phone.py", line 150, in clean_phone
    df = to_dask(df)
  File "C:\Users\x\Anaconda3\envs\myenv\lib\site-packages\dataprep\clean\utils.py", line 73, in to_dask
    return dd.from_pandas(df, npartitions=npartitions)
  File "C:\Users\x\Anaconda3\envs\myenv\lib\site-packages\dask\dataframe\io\io.py", line 236, in from_pandas
    raise TypeError(
TypeError: Please provide npartitions as an int, or possibly as None if you specify chunksize.

This is a direct attempt to replicate the tutorial shown by the dataprep package team found at: https://docs.dataprep.ai/user_guide/clean/clean_phone.html
The expected output is below, as per the tutorial:
Expected output.
Posting this as the TypeError only shows one semi-relevant result when Googled.

A: There is a small bug in dataprep package, you can track it in this PR.
In the meantime, one option to avoid the bug is to explicitly convert data to a dask dataframe and pass that into the function:
import numpy as np
import pandas as pd
from dask.dataframe import from_pandas
from dataprep.clean import clean_phone

df = pd.DataFrame(
    {
        "phone": [
            "555-234-5678",
            "(555) 234-5678",
            "555.234.5678",
            "555/234/5678",
            15551234567,
            "(1) 555-234-5678",
            "+1 (234) 567-8901 x. 1234",
            "2345678901 extension 1234",
            "2345678",
            "800-299-JUNK",
            "1-866-4ZIPCAR",
            "123 ABC COMPANY",
            "+66 91 889 8948",
            "hello",
            np.nan,
            "NULL",
        ]
    }
)

# to avoid the bug we are passing ddf, not df
ddf = from_pandas(df, npartitions=2)
clean_phone(ddf, "phone")


text:
Q: How to record network throughput per port for long period of time I have come across vnstat recently, and am enjoying it's simplicity, low resource usage, and its ability to record network history long term.
However, I am looking for a similar tool (for long term archival history), which can record the amount of traffic through network ports.
Ultimately, I'd like to be able to view the data in a way that shows me:

*

*most used TCP/UDP port (e.g. Ports sorted by most bytes TX, or RX)

*most used TCP/UDP port (e.g. Ports sorted by most number of packets)

*amount of bytes and/or packets transmitted on that port over "X" period of time (days, months, hours)

*ability to exclude certain ports (e.g. http:80)

I would prefer a non-GUI tool. Wireshark and similar are too bulky for my needs.

Progs I've tried

*

*bandwidthd

*bmon

*bwm, bwm-ng

*dstat

*ifstat

*ifstatus

*iftop

*iperf/netperf/uperf

*iptrack

*nethogs

*nload

*strobe

*tcptrack

A: Darkstat serves my purposes nicely. However, I have found that version 3.0.715 works better than 3.0.717.


text:
Q: how do I loop through an arraylist of winforms? I am currently developing a windows form application and I have a arraylist notificationList that contains notificationForms.
How do I use a for loop to loop through every single form in the arrayList to check if the forms are disposed through the isDisposed property?
int formDisposed = 0;

for (int i = 0; i < notificationList.Count; i++)
{
    if(notificationList.?????.IsDisposed == true)
    {
      formDisposed ++;
    }
}

Thanks!

A: Usually by using
if(notificationList[i].IsDisposed)

if for some reason you don't have this option: add the following line to your .cs file
using System.Data;

and Syste.Data and Syste.Data.DataSetExtensions so you will able to access xxx.ElementAt(i) method.
You can also use foreach:
int formDisposed = 0;

foreach (Form f in notificationList)
{
    if(f.IsDisposed)
      formDisposed ++;
}

A: ArrayLists are indexable with square brackets (notificationList[i]), but this isn't going to work without a cast to your type. ArrayList returns the type Object and Object does not implement IsDisposed. You may want to consider using a Generic List of Controls (List<Control>) instead, which would work the same but not need a cast.


text:
Q: Why are my DVD disks in the wrong format? I'm trying to play DVDs on my MacBook Pro however the disk doesn't play it doesn't even mount.
When I check Disk Utility it shows the format as Windows NTFS 3G.
If I try the same disks on another macbook it shows as Universal Disk Format (UDF) and plays fine.  How do I fix this?

A: It appears Parallels is the cause of the issue.  Found some instructions on paragon-software.com and executed step 1. DVDs now working great!


text:
Q: How to pass parameters dynamically in PHP? I need to pass the $route to its inner function,but failed:
function compilePath( $route )
{
    preg_replace( '$:([a-z]+)$i', 'pathOption' , $route['path'] );
    function pathOption($matches)
    {
        global $route;//fail to get the $route
    }
}

I'm using php5.3,is there some feature that can help?

A: I don't think you can do anything like that in PHP 5.2, unfortunatly -- but as you are using PHP 5.3... you could use Closures to get that to work.

To begin, here's a quick example of using a Closure :
function foo()
{
    $l = "xyz";
    $bar = function () use ($l)
    {
        var_dump($l);
    };
    $bar();
}
foo();

Will display :
string 'xyz' (length=3)

Notice the use keyword ;-)

And here's an example of how you could use that in your specific case :
function compilePath( $route )
{
    preg_replace_callback( '$:([a-z]+)$i', function ($matches) use ($route) {
        var_dump($matches, $route);
    } , $route['path'] );
}

$data = array('path' => 'test:blah');
compilePath($data);

And you'd get this output :
array
  0 => string ':blah' (length=5)
  1 => string 'blah' (length=4)

array
  'path' => string 'test:blah' (length=9)

A couple of notes :

*

*I used preg_replace_callback, and not preg_replace -- as I want some callback function to be called.

*I'm using an anonymous function as callback

*And that anonymous function is importing $route, with the new use keyword.

*

*Which means that, in my callback function, I can access both the matches, which are always passed by preg_replace_callback to the callback function, and the $route.

A: Put everything in a class, including the callback and grab $route using $this->route instead of using globals. You should be using preg_replace_callback(). To use a callback from a class use Array($class,'callback') or Array('className','callback).


text:
Q: Create Special Reports I've a situation, I google it and found a lot of data but isn't clear for me how I should accomplish what I want.
I've a DB (SQL server 2014 enterprise) with 1TB size.
There are customers that needs special reports that the application doesn't offer.
I've another server that daily restores a backup from prodution DB (copy the last backup, Drop current db, and restore the backup)
My idea is use this server for reporting, since there are some of the "special reports" that are very expensive for the production database.
I have readed some of Integration Services and Reporting Services, and I think that one possible solution could be:
Synchronize the Report Server one time a day (or hour, or two hours...).
On this report server, maintain some transformed data  for the reports (indexed views or some precalculated data). Since if I create this indexed views on production server, it will be a big impact on performance.
¿Is this possible to accomplish?
¿Is my idea correct? ¿or there are another way more efficient/correct?
I want your opinions and advises before break my head doing this.
Thanks!

A: Yes it is possible to do what you are suggesting.   An even more efficient/correct way of doing this would be with Replication, but that requires additional expenses, so it may not be an option for you.

A: You have a few options here, I'd do some research on them before implementing. Log shipping, replication, drop and reload, ssas, etc... If you have lots of pre-calculated data requirements, definitely check out SSAS for reporting needs.


text:
Q: Detect input device type .NET I'm writing a C# application in .NET 4. In the application I have 2 text boxes - one is used for user input, the other one is used for input from USB scanner. Is there some way to detect from which device the input comes - from keyboard or scanner (the scanner sends the characters from the barcode and Enter in the end). Is there any way to achieve this. So far I've tried to catch it in the text boxes onKeyDown onKeyPress triggers but without success. I get only the characters.
I guess I have to look somewhere in the reflection but I don't find anything since 3 days.
Thanks,
Mihail

A: The barcode scanner will usually supply characters much faster than a human can type, usually every 10 milliseconds or so. An inelegant but effective solution is override OnKeyDown or OnKeyPress and, if the last event occurred a short time ago, treat it as a sequence of characters entered by the barcode scanner.


text:
Q: How to plot a graph of actual vs predict values in python?           Original      Predicted
0           6            1.56
1           12.2         3.07
2           0.8          2.78
3           5.2          3.54
.

Code that I have tried:
def plotGraph(y_test,y_pred,regressorName):
    if max(y_test) >= max(y_pred):
        my_range = int(max(y_test))
    else:
        my_range = int(max(y_pred))
    plt.scatter(y_test, y_pred, color='red')
    plt.plot(range(my_range), range(my_range), 'o')
    plt.title(regressorName)
    plt.show()
    return

Graph that I just wanted:

But my current output:

A: The problem you seem to have is that you mix y_test and y_pred into one "plot" (meaning here the scatter() function)
Using scatter() or plot() function (which you also mixed up), the first parameter are the coordinates on the x-axis and the second parameter are the coordinates on the y-axis.
So 1.) you need to one scatter() with only y_test and then one with only y_pred. To do this you 2.) need either to have 2D data, or as it seems to be in your case, just use indexes for the x-axis by using the range() functionality.
Here is some code with random data, that might get you started:
import matplotlib.pyplot as plt
import numpy as np

def plotGraph(y_test,y_pred,regressorName):
    if max(y_test) >= max(y_pred):
        my_range = int(max(y_test))
    else:
        my_range = int(max(y_pred))
    plt.scatter(range(len(y_test)), y_test, color='blue')
    plt.scatter(range(len(y_pred)), y_pred, color='red')
    plt.title(regressorName)
    plt.show()
    return

y_test = range(10)
y_pred = np.random.randint(0, 10, 10)

plotGraph(y_test, y_pred, "test")

This will give you something like this:

A: You are plotting the y_test on x axis and y_pred on y axis.
And what you want to have is a common data point on x axis and y_test and y_pred both on Y axis.
And following snippet below will help you achieve that.
(where true_value and predicted_value are your lists to be plotted and common is your list from your dataframe used as common x axis.)
    fig = plt.figure()
    a1 = fig.add_axes([0,0,1,1])
    x = common
    a1.plot(x,true_value, 'ro')
    a1.set_ylabel('Actual')
    a2 = a1.twinx()
    a2.plot(x, predicted_value,'o')
    a2.set_ylabel('Predicted')
    fig.legend(labels = ('Actual','Predicted'),loc='upper left')
    plt.show()

A: I can not simulate your code, but I have seen some points at the first glance. First of all, data points in the graph you wanted are normalized. You need to divide the all data points in col by the maximum value of this col.
You should also check the legend function in the documentation to add legend like the graph you wanted.

A: In matplotlib (from the code I assume you're using it) documentation there is an information for matplotlib.pyplot.scatter function, first two parameters are:

x, y : float or array-like, shape (n, )
The data positions.

So for your application you need to draw two scatterplots on the same graph - using matplotlib.pyplot.scatter twice. First with y_test as y and color='red', second with y_pred as y and color='blue'
Unfortunately, you didn't provide information what you x values for y_test and y_pred, but you will need those as well to define x in your plt.scatter function calls.
Drawing two scatter plots is slightly tricky, and as this answer says it requires a reference to an Axes object. For example (as given in the answer):
import matplotlib.pyplot as plt

x = range(100)
y = range(100,200)
fig = plt.figure()
ax1 = fig.add_subplot(111)

ax1.scatter(x[:4], y[:4], s=10, c='b', marker="s", label='first')
ax1.scatter(x[40:],y[40:], s=10, c='r', marker="o", label='second')

Take a look at the matplotlib documentation and the mentioned answer for more details.


text:
Q: Iterate over nth row of a dataframe I have a csv file which is a single column of data. I need to split this into three separate columns through iterating through every third term. E.g.
My single column is currently of the format:
A
B
C
A
B
C
A
B
C

I need three columns containing A, B, and C. My plan was to iterate through the single column three times and cast this to 3 lists. How do I go about iterating every third term to do so? E.g. how do I incorporate [::3] into the for loop below?
import pandas as pd

df = pd.read_csv('Names+grades.txt')
initial = []
name = []
job=[]

for index, row in df.iterrows():
    initial.append(row['Raw data'])

Thanks for any help that you can provide.

A: df = pd.read_csv('Names+grades.txt')
pd.DataFrame({'A': df[::3], 'B': df[1::3], 'C': df[2::3]})

A: you can split each dataframe with integer slicing and just re-concat each part.
df_new = pd.concat([df.iloc[::3].reset_index(drop=True)
           ,df.iloc[1::3].reset_index(drop=True)
           ,df.iloc[2::3].reset_index(drop=True)],axis=1)

df_new.columns = ['A','B','C']

print(df_new)

   A  B  C
0  A  B  C
1  A  B  C
2  A  B  C


text:
Q: Installing Android ADT and Aptana studio plugins into Workbench My question is a dual to this one.
I use Workbench 2.0, but I am now interested in developing some Android Apps and Html projects.
In order to do that, I need to install Android ADT and Aptana studio plugins into Eclipse.
Questions:

*

*Since Workbench is based on Eclipse I wonder if I can install these plugins into WB.

*Is it possible and/or wiser to simply install a (newer) version of Eclipse in a parallel folder and install the plugins into this Eclipse? Would this interfere somehow with the existing Workbench?

I realize this question is not strictly about Mathematica, but I believe it might be of some interest for many Workbench users, as they explore other languages.


text:
Q: Will a browser make the AJAX if window.location is changed immediately I have the following scenario

Use Case : I want to do a bookkeeping of how many times a particular link on a web page  is clicked. Note that the landing page is not owned by me. I was thinking to making an ajax call and simultaneously navigating to the new URL.
I am basically wondering if any browser would not even make the ajax call and navigated to the new URL. My assumption is that the browser could still be in the process of preparing the ajax request object and navigating to the new URL made the browser to not fire the ajax request.
Can there be such cases?
Note that I am not worried if the ajax response is in error.

A: to be on a save way put your redirect into a success handler of the ajax call !
jQuery.ajax{
   url : 'some serverside bookkeeping handler',
   type : post,
   data : ajaxData
   success: function(){   window.location = 'Some new URL'; }
};

or use  to open a new tab in the browser if you can.

A: seems like it is impossible. The window.location line executed before ajax response reurns.  When window.location changes, all the ajax requests from the previous domain are canceled. Try this fiddle: http://jsfiddle.net/Vfk3S/8/ and look at "Network" tab in devtool.


text:
Q: Alsa Headers not found in Ubuntu 9.04 I want to run my programs which I was running in Fedora core 6 which uses alsa apis, In FC6 I had alsa headers in /usr/include/alsa folder. In Ubuntu 9.04, I search whole file system but cant find alsa headers like asoundlib, asoundef.h, input.h, output.h, etc.
Please tell me how can I get it?
Answer,
do sudo aptitude install libasound2-dev

A: I would say do a
sudo aptitude install libasound2-dev


text:
Q: Heat pump is a refrigerator? There is the following problem in a textbook on Thermodynamics:

A heat pump is an electrical device that heats a building by pumping heat in from the cold outside. In other words, it's the same as a refrigerator, but its purpose is to warm the hot reservoir rather than to cool the cold reservoir (even though it does both).

I have a hard time understanding the principal difference between a heat pump and a refrigerator. In a refrigerator, heat is drawn from a cold substance into the refrigerator cabin and then excess heat is pumped out of the device.
Now, in the case of a heat pump, heat is also pumped from a "cold substance" (the cold outside) and it goes into the "cabin" (the building interior). But then how does the building get heated and not refrigerated? I'm really confused by this problem statement, it couldn't be less clear.

A: The principal difference between a heat pump and a refrigerator is a matter of perspective. A heat pump is simply a refrigerator where the inside of the refrigerator is outside the house. In other words, a heat pump attempts to cool down the air outside the building, and in the process heats up the air inside the building.
Put differently, a refrigerator is simply a heat pump which takes heat from inside the refrigerator and transfers it outside the refrigerator.

A: I think that part of your confusion stems from the fact that the statement you highlighted is rather poorly phrased.  A couple of fact that might clarify things:
1.) a heat pump is a fancy science word for any refrigeration device or unit, be it a kitchen refrigerator, air conditioner, "swamp box" or anything else.  I'm not sure why the author of the quote is drawing some kind of difference between a refrigerator and a heat pump.  (Somebody correct me if I'm wrong on this point).
2.)  Somewhere in your quote, the author seems confused about how "heat pumps" are normally configured.  Every "heat pump" I've ever seen in the real world was used to cool off a room or the inside of a freezer, etc.
3.)  Lastly, every device whose authentic purpose was to heat a room was called a heater.  (My sarcasm is aimed at the author of the quote, not you SEQUENCE).  Granted, a traditional food refrigerator may incidentally heat a room up by cooling off the inside of the "cabin", but this is incidental, and should be presented as such.
I agree that the author couldn't be less clear.  The author seems to need to re-write this section of the book.

A: Although other people focused on the fact that when performing a single operation they are essentially the same, no-one has pointed out that heat pumps are often built to be reversible, i.e. they can be used both to cool down and to warm up an environment (they are easily switchable between those two configurations). Refrigerators are built to perform just that function.
See also the relevant Wikipedia article on heat pumps.
In particular this excerpt (emphasis mine):

Heat energy naturally transfers from warmer places to colder spaces. However, a heat pump can reverse this by absorbing heat from a cold space and releasing it to a warmer one. Heat is not conserved in this process and requires some amount of external energy such as electricity. In heating, ventilation and air conditioning (HVAC) systems, the term heat pump usually refers to vapor-compression refrigeration devices optimized for high efficiency in both directions of thermal energy transfer. These heat pumps can be reversible, and work in either direction to provide heating or cooling to the internal space.

Bottom line: from an engineering perspective, an heat pump can be easily reconfigured either to warm up or cool down the conditioned area, whereas a refrigerator can't.

A: Before answering the question let's talk about the word "efficiency".
In the meaning we care about here the word is used to described the effectiveness with which some consumed resource is converted into some desired effect. In the context of thermodynmanic engines, refrigerators and heat pumps the desired outcome and the available resource are one of

*

*heat moved between the warm source and the mechanism

*heat moved between the cold source and the mechanism

*work (done by or on the mechanism)

all three of which are denominated in terms of energy, so we use a ratio
$$ \text{efficiency} = \frac{\text{desired outcome (in energy)}}{\text{resource used(in energy)}} \;.$$
In an engine we feed energy in (heat from the hot reservoir to the engine, and get work out, so
$$ \text{efficiency}_\text{engine} = \frac{\text{work done}}{\text{heat supplied}} \;.$$
In the case of a either refrigerator or a heat pump supplied work is the resource used up, but the desired outcome varies: for refrigeration you care about heat removed from the cold source, while in a heat pump you care about the heat added to the hot source. (For historical reasons we also use the phrase "coefficient of performance" instead of "efficiency", here.)
\begin{align*}
\text{CoP}_\text{refrigerator} &= \frac{\text{heat removed}}{\text{work supplied}} \\
\\
\text{CoP}_\text{heat pump} &= \frac{\text{heat supplied}}{\text{work supplied}} \;.
\end{align*}
So, to finally put the answer in words, the only difference is what you are trying to accomplish.


text:
Q: How do I vertically align my links for a navbar? I am trying to make a navigation bar but I'm not sure how to line up the li and a tags vertically. How can I do this?

#navbar {
    font-weight: bold;
    display: block;
    background-color: #000;
}

li {
    float: left;
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #000;
}

li a {
    color: white;
    vertical-align: middle;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover {
    background-color: #111;
}

HOME

MY WORK

HIRE ME

PROJECTS

A: One of the common ways nowadays is to do it with the Flexbox:

#navbar {
  font-weight: bold;
  display: block;
  background-color: #000;
}

ul {
  display: flex; /* displays flex-items (children) inline */
  align-items: center; /* centers them vertically */
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #000;
}

li {
  float: left;
}

li a {
  color: white;
  vertical-align: middle;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  background-color: #111;
}

/* addition */
img {display: block} /* or: "vertical-align: middle" // removes bottom margin/whitespace */

HOME

MY WORK

HIRE ME

PROJECTS


text:
Q: How to access from Twig to the underlying object in an embedded form in a Symfony project In a medical record project developed with Symfony 2.7.7 I have to track the outcome of supplementary medical examinations. These can have many typology of outcomes according to the type of exam done. In particular, the parameters to take into consideration can be the following:

*

*normal/altered;

*positive/negative;

*value.

For this reason I have done an entity SupplementaryMedicalExamination in this way:
class SupplementaryMedicalExamination extends MedicalExamination
{
    /**
     * @var string $examination
     *
     * @ORM\Column(type="string", length=255, nullable=false)
     *
     */
    private $examination;

    /**
     * @var bool $hasNormalOrAlteredEvaluation;
     *
     * @ORM\Column(name="has_normal_or_altered_evaluation", type="boolean", nullable=false)
     *
     */
    private $hasNormalOrAlteredEvaluation;

    /**
     * @var bool $hasNegativeOrPositiveEvaluation
     *
     * @ORM\Column(name="has_negative_or_positive_evaluation", type="boolean", nullable=false)
     *
     */
    private $hasNegativeOrPositiveEvaluation;

    /**
     * @var bool $hasValue
     *
     * @ORM\Column(name="has_value", type="boolean", nullable=false)
     *
     */
    private $hasValue;
}

A MedicalRecord entity has a one to many relationship with supplementary examinations.
/**
 * AppBundle\Entity\HealthData\MedicalRecord
 *
 * @ORM\Table(name="medical_record")
 * @ORM\Entity(repositoryClass="MedicalRecordRepository")
 * @ORM\HasLifecycleCallbacks
 */
class MedicalRecord
{
    //other stuff

    /**
     * @var ArrayCollection $supplementaryExaminations
     *
     * @ORM\OneToMany(targetEntity="\AppBundle\Entity\HealthData\MedicalRecordSupplementaryExamination", mappedBy = "medicalRecord")
     */
    protected $supplementaryExaminations;

    //other stuff
}

And the MedicalRecordSupplementaryExamination should contain the outcomes of each supplementary examination.
/**
 * AppBundle\Entity\HealthData\MedicalRecordSupplementaryExamination
 *
 * @ORM\Table(name="medical_record_supplementary_examination")
 * @ORM\Entity()
 * @ORM\HasLifecycleCallbacks
 *
 */
class MedicalRecordSupplementaryExamination
{
    /**
     * @var int $id
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     */
    private $id;

    /**
     * @var bool $isAltered
     *
     * @ORM\Column(name="is_altered", type="boolean")
     */
    protected $isAltered;

    /**
     * @var bool $isPositive
     *
     * @ORM\Column(name="is_positive", type="boolean")
     */
    protected $isPositive;

    /**
     * @var string $alterations
     *
     * @ORM\Column(type="string", length=255)
     */
    protected $alterations;

    /**
     * @var float $value
     *
     * @ORM\Column(type = "decimal", precision = 10, scale = 2)
     */
    protected $value;

    /**
     * @var MedicalRecord $medicalRecord
     *
     * @ORM\ManyToOne(targetEntity="medicalRecord", inversedBy = "supplementaryExaminations")
     * @ORM\JoinColumn(name="medical_record_id", referencedColumnName="id")
     */
    protected $medicalRecord;

    /**
     * @var SupplementaryMedicalExamination $supplementaryExamination
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\HealthData\Core\SupplementaryMedicalExamination")
     * @ORM\JoinColumn(name="supplementary_examination_id", referencedColumnName="id")
     */
    protected $supplementaryExamination;
}

In the MedicalRecordType, I include the MedicalRecordExamination as a collection and in the MedicalRecordController I add in the MedicalRecord object many instance of MedicalRecordSupplementaryExamination according to the SupplementaryExamination available.
The problem is that I would like to show in the template the right form fields according to the type of outcome of the MedicalSupplementaryExamination.
I would like to do something like this but I don't know how because at this level I'm working with a FormView instance and I can't access the underlying object:
{% for supplementaryExamination in form.supplementaryExaminations %}
    {% if supplementaryExamination.hasNormalOrAlteredEvaluation == true %}
        {{ form_row(supplementaryExamination.isAltered) }}
    {% endif %}
{% endfor %}

I have seen this post: How to access an underlying object from a Twig's FormView in a template? but I can't understand how to apply this solution to my case.
Thank you

A: Referring from the doc on how rendering form in the twig template:

You can access the current data of your form via form.vars.value:

So, in your case, you can try this:
{% if supplementaryExamination.vars.value.supplementaryExamination.hasNormalOrAlteredEvaluation == true %}

instead of this:
{% if supplementaryExamination.hasNormalOrAlteredEvaluation == true %}

Hope this help


text:
Q: Scrollview delegate method also call while scrolling collection view I have done this code to get current page while scrolling view and there is a UICollectionView on the bottom of the screen.
Problem is, when I am scrolling scroll view it's working fine but this method also working while scrolling UICollectionView.
func scrollViewDidScroll(_ scrollView: UIScrollView){
        let pageNo = round(scrollView.contentOffset.x / scrollView.frame.size.width)
        print(pageNo)
        if pageNo == 0.0{
            changebackColor()
            dignosticView.backgroundColor = UIColor().HexToColor(hexString: "FC6614", alpha: 1.0)
            dignosticView.layer.borderColor = UIColor().HexToColor(hexString: "f68f56").cgColor
        }
        else if pageNo == 1.0{
            changebackColor()
            offerView.backgroundColor = UIColor().HexToColor(hexString: "FC6614", alpha: 1.0)
            offerView.layer.borderColor = UIColor().HexToColor(hexString: "f68f56").cgColor
        }
        else if pageNo == 2.0{
            changebackColor()
            alertView.backgroundColor = UIColor().HexToColor(hexString: "FC6614", alpha: 1.0)
            alertView.layer.borderColor = UIColor().HexToColor(hexString: "f68f56").cgColor
        }
    }

A: Yes because collection view is also scrollView. You can put if statement in the first line of scroll view delegate and do nothing if scrollView is from your collection view
if(scrollView != collectionView){
   //your code here
}


text:
Q: Describing Differences between Two Inferred Populations I am interested in the size of an animal in two populations, and found reliable estimates of the population provided by NOAA. The data was in the form of estimated total population within discrete size intervals, presented like so:
Size    Pop1     Pop1_Norm   Pop1_Cumul  Pop2    Pop2_Norm   Pop2_Cumul
21      584.14   1.15E-06    1.15E-06    5092.75 9.28E-05    9.28E-05
22      98365.15 0.000194238 0.000195391 503.38  9.18E-06    0.000102018
23      41899.32 8.27E-05    0.000278128 5723.3  0.000104337 0.000206355
...

Pop1 and 2 represent the number of individuals at a given size, the Norm columns represent the fraction of the total population, and the Cumul columns the cumulative proportion of individuals at or below the given size class. Unfortunately, I don't have access to the raw sample data, and so understand I can't do any inference myself.
However I'd still like to quantify the difference in the population distributions. What are the best methods for describing differences between two populations? Should I just take the difference of the means? What methodological problems do I face working with an estimate of the true population distribution?
I have graphed the cumulative size distributions of these populations, now how can I describe the difference?


text:
Q: Where is the memory leak in using StateT s IO a? Intention: Small application to learn Haskell: Downloads a wikipedia-article, then downloads all articles linked from it, then downloads all articles linked from them, and so on... until a specified recursion depth is reached. The result is saved to a file.
Approach: Use a StateT to keep track of the download queue, to download an article and to update the queue. I build a list IO [WArticle] recursively and then print it.
Problem: While profiling I find that total memory in use is proportional to number of articles downloaded.
Analysis: By literature I'm lead to believe this is a laziness and/or strictness issue. BangPatterns reduced the memory consumed but didn't solve proportionality. Furthermore, I know all articles are downloaded before the file output is started.
Possible solutions:
1) The function getNextNode :: StateT CrawlState IO WArticle (below) already has IO. One solution would be to just do the file writing in it and only return the state. It would mean the file is written to in very small chunks though. Doesn't feel very Haskell..
2) Have the function buildHelper :: CrawlState -> IO [WArticle] (below) return [IO WArticle]. Though I wouldn't know how to rewrite that code and have been advised against it in the comments.
Are any of these proposed solutions better than I think they are or are there better alternatives?
import GetArticle (WArticle, getArticle, wa_links, wiki2File) -- my own
type URL = Text

data CrawlState =
     CrawlState  ![URL]       ![(URL, Int)]
          --    [Completed]    [(Queue, depth)]
-- Called by user
buildDB :: URL -> Int -> IO [WArticle]
buildDB startURL recursionDepth = buildHelper cs
    where cs = CrawlState [] [(startURL, recursionDepth)]

-- Builds list recursively
buildHelper :: CrawlState -> IO [WArticle]
buildHelper !cs@(CrawlState _ queue) = {-# SCC "buildHelper" #-}
  if null queue
    then return []
    else do
      (!article, !cs') <- runStateT getNextNode cs
      rest <- buildHelper cs'
      return (article:rest)

-- State manipulation
getNextNode :: StateT CrawlState IO WArticle
getNextNode = {-# SCC "getNextNode" #-} do
  CrawlState !parsed !queue@( (url, depth):queueTail ) <- get
  article <- liftIO $ getArticle url
  put $ CrawlState (url:parsed) (queueTail++ ( if depth > 1
          then let  !newUrls  = wa_links article \\ parsed
                    !newUrls' = newUrls          \\ map fst queue
                    in zip newUrls' (repeat (depth-1))
          else []))
  return article

startUrl = pack "https://en.wikipedia.org/wiki/Haskell_(programming_language)"
recursionDepth = 3

main :: IO ()
main =  {-# SCC "DbMain" #-}
  buildDB startUrl recursionDepth
   >>= return . wiki2File
   >>= writeFile "savedArticles.txt"

Full code at https://gitlab.com/mattias.br/sillyWikipediaSpider. Current version limited to only download the first eight links from each page to save time. Without changing it download 55 pages at ~600 MB heap usage.
Thanks for any help!

A:
2) Is [IO WArticle] want I want in this case?

Not quite. The problem is that some of the IO WArticle actions depend on the result of a previous action: the links to future pages reside in previously obtained pages. [IO Warticle] can't provide that: it is pure in the sense that you can always find an action in the list without executing the previous actions.
What we need is a kind of "effectful list" that lets us extract articles one by one, progressively performing the neccessary effects, but not forcing us to completely generate the list in one go.
There are several libraries that provide these kinds of "effectful lists": streaming, pipes, conduit. They define monad transformers that extend a base monad with the ability to yield intermediate values before returning a final result. Usually the final result is of a type different from the values that are yielded; it might be simply unit ().
Note: The Functor, Applicative and Monad instances for these libraries differ from the corresponding instances for pure lists. The Functor instances map over the resulting final value, not over the intermediate values which are yielded. To map over the yielded values, they provide separate functions. And The Monad instances sequence effectful lists, instead of trying all combinations. To try all combinations, they provide separate functions.
Using the streaming library, we could modify buildHelper to something like this:
import Streaming
import qualified Streaming.Prelude as S

buildHelper :: CrawlState -> Stream (Of WArticle) IO ()
buildHelper !cs@(CrawlState _ queue) =
  if null queue
    then return []
    else do (article, cs') <- liftIO (runStateT getNextNode cs)
            S.yield article
            buildHelper cs'

And then we could use functions like mapM_ (from Streaming.Prelude, not the one from Control.Monad!) to process the articles one by one, as  they are generated.

A: Adding a further explaination and code building upon the answer of danidiaz. Here's the final code:
import Streaming
import qualified Streaming.Prelude as S
import System.IO (IOMode (WriteMode), hClose, openFile)

buildHelper :: CrawlState -> Stream (Of WArticle) IO ()
buildHelper cs@( CrawlState _ queue ) =
  if null queue
    then return ()
    else do
      (article, cs') <- liftIO (runStateT getNextNode cs)
      S.yield article
      buildHelper cs'

main :: IO ()
main = do outFileHandle <- openFile filename WriteMode
          S.toHandle outFileHandle  . S.show . buildHelper $
              CrawlState [] [(startUrl, recursionDepth)]
          hClose outFileHandle

outFileHandle is a usual file output handle.
S.toHandle takes a stream of String and writes them to the specified handle.
S.show maps show :: WArticle -> String over the stream.
An elegant solution that creates a lazy stream even though it is produced by a series of IO actions (namely downloading websites) and writes it to a file as results become available. On my machine it still uses a lot of memory (relative to the task) during execution but never exceeds 450 MB.


text:
Q: What are some GraphQL schema naming best practices? I'm beginning development on a nontrivial application for which we're considering GraphQL. When working on the initial draft of our schema, I've become a bit paralyzed trying to establish naming conventions that will scale as the product matures. I would really appreciate some insight from anyone who has had to grow a schema and run into, or successfully avoided dead ends or inconsistencies:

*

*Is it generally useful/idiomatic to keep the name "Interface" in the name of an interface? For example, would Profile or ProfileInterface be preferable in a large app?
interface ProfileInterface {
  # fields here...
}

type UserProfile implements ProfileInterface {
  # implemented fields here...
}

*Is it common to specify single-enum values as "constants"?
enum GeoJSONFeatureTypeConstant {
  feature
}

interface GeoJSONFeatureInterface {
  id: ID
  type: GeoJSONFeatureTypeConstant!
  geometry: GeoJSONGeometryInterface!
  properties: GeoJSONProperties
}

*Is it best practice to declare all-or-nothing objects as scalar or type, and where is the line drawn between the two? Imagine a Point type that is would typically be represented as an array [x,y]; which would be more idiomadic?
scalar Point

type Point {
  x: Float
  y: Float
}

*Any other best-practices specifically related to naming conventions or type declarations in GraphQL that would be difficult to know without experience.

Thanks in advance!

This question hasn't gained the momentum I would have liked, so I'm going to start posting useful snippets as I find them, which may evolve into an answer of sorts.

Naming input types with Input on the end is a useful convention,
  because you will often want both an input type and an output type that
  are slightly different for a single conceptual object.

http://graphql.org/graphql-js/mutations-and-input-types/

A: I found this graphql API design tutorial from Shopify some time ago. I think there is no explicit chapter but best practice w.r.t. naming convention spread across the tutorial.

A: I pondered about these same questions and I hope this will be helpful to you.
1. I don't believe that appending Interface at the end of every interface is idiomatic. It is much better to have a descriptive name instead. Consider the example provided in the GraphQL Specification relating to Interfaces. They don't append Interface to any of their types.
2. Enums are only advantageous when there are multiple related values. I don't see how including type is helpful when there is only one possible value. Enum values are also named with all caps and underscores per the GraphQL Specification relating to Enums.
3. If you decided to implement a scalar type then it is up to you to validate the field. In this specific case, providing Point as a type makes the most sense as a Point could be 2-D or 3-D. Defining it as a type is more declarative.
Values such as Date, Email and Url are common examples for scalar types. They provide semantic value and clients will know what to expect from these fields.
Here's the relevant section for custom scalars.
Here's an example.
4. You will find this article by Lee Byron helpful.


text:
Q: Can a GitHub codespace run indefinitely? I was wondering if we could configure a codespace to run indefinitely
and not time out when inactive

A: The docs state that the maximum is 4 hours:

Under "Default idle timeout", enter the time that you want, then click Save. The time must be between 5 minutes and 240 minutes (4 hours).


text:
Q: Class method inherits list from its previous execution (Python) See full working directory here: https://github.com/sharpvik/python-libs/tree/alpha/Testing
So I was working on some Graph theory and coding stuff in Python. I created a class called Graph as follows (don't worry about indentation, in the file itself it's fine):
class Graph:                                            # undirected graph; no values for the edges;
def __init__(self):
    self.nodes_counter = 0
    self.nodes_dict = dict()

def node_add(self, name):                           # name(int / str) -- name of the node;
    self.nodes_dict.update( { name : list() } )
    self.nodes_counter += 1
    return name

def node_del(self, name):                           # name(int / str) -- name of the node;
    self.nodes_dict.pop(name, None)
    for each in self.nodes_dict:
        self.nodes_dict[each].remove(name)
    self.nodes_counter -= 1
    return name

def connection_add(self, one, two):                 # one(int / str) and two(int / str) -- two nodes you want to connect;
    self.nodes_dict[one].append(two)
    self.nodes_dict[two].append(one)
    return [one, two]

def connection_del(self, one, two):                 # one(int / str) and two(int / str) -- two nodes you want to disconnect;
    self.nodes_dict[one].remove(two)
    self.nodes_dict[two].remove(one)
    return [one, two]

def nodes_count(self):                              # --> function returns the number of nodes in the graph;
    return self.nodes_counter

def nodes_return(self):                             # --> function returns the whole dict containing nodes and their connections;
    return self.nodes_dict

def node_return(self, name):                        # name(int / str) -- name of the node you're checking;
                                                    # --> function returns connections of the given node;
    return self.nodes_dict[name]

# search

## --> breadth first search using class Queue
def bfs( self, final, queue=Queue(None), checked=list() ):      # final(int / str) -- name of the node you're trying to establish connection with;
                                                                # queue(class Queue) -- Queue containing the element you are beginning with (format: element);
                                                                # checked(list) -- leave empty *** internal use ***;
                                                                # --> function returns True if the two nodes are connected, otherwise it returns False;
    if queue.length() == 0:
        return False
    temp = queue.pop()
    if temp == final:
        return True
    else:
        checked.append(temp)
        for child in self.node_return(temp):
            if child not in checked:
                queue.ins(child)
        return self.bfs(final, queue, checked)
## breadth first search using class Queue <--

## --> depth first serach using class Stack
def dfs( self, final, stack=Stack(None), checked=list() ):      # final(int / str) -- name of the node you're trying to establish connection with;
                                                                # stack(class Stack) -- Stack containing the element you are beginning with (format: element);
                                                                # checked(list) -- leave empty *** internal use ***;
                                                                # --> function returns True if the two nodes are connected, otherwise it returns False;
    if stack.length() == 0:
        return False
    temp = stack.pop()
    if temp == final:
        return True
    else:
        checked.append(temp)
        for child in self.node_return(temp):
            if child not in checked:
                stack.add(child)
        return self.dfs(final, stack, checked)
## depth first serach using class Stack <--

The bfs and dfs functions in the end rely on my other two classes:
class Stack:
def __init__(self, element):
    if isinstance(element, list):
        self.storage = element
    else:
        self.storage = [element]

def add(self, element):
    self.storage.append(element)
    return element

def pop(self):
    temp = self.storage[-1]
    self.storage.pop(-1)
    return temp

def length(self):
    return len(self.storage)

and
class Queue:
def __init__(self, element):
    if isinstance(element, list):
        self.storage = element
    else:
        self.storage = [element]

def ins(self, element):
    self.storage.insert(0, element)
    return element

def pop(self):
    temp = self.storage[0]
    self.storage.pop(0)
    return temp

def length(self):
    return len(self.storage)

Now, in another file I've initialized a new Graph that I called g for simplicitiy and tested on it.
print("BFS for 1 and 2 # --> should return True")
print( g.bfs(2, Queue(1) ), end="\n\n" )

print("BFS for 1 and 4 # --> should return True")    # but returns False!!!
print( g.bfs(4, Queue(1) ), end="\n\n" )

Now, when I started debugging it, I've noticed that the checked list that keeps track of checked nodes for some reason stays full of the nodes checked by the first call to the function, even though I have implicitly set it to be checked=list() in the def bfs(...) declaration so that it will be empty every time someone calls the function. This unusual behaviour causes it to not check the node 4 because it thinks that it had already been checked (checked = [1, 3, 4]), therefore the second time function decides that two nodes aren't connected and returns False.
This problem can be solved if I pass [] empty list after the Queue(1) like that:
print( g.bfs(4, Queue(1), [] ) )

However this would complicate things and I also just want to know why it does that anyways. So if anyone knows what the hell is happening here, I am looking forward to your response.


text:
Q: Timeline for availablity of azure search indexing on ADLS Gen2 Our team is heavily using ADLS gen2 to store our analytical data. We want to build azure search indexes on top of this data. But seems like currently azure search doesn't support indexing on ADLS Gen2. Is there any guidance on the timeline when it would be supported?

A: It is correct that we do not currently support ADLS Gen2 as a source for our Azure Search indexer.  This is in the works, however we do not have a timeline I can provide yet.
In the meantime, you can use our PUSH api to programmatically send content from it to Azure Search.

A: We have announced a public preview of an indexer that supports Azure Data Lake Storage Gen2 as a data source.
Request access to the preview here:
https://aka.ms/azure-cognitive-search/indexer-preview
More documentation on the preview indexer:
https://learn.microsoft.com/azure/search/search-howto-index-azure-data-lake-storage


text:
Q: Initializing StringBuffer with new operator inside a static method . is the stringbuffer reference thread safe? Does creating a StringBuffer testing= null;
testing = new StringBuffer("Thread Safe ");

inside a static method . Does the same reference of stringbuffer gets modified by thread every time in case multiple threads are calling the function at the same time.
public static StringBuffer test(String string) {
    StringBuffer testing = null;
    testing = new StringBuffer("Thread Safe ");
    return testing;
}


text:
Q: What is the best practice for selecting from two tables with multiple relations? I have two tables with a structure like below:

and am selecting the data with below query:
SELECT
(SELECT Name FROM Management_EnumerableItem ME WHERE ME.ID = DN) DN,
(SELECT Name FROM Management_EnumerableItem ME WHERE ME.ID = PN) PN,
(SELECT Name FROM Management_EnumerableItem ME WHERE ME.ID = Winder) Winder,
(SELECT Name FROM Management_EnumerableItem ME WHERE ME.ID = CouplingType) CouplingType,
(SELECT Name FROM Management_EnumerableItem ME WHERE ME.ID = Type) Type,
(SELECT Name FROM Management_EnumerableItem ME WHERE ME.ID = ILayer) ILayer,
(SELECT Name FROM Management_EnumerableItem ME WHERE ME.ID = OLayer) OLayer
FROM Product_Coupling_Serial

So,what is the best practice for the best performance of selects like that (fastest way)?

A: Create a covering index on Id column and Include Name on the table Management_EnumerableItem.
CREATE INDEX IDX_Name on Management_EnumerableItem (Id) Include (Name) with (fillfactor=90);

and write it like this.
SELECT A.NAME,
B.NAME,
C.NAME,
D.NAME,
E.NAME,
F.NAME,
G.NAME,

FROM Product_Coupling_Serial P
LEFT OUTER JOIN Management_EnumerableItem A
ON A.ID = P.DN
LEFT OUTER JOIN Management_EnumerableItem B
ON B.ID = P.PN
LEFT OUTER JOIN Management_EnumerableItem C
ON C.ID = P.Winder
LEFT OUTER JOIN Management_EnumerableItem D
ON D.ID = P.CouplingType
LEFT OUTER JOIN Management_EnumerableItem E
ON E.ID = P.[Type]
LEFT OUTER JOIN Management_EnumerableItem F
ON F.ID = P.[ILayer]
LEFT OUTER JOIN Management_EnumerableItem G
ON G.ID = P.[OLayer]

Thanks

A: Please consider trying out this query, and let me know how it performs.
WITH EnumerableItemNames AS (
   SELECT
      PcsID = pcs.ID,
      v.ColName,
      ItemName = me.Name
   FROM
      dbo.Product_Coupling_Serial pcs
      CROSS APPLY (VALUES
         ('DN', pcs.DN),
         ('PN', pcs.PN),
         ('Winder', pcs.Winder),
         ('CouplingType', pcs.CouplingType),
         ('Type', pcs.[Type]),
         ('ILayer', pcs.ILayer),
         ('OLayer', pcs.OLayer)
      ) v (ColName, EnumerableItemID)
      LEFT JOIN dbo.Management_EnumerableItem me
         ON v.EnumerableItemID = me.ID
)
SELECT
   p.DN, p.PN, p.Winder, p.CouplingType, p.[Type], p.ILayer, p.OLayer
FROM
   EnumerableItemNames ein
   PIVOT (
      Max(ein.ItemName)
      FOR ein.ColName IN (DN, PN, Winder, CouplingType, [Type], ILayer, OLayer)
   ) p
;

While it could theoretically be a total failure in performance, I also think it could end up performing better. If it isn't better, you still might be able to get it there by inserting the results of the CTE (without the LEFT JOIN to Management_EnumerableItem) into a temp table with some carefully-chosen indexes, then doing a second query using the temp table. It does depend a bit on how exactly you're querying the table, how many rows it has, how wide they are, how many result rows there are, and so on.
If you need more columns from the Product_Coupling_Serial table, then you could try including those in the CTE, but that may affect the performance badly by bloating the memory required for the pivot operation, so you could also just join back to it at the end:
// CTE here...
SELECT
   pcs.Year,
   pcs.ProductCode,
   pcs.QRText,
   pcs.UniqueSerial,
   ...
   p.DN, p.PN, p.Winder, p.CouplingType, p.[Type], p.ILayer, p.OLayer
FROM
   EnumerableIDs ei
   PIVOT (
      Max(ei.ItemName)
      FOR ei.ColName IN (DN, PN, Winder, CouplingType, [Type], ILayer, OLayer)
   ) p
   INNER JOIN dbo.Product_Coupling_Serial pcs
      ON ei.PcsID = pcs.ID
;

A: Although you can rewrite the query with a string of left joins, the performance will be the same as SQL Server will optimise the subqueries in your code into joins. (This may depend on the SQL Server version, and also on what other complexity you're adding into the final query. You can confirm using the execution plan.)
So the way you've done it is probably the best as it's the most easily understood.

A: You've already defined the primary key on Management_EnumerableItem as ID, which will by default created the clustered index on that column. Since the query you've written can use the clustered index on that table, it has no cause to use a non-clustered index.
There could, however, be performance benefits to creating clustered indexes on each of the joined columns in the Product_Coupling_Serial table. So:
CREATE INDEX IX_DN ON Product_Coupling_Serial (DN);
CREATE INDEX IX_PN ON Product_Coupling_Serial (PN);
CREATE INDEX IX_Winder ON Product_Coupling_Serial (Winder);
CREATE INDEX IX_CouplingType ON Product_Coupling_Serial (CouplingType);
CREATE INDEX IX_Type ON Product_Coupling_Serial ([Type]);
CREATE INDEX IX_ILayer ON Product_Coupling_Serial (ILayer);
CREATE INDEX IX_OLayer ON Product_Coupling_Serial (OLayer);

However, it would be best just to run your original query through SSMS to view the actual execution plan, which will return any missing indexes, to verify that those indexes will be used. But if you're feeling lucky you can just run the SQL I included above.
Next you'll want to rewrite your query in minimal form. SQL Server is a set based interpreted language, and the query optimizer is written in such a way that the minimal solution is either best, or gets automatically interpreted to the best solution in most cases. In your case the minimal form is:
SELECT
E1.NAME as DN,
E2.NAME as PN,
E3.NAME as Winder,
E4.NAME as CouplingType,
E5.NAME as [Type],
E6.NAME as ILayer,
E7.NAME as OLayer
FROM Product_Coupling_Serial P
LEFT JOIN Management_EnumerableItem E1 ON E1.ID = P.DN
LEFT JOIN Management_EnumerableItem E2 ON E2.ID = P.PN
LEFT JOIN Management_EnumerableItem E3 ON E3.ID = P.Winder
LEFT JOIN Management_EnumerableItem E4 ON E4.ID = P.CouplingType
LEFT JOIN Management_EnumerableItem E5 ON E5.ID = P.[Type]
LEFT JOIN Management_EnumerableItem E6 ON E6.ID = P.ILayer
LEFT JOIN Management_EnumerableItem E7 ON E7.ID = P.OLayer;

This should evaluate to the best possible execution plan with minimal code. If it does not you'll want to explore CTEs (Common Table Expressions) next, but it is unlikely you'll find anything faster than what I wrote. If you can upgrade your server to 2012 another possibility is the use of a Columnstore index, but since you listed 2088 R2 (which I assume is a typo for 2008 R2) you'll not be able to use that feature until you upgrade to 2012 or above.

A: You should create separate indexes on Product_Coupling_Serial for each column you use on your joins (DN, PN, Winder).Then both the subquery and the left joins will be faster.
You should consider the index size of the table and insert speed.
I don't think SQL server will use a covering index in this scenario because each column is queried separately.


text:
Q: Implementing localstorage Currently working on an e-commerce website, which is my first major project. I am, for the first time, implementing localstorage for the basket date (qty, items etc).
What I am trying to achieve is whenever the user clicks on the 'add to basket' button, the number beside the basket increases and displays. This is pretty straightforward but with localstorage I am obviously doing something wrong. I assume I am retrieving it incorrectly?
Please can you explain to me what I am doing wrong here as I want to get my head wrapped around how to use local storage in this scenario correctly. I thinkk that will help me understand how to implement it correctly when it comes to parseing the JSON product details correctly too.
Please have a look at the code below.
let basketData = {
    basketQty: 0,
    products: []
}

//LOCAL STORAGE
localStorage.setItem("basketData", JSON.stringify(basketData));
let localData = JSON.parse(localStorage.getItem("basketData"));

//INCREASE BASKET QTY INNER HTML
addToBasket.click(function(){
    basketData.basketQty++;
    if (basketData.basketQty > 0){
    $(basketQty).html(localData.basketQty);
}
})

VITAMIN & SUPPLEMENTS

SPORTS & WORKOUT NUTRITION

WEIGHT MANAGEMENT

FREE FROM

Many thanks for taking the time out to help and respond!

A: You are just setting it to a variable and not updating it in local storage. Also in addToBasket function you need to check the quantity from the local storage and increment it and then set the new quantity to the local storage.
localStorage.setItem("basketData", JSON.stringify({
    basketQty: 1,
    products: []
}));

You can refer this example. I have created a raw workaround for this you would have an better idea of it
https://jsfiddle.net/3tdn2jrv/


text:
Q: Symfony autoload not working for a custom Bundle In a project with Symfony 3.3.1 I have several "self-made" bundles I import with composer.json specifying the repositories, this way:
"repositories": [
    { "type": "git", "url": "git@github.com:MyCompany/CoreBundle.git" },
...
  ],

In the same project, in the src folder I have another Bundle like so:
src/MyCompany/Bundle/OtherBundle

Now, in my dev enviroment (Vagrant with Ubuntu 14.04, php 7.1, composer 1.5.2) it works perfectly. But on production (exactly same versions of OS, PHP and composer) I get this error:
PHP Fatal error:  Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "MyCompanyOtherBundle" from namespace "MyCompany\Bundle\OtherBundle".

In the composer.json I tried several configurations for the psr-4, all of them work fine in dev but not in prod:
"psr-4": {
  "MyCompany\\": "src/MyCompany/"
},

or
"psr-4": {
      "": "src/"
    },

or
"psr-4": {
      "MyCompany\\Bundle\\OtherBundle": "src/MyCompany/Bundle/OtherBundle"
    },

I ran the composer dump-autoload after on all of those changes but it had no effect.
Any idea on how this is happening? Thanks in advance


text:
Q: How to join two words together in a list with a space in the middle? I have a list like this :
['which', 'means', 'which', 'one','which', 'will]

How can I possibly join two words together and form this:
['which means', 'which one', 'which will']

A: Here's an option using join and zip:
>>> words = ['which', 'means', 'which', 'one', 'which', 'will']
>>> [' '.join(z) for z in zip(words[::2], words[1::2])]
['which means', 'which one', 'which will']

Breaking it down a little to show what the slice operation [::2] does and what zip does:
>>> words[::2], words[1::2]
(['which', 'which', 'which'], ['means', 'one', 'will'])
>>> list(zip(words[::2], words[1::2]))
[('which', 'means'), ('which', 'one'), ('which', 'will')]

A neat thing about this method is that you can change the number of words in the grouping very easily by using another iteration to build the arguments to zip:
>>> list(zip(*(words[i::3] for i in range(3))))
[('which', 'means', 'which'), ('one', 'which', 'will')]
>>> [' '.join(z) for z in zip(*(words[i::3] for i in range(3)))]
['which means which', 'one which will']


text:
Q: UIScrollView lazy loading of images to reduce memory usage and avoid crash My app, using scrollview that loads multiple images with NSOperation (Max around 100sh). I tried to test it out on my ipod 2Gen and it crashes due to low memory on device, but works fine on ipod 4th Gen. On 2nd Gen, it crashes when it loads about 15-20 images. How should I handle this problem ?

A: You could load you images lazily. That means, e.g., just a couple of images at a time in your scroll view, so that you can animate to the next and the previous one; when you move to the right, e.g., you also load one more image; at the same time, you unload images that are not directly accessible anymore (e.g. those that have remained to the left).
You should make the number of preloaded image sufficiently high so that the user can scroll without waiting at any time; this also depends on how big those images are and where they come from (i.e., how long it takes to load them)... a good starting point would be, IMO, 5 images loaded at any time.
Here you will find a nice step by step tutorial.
EDIT:
Since the link above seems to be broken, here is the final code from that post:
-(void)scrollViewDidScroll:(UIScrollView *)myScrollView {

/**
 *  calculate the current page that is shown
 *  you can also use myScrollview.frame.size.height if your image is the exact size of your scrollview
 */
int currentPage = (myScrollView.contentOffset.y / currentImageSize.height);

// display the image and maybe +/-1 for a smoother scrolling
// but be sure to check if the image already exists, you can do this very easily using tags
if ( [myScrollView viewWithTag:(currentPage +1)] ) {
    return;
}
else {
    // view is missing, create it and set its tag to currentPage+1
}

/**
 *  using your paging numbers as tag, you can also clean the UIScrollView
 *  from no longer needed views to get your memory back
 *  remove all image views except -1 and +1 of the currently drawn page
 */
for ( int i = 0; i < currentPages; i++ ) {
    if ( (i < (currentPage-1) || i > (currentPage+1)) && [myScrollView viewWithTag:(i+1)] ) {
        [[myScrollView viewWithTag:(i+1)] removeFromSuperview];
    }
}
}


text:
Q: Windows XP as wireless access point I wonder if it's possible to turn my normal windows PC to a wireless access point.
I've got a USB Wi-Fi adapter plugged on my PC but I don't have a wireless access point to connect to. What I want to achieve is to connect my phone (mobile) to the Wi-Fi adapter I've got and use the internet from my PC... is that achievable?
Please say yes :)
Thanks

A: Operating in Access Point mode requires a compatible driver and adapter at least, and I have no idea if this is even possible under windows.
You could however, if your phone supports it, operate in Ad-Hoc mode, which does not require an AP. It should be enough to set your WiFi adapter to Ad-Hoc, and enable Internet Connection Sharing for it.

A: *

*Bridge your LAN and WIRELESS card.

*Connect your wireless card and your phone using adhoc. The bridge created should give the phone access to the same internet on the LAN.

A: The first step in the process is called "tethering" (meaning you connect your computer to the Internet via your phone's Internet connection), and some phones and carriers support it.  I don't know of a comprehensive list of carriers and devices; you'll have to check with your carrier to see if they provide the service, check your plan to make sure you're allowed to do it (otherwise you'll incur massive data charges), check to make sure your device can do it, and make sure the software is available for your OS (although sometimes you can use either the built-in Windows dial-up utility or connect via Bluetooth, depending on your hardware).
Now, if you can tether your device, it only takes a little more effort to turn your computer into a wireless access point.  Follow the steps in these (or similar) articles:
http://support.microsoft.com/kb/306126
http://www.practicallynetworked.com/sharing/xp_ics/


text:
Q: Multiplication of very large numbers using character strings I'm trying to write a C program which performs multiplication of two numbers without directly using the multiplication operator, and it should take into account numbers which are sufficiently large so that even the usual addition of these two numbers cannot be performed by direct addition.
I was motivated for this when I was trying to (and successfully did) write a C program which performs addition using character strings, I did the following:
#include<stdio.h>
#define N 100000
#include<string.h>
void pushelts(char X[], int n){
int i, j;
for (j = 0; j < n; j++){
    for (i = strlen(X); i >= 0; i--){
        X[i + 1] = X[i];
    }
        X[0] = '0';
    }
}

int max(int a, int b){
    if (a > b){ return a; }
    return b;
}

void main(){
    char E[N], F[N]; int C[N]; int i, j, a, b, c, d = 0, e;
    printf("Enter the first number: ");
    gets_s(E);
    printf("\nEnter the second number: ");
    gets_s(F);
    a = strlen(E); b = strlen(F); c = max(a, b);
    pushelts(E, c - a); pushelts(F, c - b);
    for (i = c - 1; i >= 0; i--){
        e = d + E[i] + F[i] - 2*'0';
        C[i] = e % 10; d = e / 10;
    }
    printf("\nThe answer is: ");
    for (i = 0; i < c; i++){
        printf("%d", C[i]);
    }
    getchar();
}

It can add any two numbers with "N" digits. Now, how would I use this to perform multiplication of large numbers? First, I wrote a function which performs the multiplication of number, which is to be entered as a string of characters, by a digit n (i.e. 0 <= n <= 9). It's easy to see how such a function is written; I'll call it (*). Now the main purpose is to multiply two numbers (entered as a string of characters) with each other. We might look at the second number with k digits (assuming it's a1a2.....ak) as:
a1a2...ak = a1 x 10^(k - 1) + a2 x 10^(k - 2) + ... + ak-1 x 10 + ak

So the multiplication of the two numbers can be achieved using the solution designed for addition and the function (*).
If the first number is x1x2.....xn and the second one is y1y2....yk, then:
x1x2...xn x y1y2...yk = (x1x2...xn) x y1 x 10^(k-1) + .....

Now the function (*) can multiply (x1x2...xn) with y1 and the multiplication by 10^(k-1) is just adding k-1 zero's next to the number; finally we add all of these k terms with each other to obtain the result. But the difficulty lies in just knowing how many digits each number contains in order to perform the addition each time inside the loop designed for adding them together. I have thought about doing a null array and each time adding to it the obtained result from multiplication of (x1x2....xn) by yi x 10^(i-1), but like I've said I am incapable of precising the required bounds and I don't know how many zeros I should each time add in front of each obtained result in order to add it using the above algorithm to the null array. More difficulty arises when I'll have to do several conversions from char types into int types and conversely. Maybe I'm making this more complicated than it should; I don't know if there's an easier way to do this or if there are tools I'm unaware of. I'm a beginner at programming and I don't know further than the elementary tools.
Does anyone have a solution or an idea or an algorithm to present? Thanks.

A: There is an algorithm for this which I developed when doing Small Factorials problem on SPOJ.
This algorithm is based on the elementary school multiplication method. In school days we learn multiplication of two numbers by multiplying each digit of the first number with the last digit of the second number. Then multiplying each digit of the first number with second last digit of the second number and so on as follows:
               1234
               x 56
         ------------
               7404
             +6170-   // - is denoting the left shift
         ------------
              69104

What actually is happening:

*

*num1 = 1234, num2 = 56, left_shift = 0;

*char_array[] = all digits in num1

*result_array[]

*while(num2)

*

*n = num2%10

*num2 /= 10

*carry = 0, i = left_shift, j = 0

*while(char_array[j])
     i. partial_result = char_array[j]*n + carry
    ii. partial_result += result_array[i]
   iii. result_array[i++] = partial_result%10
    iv. carry =  partial_result/10

*left_shift++

*Print the result_array in reverse order.

You should note that the above algorithm work if num1 and num2 do not exceed the range of its data type. If you want more generic program, then you have to read both numbers in char arrays. Logic will be the same. Declare num1 and num2 as char array. See the implementation:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char num1[200], num2[200];
    char result_arr[400] = {'\0'};
    int left_shift = 0;

    fgets(num1, 200, stdin);
    fgets(num2, 200, stdin);

    size_t n1 = strlen(num1);
    size_t n2 = strlen(num2);

    for(size_t i = n2-2; i >= 0; i--)
    {
        int carry = 0, k = left_shift;
        for(size_t j = n1-2; j >= 0; j--)
        {
            int partial_result = (num1[j] - '0')*(num2[i] - '0') + carry;
            if(result_arr[k])
                partial_result += result_arr[k] - '0';
            result_arr[k++] = partial_result%10 + '0';
            carry = partial_result/10;
        }
        if(carry > 0)
            result_arr[k] = carry +'0';
        left_shift++;
    }
    //printf("%s\n", result_arr);

    size_t len = strlen(result_arr);
    for(size_t i = len-1; i >= 0; i-- )
        printf("%c", result_arr[i]);
    printf("\n");
}

This is not a standard algorithm but I hope this will help.

A: Bignum arithmetic is hard to implement efficiently. The algorithms are quite hard to understand (and efficient algorithms are better than the naive one you are trying to implement), and you could find several books on them.
I would suggest using an existing Bignum library like GMPLib or use some language providing bignums natively (e.g. Common Lisp with SBCL)

A: You could re-use your character-string-addition code as follows (using user300234's example of 384 x 56):
Set result="0" /* using your character-string representation */
repeat:
    Set N = ones_digit_of_multiplier /* 6 in this case */
    for (i = 0; i < N; ++i)
      result += multiplicand  /* using your addition algorithm */
    Append "0" to multiplicand /* multiply it by 10 --> 3840 */
    Chop off the bottom digit of multiplier /* divide it by 10 --> 5 */
    Repeat if multiplier != 0.


text:
Q: Why is this a conflict-free memory bank access? Here is an image taken from the CUDA C Programming Guide:

The guide says that this is an example of a Conflict-free access since threads 3, 4, 6, 7 and 9 access the same word within bank 5.
I don't quite understand why is this conflict-free, since not only threads 3, 4, 6, 7 and 9 access the same work within same bank (shouldn't that be an example of memory conflict?) but also thread 5 has to access bank 4.
Could you please explain to me this case?

A: Note that a bank is not the same thing as a word or location in shared memory.  A bank refers collectively to all words in shared memory that satisfy a certain address pattern condition.
In general, shared memory bank conflicts can be avoided if all accesses from a warp (or half-warp in cc 1.x) go to separate banks.  These accesses need not be in warp order, i.e. they can be scrambled, as long as the request from each thread targets a separate bank.
The above description covers every arrow in your diagram except those arrows pointing to bank 5.
If we had no other information, then multiple arrows targetting a single bank would indicate a potential bank conflict.
However, there is an exception, when not only are the accesses targetting the same bank, but they are targetting the same word in memory.  When multiple shared memory requests target the same word in memory, then the shared memory system has a broadcast mechanism to take the data contained in that word, and service it to all the requesting threads, in a single cycle.
From the documentation(http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#shared-memory-1-x):

Shared memory features a broadcast mechanism whereby a 32-bit word can be read and broadcast to several threads simultaneously when servicing one memory read request. This reduces the number of bank conflicts when several threads read from an address within the same 32-bit word.


text:
Q: How to pass data to a previous ViewController in Swift (Cocoa Application) Passing data to the next viewController is simple and straightforward, and can be done using prepareSegue method. However, I can't understand how to pass data to a previous viewController in Swift(Cocoa Application)
I have a textfield in viewControllerB and when you type something in it and press a button, I want to pass it to a label in viewControllerA and instead of opening the viewControllerA in a new window, I just want the viewController B to be dismissed and the passed data to be visible on the viewControllerA.
That's all there is to it. I have been stuck on it for the past 48 hours. Any help on this will be appreciated.
Thanks!

A: You do this using delegates. Example:
protocol NextProtocol: class {
    func sendBack(value: Int)
}

class Previous: NextProtocol {
    func sendBack(value: Int) {
        print("I have received \(value)")
    }

    func prepareSegue(...) {
        // get next instance
        var next: Next
        next.delegate = self
    }
}

class Next {
   weak var delegate: NextProtocol?

   func someMethod() {
       delegate?.sendBack(5)
   }
}


text:
Q: Is there a way to write node.js code synchronously? I am trying to create a program that analyses some data. The data I am collection form the internet with node.js. I'm having a very hard time with the fact that the code is asynchronous, and I'm getting a lot of bugs because of it.
I know that it is not efficient at all, but is there a way to write the whole code shynchronously?
*I've used a lot of promises and patched a lot of bugs, but I still keep getting bugs because the code is asynchronous, and I'm tired of thinking of creative ideas to make my code work.

A: This highly depends on the functions you use. Of course you can write an entire Node.js program purely synchronous - you just have to avoid using any function that is asynchronous.
But as Node.js is asynchronous by heart, I doubt that this will work for more complex things. Since you mentioned loading data from over the network: Just this is already an example of a task that can't be accomplished synchronously in Node.js, as any I/O in Node.js is always asynchronous (except for the file system methods that exist twice, but they are the exception to the rule).
I think the way better approach to solve your problems is to either use a different platform than Node.js, or to appropriately learn to deal with asynchronous code.
I guess that this is not the answer you wanted to hear, but unfortunately that's just the way it is IMHO.

A: If you're using networking (which it sounds like you are to retrieve data from other sources), then NO you can't write synchronous networking code in node.js.  Does not exist.  All networking API in node.js are asynchronous.
To use node.js networking, you must learn asynchronous programming.
It is possible to use only synchronous file I/O which should never be done in server request processing (because it wrecks scalability), but is sometimes useful in server startup and in non-server type scripts.


text:
Q: What function is called on SharePoint Post button click I want to know what function is called when Sharepoint NewsFeed's Post button is clicked.
I want to override or change it because it adds post image with wrong dimensions
<button id="ms-postreplybutton_1.1cb64504733e419c980e01269ed96f7a.049023eae3fc4b27a4755ed99c0e57cf.a28168d7eab4416783ec0599909c7d7f.0c37852b34d0418e91c62ac25af4be5b.6f01a2799a02461a9b636acab1d7fa98.10.10.S-1-5-21-1393957893-2012297305-37170099-80844" type="button" class="ms-microfeed-postButton ms-button-emphasize ms-floatRight" attachid="1.1cb64504733e419c980e01269ed96f7a.049023eae3fc4b27a4755ed99c0e57cf.a28168d7eab4416783ec0599909c7d7f.0c37852b34d0418e91c62ac25af4be5b.6f01a2799a02461a9b636acab1d7fa98.10.10.S-1-5-21-1393957893-2012297305-37170099-80844" disabled="">Post</button>

Also can someone explain, what is attachId property in button tag

A: All the functionalities related to SharePoint Newsfeed is included in SP.UI.MicroFeed.js which is a minified version.
You can also find debug version(SP.UI.MicroFeed.debug.js) too at
C:\Program Files\Common Files\Microsoft shared\Web Server Extensions\15\TEMPLATE\LAYOUTS

$7Z_0 is the function if you want to override


text:
Q: Custom certificate authentication for WCF service i am using a WCF service which is using "Transport" binding for communication and Certificate for authentication.
My service is hosted in IIS. i have to override the default authentication of WCF/IIS and write custom implementation.
i implemented Custom X509 validator but Api call does not even reaches the validator and fails before that.
is there a way to override the default authentication behavior?
Configuration:--
<service name="MyService" behaviorConfiguration="MyServiceBehavior">
        <endpoint binding="basicHttpBinding" bindingConfiguration="testBinding"
           contract="MyService"/>
</service>

<basicHttpBinding>
     <binding name="testBinding"
         maxReceivedMessageSize="2147483647">
      <security mode="Transport">
         <transport clientCredentialType="Certificate"/>
     </security>
    </binding>
</basicHttpBinding>

<serviceBehaviors>
    <behavior name="MyServiceBehavior">
      <serviceMetadata httpsGetEnabled="true" />
       <serviceDebug includeExceptionDetailInFaults="true" />
        <serviceCredentials>
         <clientCertificate>
          <authentication certificateValidationMode="Custom"
             customCertificateValidatorType="TestCertificateValidation
              ,MyService"/>
         </clientCertificate>
       </serviceCredentials>
     </behavior>
   </serviceBehaviors>

Custom Validator:--
public class TestCertificateValidation : X509CertificateValidator
{
   public override void Validate(X509Certificate2 certificate)
   {
     return;
   }
}

Thanks in Advance.