text:
Q: NHibernate not picking up changes I am wondering under what circumstances the following NHibernate code could fail:
var session = NHibernateSessionManager.CurrentSession;

var foo = session.Linq<Foo>.ToList()[0];

foo.SomeProperty = "test";

session.SaveOrUpdate(foo);

var reloadedFoos = session.Linq<Foo>
                         .Where(x => x.SomeProperty == "test");

Assert.That(reloadedFoos.Count > 0);

The Assert statement always fails.
If I manually call session.Flush after SaveOrUpdate, then the select query succeeds, however I thought that we did not have to manually call flush? It was my understanding that NHibernate should be smart enough to realise that Foo has been updated, so the second select query should succeed.
Watching the SQL that is generated, it appears the second select query's SQL is executed before the first SaveOrUpdate's sql.
In fact, if I wrap the entire method in a transaction, then it succeeds:
using(NHibernateSessionManager.CurrentSession.BeginTransaction()
{
    // Same code as above
}

Now the SaveOrUpdate's sql will execute before the Linq.Where sql. This is a little strange, as I do not have to even commit the transaction in between.
What is going on?

A: I recommend you leverage NHibernate transactions.  It's entirely possible that, without their use, NHibernate has no way of determining when to issue your SaveOrUpdate call.
You'll find that even read-only statements perform better when using transactions.  Please see http://nhprof.com/Learn/Alert?name=DoNotUseImplicitTransactions for further details.
For example:
using(var session = NHibernateSessionManager.CurrentSession)
{
  using(var transaction = session.BeginTransaction())
  {
    var foo = session.Linq<Foo>.ToList()[0];

    foo.SomeProperty = "test";

    session.SaveOrUpdate(foo);
    transaction.Commit();
  }
}

A: Note that you need a transaction for NHibernate to be "smart."
Here is how it works:
var session = NHibernateSessionManager.CurrentSession;
using(NHibernateSessionManager.CurrentSession.BeginTransaction()) {
    var foo = session.Linq<Foo>.ToList()[0];
    foo.SomeProperty = "test";
    var reloadedFoos = session.Linq<Foo>()
        .Where(x => x.SomeProperty == "test");
    Assert.That(reloadedFoos.Count > 0);
}

Note also that you do not call Save, Update, or SaveOrUpdate when you want to save the changes you have made to an object that the Session is already tracking back down to the database. NHibernate works differently from other ORMs: if it is tracking an object, then it will figure out when to send down the changes to the database and you don't need to tell it to do so.

A: "I am wondering under what circumstances the following NHibernate code could fail:" I think you have supplied at least one answer to your own question: when the code is run inside an implicit transaction. See this post from Ayende, which mentions inconsistent behavior inside implicit transactions. I have many unit tests that resemble your code except the test driver supplies a wrapping transaction, e.g.,
[Test]
public void Can_Update_Account() {
        Account account = PersistenceContext.Get<Account>(TEST_ACCOUNT_ID);

        string accountNumber = RandomString(10);
        account.AccountNumber = accountNumber;

        Account account1 = PersistenceContext.GetAll<Account>().Where(x => x.AccountNumber == accountNumber).SingleOrDefault();
        Account account2 = PersistenceContext.Get<Account>(account.Id);
        Assert.AreEqual(account.Id, account1.Id);
        Assert.AreEqual(accountNumber, account2.AccountNumber);
    }

[GetAll<>() is a thin wrapper over Linq<>.] I have many such tests that pass regularly.

A: You've probably got the incorrect flushmode set. You need to set the flushmode on the session to Auto for it to automatically flush the session before every query otherwise you need to flush the session manually to force the changes to be saved.

A:
If I manually call session.Flush after
  SaveOrUpdate, then the select query
  succeeds.

For a start: your call to SaveOrUpdate() is not even needed.
Here are some things to remember when using an NH session:

*

*When you have Loaded an object from session, the session will continue to track changes to that object

*Calling session.Update(entity) only tells the NHibernate session that it should start tracking the object, it does not go and write changes to the db

So, in your case, because you have loaded an object from the session already, calling session.Update() does nothing since it is already being tracked. You could infact force an update to the database by merely doing the following:
var session = NHibernateSessionManager.CurrentSession;
var foo = session.Linq<Foo>.ToList()[0];
foo.SomeProperty = "test";

session.Flush();

var reloadedFoos = session.Linq<Foo>
                         .Where(x => x.SomeProperty == "test");
Assert.That(reloadedFoos.Count > 0);

A: You have to close the session and create an now one before the Assert.
using(var session = NHibernateSessionManager.CurrentSession)
{
  using(var tx = session.BeginTransaction())
  {
    var foo = session.Linq<Foo>.ToList()[0];
    foo.SomeProperty = "test";
    session.SaveOrUpdate(foo);
    tx.Commit();
  }
}

//create a new session here, the code depend if you use RhinoCommons (like me), no Rhino

using(var session = NHibernateSessionManager.CurrentSession)
{
  using(var tx = session.BeginTransaction())
  {
    var reloadedFoos = session.Linq<Foo>
            .Where(x => x.SomeProperty == "test");
    Assert.That(reloadedFoos.Count > 0);
    tx.Commit();
  }
}


text:
Q: Unable to create mfp cordova project in Android 28 Latest Android SDK is not letting me use android command, as it is deprecated to create a mfp cordova project.
I'm using IBM MobileFirst CLI v7.1.0.00.20180706-0858 and latest Android SDK & Android Studio.
May I know any work around to create a project with mfp cordova?
Updated
Steps to reproduce the issue:
1) Download and install the latest Android Studio and download the latest Android SDK using sdkmanager. Set the system variables to the downloaded SDK buildtools and tools.
2) Download and install the latest MFP CLI v7.1.0.00.20180706-0858.
3) Run mfp cordova create in the command line and the following error happens.
MFP cordova project create Error Screenshot
Android Deprecated Screenshot
Thank you

A: MobileFirst CLI contains an instance of Cordova CLI v5.0.0, Android platform version 3.6.4.For more details see here :
https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/7.1/hello-world/integrating-mfpf-sdk-in-cordova-applications/
Cordova-Android@3.6.4  works only with older tools of android such as Android target: android-23.In your case you have updated your platform tools to latest that is why you are seeing such error.
I have uploaded older tools of android here :
https://ibm.box.com/s/je74bzx73y6je65tdnpttyns4ih1zj7b
Rename or take back up of your existing tools in android sdk path.Put uploaded tools in android sdk path.
With Android P that is targeting to API 28 with MobileFirst 7.1 app ,you may face an error java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/params/BasicHttpParams;
Work around is to add below tag in AndroidManifest.xml inside the  tag:

Google's issue tracker
The same has been update in the
Android P blog

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any package to read table from file in python I've stored some data in a file in tabular format using the python package:  tabulate
>>> print tabulate(table, headers, tablefmt="orgtbl")$

The table looks like:
| name   |   num |
|--------+-------|
| abcd   |    30 |
| efgh   |   100 |
| ijklm  |    10 |

Now I need to feed this data to some other program(written in python).
Is there any easy way(I mean any package) to read the table into some data structure instead of parsing it explicitly. In other words  I could have printed the table into some other format(e.g: grid, pipe, media-wiki, latex) is there any ready made solution to read it into a data structure from any of such formats?

A: You might take a look at astropy.io.ascii (previously known as Asciitable) and see if it does some of what you want.

The following shows a few of the ASCII formats that are available, while the section on Supported formats contains the full list.

*

*Basic: basic table with customizable delimiters and header configurations

*Cds: CDS format table (also Vizier and ApJ machine readable tables)

*Daophot: table from the IRAF DAOphot package

*Ecsv: Enhanced CSV format

*FixedWidth: table with fixed-width columns (see also Fixed-width Gallery)

*Ipac: IPAC format table

*HTML: HTML format table contained in a <table> tag

*Latex: LaTeX table with datavalue in the tabular environment

*Rdb: tab-separated values with an extra line after the column definition line

*SExtractor: SExtractor format table

A:
Is there any easy way(I mean any package) to read the table into some data structure instead of parsing it explicitly.

With some effort, csv.reader will do:
from csv import reader

with open('table') as f:
    next(f) # throw away header
    next(f) # throw away |-----+-----|
    for line in reader((l.strip().strip('|') for l in f), delimiter='|'):
        print(line)

Output:
[' abcd   ', '    30 ']
[' efgh   ', '   100 ']
[' ijklm  ', '    10 ']

Not perfect, but close.
But, parsing it manually is in my opinion more readable:
with open('table') as f:
    next(f) # throw away header
    next(f) # throw away |-----+-----|
    for line in f:
        print(line.strip().strip('|').split('|'))

Throwing away redundant spaces also it's quite easy:
with open('table') as f:
    next(f) # throw away header
    next(f) # throw away |-----+-----|
    for line in f:
        print([scalar.strip() for scalar in line.strip().strip('|').split('|')])

Output:
['abcd', '30']
['efgh', '100']
['ijklm', '10']

That said, I would use tabulate only for displaying data. For storing, I'd use csv or json.


text:
Q: Forward declare typedef within C++ class What's the best solution to forward declare a typedef within a class.  Here's an example of what I need to solve:
class A;
class B;

class A
{
    typedef boost::shared_ptr<A> Ptr;

    B::Ptr foo();
};

class B
{
    typedef boost::shared_ptr<B> Ptr;

    A::Ptr bar();
};

I suppose I could just do the following:
boost::shared_ptr<B> foo();

But is there a more elegant solution?

A: You're facing two distinct difficulties:
1. There are no forward declarations of typedefs
2. Forward declarations of nested types are not possible
There is no way around the second: you have to unnest the types.
One way around the first that I occasionally use is to make a derived type, and that yes, can be forwardly declared.
Say:
struct Ptr : shared_ptr<A> {};

This is a new type, but it is almost the same as a synonym.
The problem, of course, is constructors, but that is getting better with C++11.
This answer, of course, is in general. For your specific case, I think you should define the Ptrs outside the classes and you would have no problem at all.
struct A;
struct B;
typedef shared_ptr<A> APtr;
typedef shared_ptr<B> BPtr;

and then the classes.

A: There's no way to forward declare either

*

*A typedef

*A name in another class

So - you can't forward declare a typedef and if you could, you still wouldn't be able to do that, because you'd need to do this:
class B::Ptr;

and that's not possible

A: You cannot.
But you can decouple the Ptr definition of the classes:
class A;
class B;

template <typename T>
struct Traits {
    typedef std::shared_ptr<A>  Ptr;
};

class A
{
    Traits<B>::Ptr foo();
};

class B
{
    Traits<A>::Ptr bar();
};

If A and B does not share the same types, you always can specialize Traits for all type.

A: As others have noted, you cannot forward-declare typedefs.  That's in part because typedefs aren't really "types" of their own, but aliases for other types (hence the C++11 equivalent notion of a "type alias" such as "using Int = int;").  That means, for example, that typedefs don't show up in ABI elements such as mangled names, and so the compiler really has to know enough of the underlying type to satisfy all ABI requirements (including how to mangle the type name).

A: There is no such thing as forward declaring a typedef unfortunately. However, there's a trick using late template instantiation:
template <typename T> class BImpl;

template <typename T>
class AImpl
{
public:
    typedef boost::shared_ptr<AImpl> Ptr;
    typename BImpl<T>::Ptr foo();
};

template <typename T>
class BImpl
{
public:
    typedef boost::shared_ptr<BImpl> Ptr;
    typename AImpl<T>::Ptr bar();
};

typedef AImpl<void> A;
typedef BImpl<void> B;

This should hopefully accomplish the thing you're aiming for.


text:
Q: Why click event fires even it is removed? in my App I add a click listener via function activateListener().
On some point at the run-time I remove the click listener via function deactivatelistener().
But still when the user does a click the click function pingIfLastPingIsOld() is called again.
The function activateListener() is not called again after deactivatelistener().
Does some body have a glue how comes?
Why the click listener is still working?
Frank

    activateListener() {
        window.addEventListener('click', () => {
            this.pingIfLastPingIsOld();
        });
    }

    deactivatelistener() {
        window.removeEventListener('click', this.pingIfLastPingIsOld);
    }

A: It's normal because you didn't register/unregsiter the exact same method. Do this :
activateListener() {
    window.addEventListener('click', this.pingIfLastPingIsOld);
}

deactivatelistener() {
    window.removeEventListener('click', this.pingIfLastPingIsOld);
}

But, the angular way would be more :
@HostListener('document:click', ['$event.target'])
public onClick(targetElement) {
    // your stuff
}

A: The existing answer by Cétia correctly identifies the issue - you register a click handler with an anonymous function, but then try to unregister a named function - however I would like to provide an alternative solution.

I see you're using an anonymous function as your click listener, I assume this is to fix the this context for the execution of pingIfLastPingIsOld. This can also be done via the .bind method.
constructor() {
    this.pingIfLastPingIsOld = this.pingIfLastPingIsOld.bind(this);
}

activateListener() {
    window.addEventListener('click', this.pingIfLastPingIsOld);
}

deactivatelistener() {
    window.removeEventListener('click', this.pingIfLastPingIsOld);
}

Regardless of where pingIfLastPingIsOld is invoked from, it will now execute with the component as the value of this.

Documentation


text:
Q: How to only change the value from 'apply_filters' via child theme functions? I have the following code that outpouts the text "via nameOfshippingMethod" in the order summary in emails which I want to get rid of:
$shipping .= apply_filters( 'woocommerce_order_shipping_to_display_shipped_via', ' ' . sprintf( __( 'via %s', 'woocommerce' ), $this->get_shipping_method() ) . '', $this );

From the perspective of taking the least invasive method, is it possible to somehow change the value of this apply_filters or would I have to replace the entire function in my child functions.php?
I would truly appreciate if anyone could help me!
For completeness the entire function is (located in "abstract-wc-order.php):
public function get_shipping_to_display( $tax_display = '' ) {
    $tax_display = $tax_display ? $tax_display : get_option( 'woocommerce_tax_display_cart' );

    if ( 0 < abs( (float) $this->get_shipping_total() ) ) {

        if ( 'excl' === $tax_display ) {

            // Show shipping excluding tax.
            $shipping = wc_price( $this->get_shipping_total(), array( 'currency' => $this->get_currency() ) );

            if ( (float) $this->get_shipping_tax() > 0 && $this->get_prices_include_tax() ) {
                $shipping .= apply_filters( 'woocommerce_order_shipping_to_display_tax_label', ' ' . WC()->countries->ex_tax_or_vat() . '', $this, $tax_display );
            }
        } else {

            // Show shipping including tax.
            $shipping = wc_price( $this->get_shipping_total() + $this->get_shipping_tax(), array( 'currency' => $this->get_currency() ) );

            if ( (float) $this->get_shipping_tax() > 0 && ! $this->get_prices_include_tax() ) {
                $shipping .= apply_filters( 'woocommerce_order_shipping_to_display_tax_label', ' ' . WC()->countries->inc_tax_or_vat() . '', $this, $tax_display );
            }
        }

        /* translators: %s: method */
        $shipping .= apply_filters( 'woocommerce_order_shipping_to_display_shipped_via', ' ' . sprintf( __( 'via %s', 'woocommerce' ), $this->get_shipping_method() ) . '', $this );

    } elseif ( $this->get_shipping_method() ) {
        $shipping = $this->get_shipping_method();
    } else {
        $shipping = __( 'Free!', 'woocommerce' );
    }

    return apply_filters( 'woocommerce_order_shipping_to_display', $shipping, $this, $tax_display );
}

A: With the helpful tip from Howard E I was able to produce the following WooCommerce filter that works:
add_filter( 'woocommerce_order_shipping_to_display_shipped_via', 'woocommerce_order_shipping_to_display_shipped_via_remove', 10);

function woocommerce_order_shipping_to_display_shipped_via_remove( $no_via ) {
    $no_via = ' ' ;
    return $no_via;
}

This was quite helpful in creating it for the first time:
https://www.hardworkingnerd.com/how-to-use-add_filter-and-apply_filters-in-woocommerce/


text:
Q: In Android Studio, the "run" button is disabled / grayed-out, when cloning a flutter project from Git I just started learning flutter, and I wanted to clone a flutter project from git. When ever I clone a project and open it in android studio, the "run" button is disabled. The "Flutter device selection" dropdown is also not visible.
This does not happen when I created a flutter project from scratch but only when I clone it I face these issues.

The above pic shows the issue.
I have tried:
1) restarting the editor, 2) file -> invalidate caches/ restart, 3) file -> project structure -> modules and removed the existing "content root" and adding it again. Nothing worked.
My flutter doctor -v shows the following:

This is how my editor looks when I create a flutter project from scratch:

I have tried finding answers online but nothing worked. How do I fix this?

A: I found a fix. Open a different project (I have only been testing on flutter projects so far), then file -> open -> your project, in the dialogue pop up which asks do you want to open in this window or new window, select new window.


text:
Q: datatables.net plugin hides left menu behind table in IE I had a page that works perfectly in IE.
Then I added the wonderful jQuery plugin Datatables to it using this code in DOMReady with this code
$('#articlestable-container table').dataTable({
    "bPaginate": true,
    "bLengthChange": false,
    "bFilter": true,
    "bSort": false,
    "bInfo": false,
    "bAutoWidth": false
});

Everything is fine in Webkit and Firefox browsers. See the image.

But in IE, the table hides the menu that ideally should come over the table like this.

As you can see, the sub-menu gets rendered behind the table.
I don't think z-index is the culprit here. The sub-menu has z-index: 9999; anyway.
What could be wrong? Any pointers to solve this will be very helpful.

A: Have been using the default CSS that ships with datatables.net. Here the wrapper was having position:relative;. Just remove that code and the menu appears properly.
.dataTables_wrapper {
    /*position: relative;*/
    clear: both;
    zoom: 1;  /*Feeling sorry for IE */
}

I guess that its an IE bug. http://www.gobdg.com/blog/2009/04/positionrelative-z-index-ie-bug/
But manually setting z-index:1; didn't work for me.
Disclaimer: I don't know yet as to how this actually solved the issue. I am no CSS guru.


text:
Q: How do I increase parent element as child element is increased? I have two classes and I need to make their the elements same height. As the children element's height is increased, the parent element also needs its height to be increased.
Parent element class is .user-data and children element class is .scheduleWorkingPeriodContainer.
.user-data {
    position: relative;
    float: left;
    box-sizing: border-box;
    min-height: 40px;
    align-items: center;
    text-align: center;
    border-left: 1px solid #d0d0d0;
    border-bottom: 1px solid #d0d0d0;
    background-color: white;
}

.scheduleWorkingPeriodContainer {
    position: absolute;
    z-index: 1;
    width: 100%;
    display: block;
    overflow-x: hidden;
    height: auto;
 }

Parent and children element need to have same class and I also cannot change the position property in .user-data and .scheduleWorkingPeriodContainer due to code not shown here.
Can someone help?

A: As stated in this other answer, you cannot set the parent's height according to an absolute positioned element unless you use fixed height or JavaScript.

With JavaScript, you just need to retrieve the height of your absolute positioned child element .scheduleWorkingPeriodContainer then set that retrieve value as the height for your relative positioned parent element .user-data.

Check and run the following Code Snippet for a practical example of what I described above. In the following snippet, I changed the parent element's height to be 5px more than it's absolute positioned child element so that you can see the extra height of the parent element:

/* JavaScript */

var child = document.querySelector(".scheduleWorkingPeriodContainer");
var parent = document.querySelector(".user-data");

parent.style.height = parseInt(window.getComputedStyle(child).height) + 5 + "px";
/* CSS */

.user-data {
    position: relative;
    float: left;
    box-sizing: border-box;
    min-height: 40px;
    align-items: center;
    text-align: center;
    border-left: 1px solid #d0d0d0;
    border-bottom: 1px solid #d0d0d0;
    background-color: green;
    width: 100%;
}

.scheduleWorkingPeriodContainer {
    position: absolute;
    z-index: 1;
    display: block;
    width: 100%;
    overflow-x: hidden;
    height: auto;
    background-color: red;
 }
 html, body {width: 100%;height: 100%; margin: 0; padding: 0;}

ABCD

ABCD

ABCD

ABCD


text:
Q: How to create a Google calendar event with C# and Google calendar API? I have some code for creating Google Calendar Event, but it does not work. I try to create event in my Google Calendar from C#.
The source code is taken from Google site (https://developers.google.com/calendar/v3/reference/events/insert), but some part of code is from other link(https://developers.google.com/calendar/quickstart/dotnet).
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CalendarQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/calendar-dotnet-quickstart.json
        static string[] Scopes = { CalendarService.Scope.Calendar };
        static string ApplicationName = "Google Calendar API .NET Quickstart";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
            Console.WriteLine("Credential file saved to: " + credPath);
        }

        // Create Google Calendar API service.
        var service = new CalendarService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });

        Event newEvent = new Event()
        {
            Summary = "Google I/O 2015",
            Location = "800 Howard St., San Francisco, CA 94103",
            Description = "A chance to hear more about Google's developer products.",
            Start = new EventDateTime()
            {
                DateTime = DateTime.Parse("2019-06-28T09:00:00-07:00"),
                TimeZone = "America/Los_Angeles",
            },
            End = new EventDateTime()
            {
                DateTime = DateTime.Parse("2019-06-28T17:00:00-07:30"),
                TimeZone = "America/Los_Angeles",
            },
            Recurrence = new String[] { "RRULE:FREQ=DAILY;COUNT=2" },
            Attendees = new EventAttendee[] {
                new EventAttendee() { Email = "lpage@example.com" },
                new EventAttendee() { Email = "sbrin@example.com" },
            },
            Reminders = new Event.RemindersData()
            {
                UseDefault = false,
                Overrides = new EventReminder[] {
                new EventReminder() { Method = "email", Minutes = 24 * 60 },
                new EventReminder() { Method = "sms", Minutes = 10 },
                }
            }
        };

        String calendarId = "primary";
        EventsResource.InsertRequest request = service.Events.Insert(newEvent, calendarId);
        Event createdEvent = request.Execute();
        Console.WriteLine("Event created: {0}", createdEvent.HtmlLink);
    }
}

}
This is an error, and I don't understand what it means.

A: The error message "request had insufficient authentication scopes" indicates a problem with the scopes you're using in your token. I can see in your code you're using the correct scope to execute those actions, so most probably the problem is that the token.json haven't been updated with the new scope and it's still with the previous scopes which don't allow those actions.
Solution:
Delete the file token.json and run the script again, it'll prompt you the link to grant access and once accepted it'll create the token.json again with the updated scopes. You have to do this every time you change the scopes.
If the above doesn't solve the issue, another important thing is to enable the service you're going to use in the Cloud Platform console , in this case Calendar API (1st step of the quickstart [1]).
Bear in mind that if you enable an additional API for your project in the Cloud Platform console, you would have to create a new credentials.json which will have the enabled services updated and replace that credentials.json for the previous one.
[1] https://developers.google.com/calendar/quickstart/dotnet


text:
Q: remove duplicates in a datatable from sql query basically I have this code in sql
SELECT DISTINCT A.fDate FROM tblReport_Date A
LEFT JOIN tblReport_Type B ON A.ID_ReportType = B.ID
LEFT JOIN tblReceiver C ON A.ID_Receiver = C.ID
LEFT JOIN tblClients D ON A.ID_Client = D.ID
WHERE A.fDate BETWEEN '1/1/2013 12:00:00 AM' AND '6/1/2014 12:00:00 AM'
AND B.fType = 'HCC' AND C.Receiver = '<test@test.com>'
AND D.fClientName = 'Radford'

now, it would return
9/25/2013 8:00:00 AM
10/3/2013 12:00:00 PM
12/5/2013 10:00:00 AM
12/5/2013 12:00:00 AM

what I wanted is something like
9/25/2013 8:00:00 AM
10/3/2013 12:00:00 PM
12/5/2013 10:00:00 AM

or even better
9/25/2013 12:00:00 AM
10/3/2013 12:00:00 AM
12/5/2013 12:00:00 AM

I know this is impossible in my current query, because
12/5/2013 10:00:00 AM  and  12/5/2013 12:00:00 AM
have different TIME values. Is this possible through query?

A: You can group by date (without time), this should work on most versions of SQL-Server starting with 2005:
SELECT fDate = DATEADD(day, DATEDIFF(day, 0, A.fDate), 0)
FROM tblReport_Date A
LEFT JOIN tblReport_Type B ON A.ID_ReportType = B.ID
LEFT JOIN tblReceiver C ON A.ID_Receiver = C.ID
LEFT JOIN tblClients D ON A.ID_Client = D.ID
WHERE A.fDate BETWEEN '1/1/2013 12:00:00 AM' AND '6/1/2014 12:00:00 AM'
AND B.fType = 'HCC' AND C.Receiver = '<test@test.com>'
AND D.fClientName = 'Radford'
GROUP BY DATEADD(day, DATEDIFF(day, 0, A.fDate), 0)

Or in SQL Server 2008 onwards you  cast to  Date:
GROUP BY CAST(A.fDate AS DATE)

A: ;WITH CTE_Temp
(
SELECT DISTINCT A.fDate FROM tblReport_Date A
LEFT JOIN tblReport_Type B ON A.ID_ReportType = B.ID
LEFT JOIN tblReceiver C ON A.ID_Receiver = C.ID
LEFT JOIN tblClients D ON A.ID_Client = D.ID
WHERE A.fDate BETWEEN '1/1/2013 12:00:00 AM' AND '6/1/2014 12:00:00 AM'
AND B.fType = 'HCC' AND C.Receiver = '<test@test.com>'
AND D.fClientName = 'Radford'
)
SELECT DISTINCT DATE(fDate) FROM CTE_Temp


text:
Q: ready function inside jsp and ready function in js file I have a ready function inside my jsp and also a ready function inside my javascript. I am having some issues understanding in what order things are running.
Inside my jsp i have...
<head>
    <script type="text/javascript">
    $().ready(function() {
        var params = ({
            reportingManagerTitle : "<spring:message code='title.reportingManager'/>",
            launchButtonText: "<spring:message code='button.launch'/>"
        });
    init(params);
    });
    </script>
    <script type="text/javascript" src="<c:url value="resources/js/pages/login.js" />"></script>
</head>

Then inside my javascript file I have ...
var reportingManagerTitle = null;
var launchButtonText = null;
$().ready(function() {
    // do something with reportingManagerTitle after page load
    alert(reportingManagerTitle );

    // so something with launchButtonText after page load
    alert(launchButtonText );
});

function init(params) {
    reportingManagerTitle = params.reportingManagerTitle;
    launchButtonText = params.launchButtonText;
}

My problem is that both reportingManagerTitle and launchButtonText are undefined. I through the javascript in my js would run first and then the js in my external file. What am I doing wrong?
thanks


text:
Q: Copy two columns to another table, one is a primary key I have a large table (Visits) with primary key kha_ID.  There are a dozen or so columns in this table and I only want to replace one of them, ADM_SRC.  The problem is that ADM_SRC contains nulls.  I imported another table with the kha_id and that record's corresponding ADM_SRC.  I'm hoping my query below will insert the correct ADM_SRC into the correct record.
Here's my query, I wanted to check out if it'll pass before I run it
INSERT INTO tblVisits (kha_id, adm_src)
SELECT (kha_id, adm_src) from tblAdm_Src

tblAdm_Src is the imported table.  Thanks.

A: Assuming

*

*There's no data in tblVisits

*Id is not an auto-incrementing identity column

*All of the columns have a default value specified

Then your query will work
insert into tblVisits (kha_id, adm_src) select kha_id, adm_src from tblAdm_Src

If some of the columns don't have default values then you need to supply default values in the query, e.g.
insert into tblVisits (kha_id, adm_src, otherColumn)
select kha_id, adm_src, 'a value' from tblAdm_Src

If kha_id is an identity column, you need to use SET IDENTITY_INSERT
set identity_insert tblVisits on
insert into tblVisits (kha_id, adm_src) select kha_id, adm_src from tblAdm_Src
set identity_insert tblVisits off

If there is existing data in Visit and you need to update matching rows, but insert missing ones then you need something like
-- update existing rows
update tblVisits
    set adm_src = tblAdm_Sr.adm_src
from VisitSource
    where tblVisits.kha_id = tblAdm_Sr.kha_id

-- insert missing rows
insert into tblVisits (kha_id, adm_src)
select kha_id, adm_src from tblAdm_Src
   where not exists(
     select kha_id from tblVisits where tblVisits.kha_id = tblAdm_Src.kha_id)

and of course taking into account default values and auto incrementing Id column as necessary

A:
I wanted to check out if it'll pass before I run it

maybe I do not understand your question in the right way .. but what about

*

*truning off auto commit

*running your query

*check the result

*commit (everything went fine) or rollback (not the result as expected)?


text:
Q: How To Determine If Outlook Is Fully Launched from my C# Add-In? Windows users can right-click on any file in explorer and go to Send to > Mail recipient
This launches a new message in a compose inspector with the file attached and some pre-populated text. However, it does not seem to fully launch the Outlook application.
This causes problems when my Add-In tries to close the inspector and run some cleanup code (which it does successfully when Outlook is fully launched). The Add-In suspends and crashes Outlook when trying to run the clean up code because closing the inspector is trying to close Outlook.
Is there a way using C# to determine whether Outlook is fully launched or just in this compose-only mode?

A: What is the problematic snippet of your code?
You can check if there are any open explorers by checking the Application.Explorers.Count property.


text:
Q: Multiple client calls after page refresh with SignalR We have a application with multiple hubs using Signal R 1.1.3, that monitors currently logged on users.  The hub periodically refreshes the user count with the following script
     $.extend(sr_users.client, {
    showCurrentUserCount: function (data) {
        console.log("Showing Current Users");
        $('#current-users').html(data);
    }
});

Which produces the following line
   [xx:xx:xx GMT+0000 (GMT Standard Time)] SignalR: Triggering client hub event 'showCurrentUserCount' on hub 'userhub'.

However when the browser is refreshed the above client hub event is called multiple times
  [15:40:20 GMT+0000 (GMT Standard Time)] SignalR: Triggering client hub event 'showCurrentUserCount' on hub 'userhub'.
  [15:40:20 GMT+0000 (GMT Standard Time)] SignalR: Triggering client hub event 'showCurrentUserCount' on hub 'userhub'.

How can I prevent this from happening
Thank you
Additional Code
    sr_users = $.connection.userhub;
$.connection.hub.logging = true;

    //update any ui when the hub starts
$.connection.hub.start()
    .done(function () {
        sr_users.server.getCurrentUsers()
        .done(function (users) {
            $('#current-users').html(users);
        });
    });

A: Sorted it! Doh! Put an event subscription on the Hub constructor. Bad idea
   public UserHub()
   {
      Connections.Instance.OnPurge += ConnectionsUpdate
   }

So each time the page was refreshed the event would be subscribed to.  I have no removed the procedure completely and gave the connection Instance access to the HUbContext from where it can send out to all clients


text:
Q: Passing Bitmap / JPEG Over Network I'm trying to create a remote desktop-esque program, and am currently trying to get an image of what's on my remote PC, and send it back over to my client PC to update their image (This happens ever 2-3 seconds.)
I currently get the image of the desktop like this:
// Set up a bitmap of the correct size
        Bitmap CapturedImage = new Bitmap((int)SystemInformation.VirtualScreen.Width,
            (int)SystemInformation.VirtualScreen.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb565);

        // Create a graphics object from it
        System.Drawing.Size size = new System.Drawing.Size((int)SystemInformation.VirtualScreen.Width, (int)SystemInformation.VirtualScreen.Height);

        using (Graphics gr = Graphics.FromImage(CapturedImage))
        {
            // copy the entire screen to the bitmap
            gr.CopyFromScreen(0, 0, 0, 0,
                size, CopyPixelOperation.SourceCopy);
        }

        EncodeToJPEG(CapturedImage);

And EncodeToJPEG looks like this:
var qualityEncoder = Encoder.Quality;
        var quality = (long)0;
        var ratio = new EncoderParameter(qualityEncoder, quality );
        var codecParams = new EncoderParameters(1);
        codecParams.Param[0] = ratio;
        var jpegCodecInfo = GetEncoder(ImageFormat.Jpeg);
        capturedImage.Save(@"c:\Test.jpg", jpegCodecInfo, codecParams); // Save to JPG

My question comes from the Save method. I was wondering if there was a way to temporarily store this JPG just long enough for me to have it to send back over the network, instead of saving it to a file? Like, can I return an Image object that is a compressed JPG? Or is this just not possible this way?
I've also heard that for these purposes, splitting the image into blocks, and checking their deltas and only sending back the changes is the most efficient way to update images like this faster. If anyone has any pointers in that department I'd be very grateful.

A: Encoder has method of OVERLOAD name of Save
Arugument to pass is the Stream
You will save to MemoryStream for the memory block save
No files !!
Best ,
PRASHANT :)


text:
Q: SQLite Android update field from other fields I am trying to update an integer field in my SQLite database by combining three other integer fields but I need to also prefix two the of the other fields with a zero if the length of the field value is 1.
This is a routine I am trying to do via the Upgrade Database method in my DBAdapter Class.
So I need to change this current update :
if (newVersion==2) {
  populatesql = "update " + DB_TABLE +
                " set field1="+ COL_FIELD2 +
                " || " +
                COL_FIELD3 +
                " || " +
                COL_FIELD4;
}

to something like this (yes I know the the prefixzero would not work as it needs String not integer but I tried it with String and made it static but it did not work)
if (newVersion==2) {
  populatesql = "update " + DB_TABLE +
                " set field1="+ COL_FIELD2 +
                " || " +
                prefixzero(COL_FIELD3) +
                " || " +
                prefixzero(COL_FIELD4);
}

public String prefixzero(String number) {
    String result = Integer.toString(number);

    // Log.d("PREFIX", "result starts with this = "+result);
    if (result.length() >1 ) {
      // Log.d("PREFIX", "NO ZEROES HERE");
      return Integer.toString(number);
    }

   String zeroprefix = "";
   zeroprefix = "0"+result;
   // Log.d("PREFIX", zeroprefix);

   return zeroprefix ;
}

The database fields are declared as follows:
public static final String COL_FIELD4 = "day";
public static final String COL_FIELD3 = "month";
public static final String COL_FIELD2 = "year";
public static final String COL_FIELD1 = "long_date";

This is the error I get leaving out the spaces. It is as thought without the spaces the field names are simply joined together. The code used is below this error.
02-28 07:34:00.919: E/AndroidRuntime(18332): java.lang.RuntimeException: Unable to start activity ComponentInfo{co.uk.common.myapp/co.uk.common.myapp.MainActivity}: android.database.sqlite.SQLiteException: no such column: yearmonthday: update Log set long_date= yearmonthday
02-28 07:34:00.919: E/AndroidRuntime(18332):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1658)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1674)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:942)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at android.os.Looper.loop(Looper.java:130)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at android.app.ActivityThread.main(ActivityThread.java:3735)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at java.lang.reflect.Method.invokeNative(Native Method)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at java.lang.reflect.Method.invoke(Method.java:507)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:662)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at dalvik.system.NativeStart.main(Native Method)
02-28 07:34:00.919: E/AndroidRuntime(18332): Caused by: android.database.sqlite.SQLiteException: no such column: yearmonthday: update Log set long_date= yearmonthday
02-28 07:34:00.919: E/AndroidRuntime(18332):    at android.database.sqlite.SQLiteDatabase.native_execSQL(Native Method)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1763)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at co.uk.shieldstothemax.blastedneighbours.DBAdapter$DBHelper.onUpgrade(DBAdapter.java:68)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:132)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at co.uk.shieldstothemax.blastedneighbours.DBAdapter.open(DBAdapter.java:87)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at co.uk.shieldstothemax.blastedneighbours.MainActivity.onCreate(MainActivity.java:123)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-28 07:34:00.919: E/AndroidRuntime(18332):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1622)

Cod in the onUpgrade method:
if (newVersion==2) {

                 populatesql = "update "+ DB_TABLE +" set long_date= "+getDateStr(COL_FIELD2,COL_FIELD3,COL_FIELD4);
                }

The getDateStr:
public static String getDateStr(String year, String month,String day) {
        return year+ prefixfieldzero(month)+ prefixfieldzero(day);
     }

the prefixfieldzero :
public static String prefixfieldzero(String number) {
            String result = String.valueOf(number);
          //  Log.d("PREFIX", "result starts with this = "+result);
            if (result.length() >1 ) {
             // Log.d("PREFIX", "NO ZEROES HERE");
             return number;
             }

           String zerofieldprefix = "";
           zerofieldprefix = "0"+result;
          // Log.d("PREFIX", zeroprefix);

              return zerofieldprefix ;
        }

Here is my DBAdapter :
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
    private static final String DB_NAME = "TABLE";
    private static final String DB_TABLE = "Log";
    private static final int DB_VERSION = 2;

    private static final String DB_CREATE = "CREATE TABLE IF NOT EXISTS "+DB_TABLE+
                " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                       "type_id INTEGER, " +" hour INTEGER, " +
                         "min INTEGER , " +" info VARCHAR,"+"image_desc VARCHAR, "+
                       "day INTEGER, "+"month INTEGER,  "+ "year INTEGER,"+" second INTEGER,long_date INTEGER ,date_time_long INTEGER NOT NULL "+");" ;

        public static final String COL_TYPE = "type_id";
        public static final String COL_HOUR = "hour";
        public static final String COL_MIN = "min";
        public static final String COL_SEC = "second";
        public static final String COL_IMAGE = "image_desc";

        public static final String COL_DAY = "day";
        public static final String COL_MON = "month";
        public static final String COL_YEAR = "year";
        public static final String COL_DATE = "date";
        public static final String COL_LONG_DATE = "long_date";
        public static final String COL_INFO = "info";
        public static final String COL_ID = "_id";

        private SQLiteDatabase mDB;
        private DBHelper mDBHelper;
        private Context mCtx;

        private static class DBHelper extends SQLiteOpenHelper{
            public DBHelper(Context context) {
                super(context, DB_NAME, null, DB_VERSION);
            }

            @Override
            public void onCreate(SQLiteDatabase db) {
                db.execSQL(DB_CREATE);

            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                Log.v("OLDDBVERSION", "Old version="+String.valueOf(oldVersion));
                Log.v("NEWDBVERSION", "New version="+String.valueOf(newVersion));
                //String upgradesql = null;
                String populatesql = null;
                if (newVersion==2) {

                 populatesql = "update "+ DB_TABLE +" set long_date= "+getDateStr(COL_YEAR,COL_MON,COL_DAY);
                }
                if (populatesql !=null) {
                    //db.execSQL(upgradesql);
                    if (populatesql !=null) {

                        db.execSQL(populatesql);
                    }
                }

        }
   }

        public DBAdapter(Context ctx)
        {
            this.mCtx = ctx;
        }

        //OPEN METHOD AND CLOSE METHOD
        public DBAdapter open()
        {
            mDBHelper = new DBHelper(mCtx);
            mDB = mDBHelper.getWritableDatabase(); //important
            return this;
        }

        public void close()
        {
            mDBHelper.close();
        }

        //INSERT AND DELETE
        public long createLog(String info,String image, Integer type,Integer hour,Integer mins,Integer sec,Integer day,Integer month,Integer year,Long longdate,Long date)
        {
            ContentValues v = new ContentValues();
            v.put(COL_TYPE, type);
            v.put(COL_INFO, info);
            v.put(COL_IMAGE, image);
            v.put(COL_HOUR, hour);
            v.put(COL_SEC, sec);
            v.put(COL_MIN, mins);
            v.put(COL_DAY, day);
            v.put(COL_MON, month);
            v.put(COL_YEAR, year);
            v.put(COL_DATE, date);
            v.put(COL_LONG_DATE, longdate);

            return mDB.insert(DB_TABLE, null, v);
        }

        public boolean deleteLogRec(long id)
        {
            return mDB.delete(DB_TABLE, COL_ID + "="+ id, null)>0;
        }

        public boolean deleteAllLogs()
        {
            return mDB.delete(DB_TABLE, null, null)>0;
        }

        //get all bookmark
        public Cursor GetAllLogs(Integer i,String sortfield)
        {
            String sorted = "";
            if (i == 1 ) {
                sorted = "DESC";
            } else if (i == 2) {
                sorted = "ASC";
            }

            return mDB.query(DB_TABLE, new String[] {COL_ID, COL_TYPE,COL_IMAGE, COL_INFO,COL_IMAGE,COL_HOUR,COL_SEC,COL_MIN,COL_DAY,COL_MON,COL_YEAR,COL_SORT_DATE},
                            null, null, null, null, COL_DATE+" "+sorted);
        }

        public Cursor allrecords() {

            return mDB.query(DB_TABLE, new String[] {COL_ID, COL_TYPE,COL_IMAGE, COL_INFO,COL_IMAGE,COL_HOUR,COL_SEC,COL_MIN,COL_DAY,COL_MON,COL_YEAR,COL_SORT_DATE},
                    null, null, null, null, null);
        }

        //get a specific log by id
        public Cursor getLog(long id)
        {
            Cursor mCursor = mDB.query(true, DB_TABLE, new String[] {COL_ID, COL_TYPE,COL_IMAGE, COL_INFO,COL_IMAGE,COL_HOUR,COL_SEC,COL_MIN,COL_DAY,COL_MON,COL_YEAR},
                    COL_ID + "=" + id,
                    null, null, null, null, null);

            if (mCursor!=null)
                mCursor.moveToFirst();
            return mCursor;
        }

        //finally update the log
        public boolean updateLog(long id, String uinfo, String uimage,Integer utype,Integer uhour,Integer usec,Integer umin,Integer uday,Integer umonth,Integer uyear,Long ulongdate,Long udate)
        {
            ContentValues v = new ContentValues();
            v.put(COL_TYPE, utype);
            v.put(COL_INFO, uinfo);
            v.put(COL_IMAGE, uimage);
            v.put(COL_HOUR, uhour);
            v.put(COL_SEC, usec);
            v.put(COL_MIN, umin);
            v.put(COL_DAY, uday);
            v.put(COL_MON, umonth);
            v.put(COL_YEAR, uyear);
            v.put(COL_DATE, udate);
            v.put(COL_SORT_DATE, ulongdate);

            return mDB.update(DB_TABLE, v, COL_ID + "=" + id, null) > 0;
        }

        public static String prefixfieldzero(String number) {
            String result = String.valueOf(number);
          //  Log.d("PREFIX", "result starts with this = "+result);
            if (result.length() >1 ) {
             // Log.d("PREFIX", "NO ZEROES HERE");
             return number;
             }

           String zerofieldprefix = "";
           zerofieldprefix = "0"+result;
          // Log.d("PREFIX", zeroprefix);

              return zerofieldprefix ;
        }

    public static String getDateStr(String year, String month,String day) {
            return year+ prefixfieldzero(month)+ prefixfieldzero(day);
         }

}

Tried to run the SQL as per your latest answer but get this error :
03-01 00:20:05.379: E/AndroidRuntime(19060): Caused by: android.database.sqlite.SQLiteException: near "AS": syntax error: update TABLE AS TABLE_Temp1 set long_date = (select year || substr('00' || month ,-2,2  ) || substr('00' || ,day, -2 ,2)  from Log AS TABLE_Temp2 where TABLE_Temp1.id=TABLE_Temp2.id

Current SQL used to update long date to the combination of the year month and day:
populatesql = "update "+DB_TABLE + " AS LogTemp1 set long_date = (select year || substr('00' || month ,-2,2  ) || substr('00' || ,day, -2 ,2)  from "+DB_TABLE+" AS LogTemp2 where LogTemp1.id=LogTemp2.id   "  ;

I have also tried it as follows:
populatesql = "update "+DB_TABLE + " AS LogTemp1 set long_date = (select year || substr('00' || month ,-2,2  ) || substr('00' || ,day, -2 ,2)  from "+DB_TABLE+" AS LogTemp2 where **LogTemp1._id=LogTemp2._id**   "  ;

A: Okay, I finally got, what you want. You need an update statement that updates each row based on its current values. Of course you cannot call from the SQLite database to a function within your Java code. Thus everything must be done within your UPDATE statement within SQLite itself.
Given that, your statement should look like this:
UPDATE yourTable AS table1
SET date =
    (SELECT year ||
            substr('00' || month, -2, 2) ||
            substr('00' || day, -2, 2)
     FROM yourTable AS table2
     WHERE table1.id = table2.id);

You only have to replace the names I use here with the names you actually use and make a valid Java String of it.
The substr('00' || month, -2, 2) statements does what the lpad statement (which is not available in SQLite) of other database engines would do.
You can read it like this: Concatenate two zeros with a number, and take the rightmost two characters of the resulting string. The -2 means, start the substring count from the right edge, and the 2means take two characters as the resulting substring.
This lpad replacement is based on a blogpost by Jason Hinkle.

A: Assuming that COL_FIELD2... are String values, why not do something like this?
     if (newVersion==2) {
       populatesql = "update " + DB_TABLE +
                     " set field1 = " + getDateStr(COL_FIELD2, COL_FIELD3, COL_FIELD4);
     }

     getDateStr(String year, String month,String day) {
        return year + prefixzero(month) + prefixzero(day);
     }

     public String prefixzero(String number) {
        //Log.d("PREFIX", "result starts with this = "+result);
        if (number.length() > 1) {
           //Log.d("PREFIX", "NO ZEROES HERE");
           return number;
        }
        number = "0" + number;
        //Log.d("PREFIX", zeroprefix);
        return zeroprefix ;
     }

If they are int-values you could use the following prefixzero() method instead (and of course adapt the method signature of getDateStr() as well:
     public String prefixzero(int number) {
        if (number > 9) {
           return Integer.toString(number);
        }
        return "0" + number;
     }


text:
Q: Is there a way to have a global diff before doing a checkin in TFS With Visual Studio and TFS, is there a way to have a diff showing in a single page changes for each file before doing a checkin ? Instead of having to do diff of each file one after the other.
Similar to the UI of GitHub for Windows when doing a commit:

*

*file1

*

*diff

*file2

*

*diff

*...

Thanks,
Edit: as mentioned by Jehan33 the view I'm looking for looks like this (it's available on the web portal AFTER a commit):

A: This view is available after the check-in for the change sets where it will display all the file differences for a changeset in single page in web portal. Its not possible to do the same before the check-in.

A: Assuming your are using Team Foundation Version Control. If you right click on the folder where you have pending changes and click Compare. Select the options
"Show Items that exists only in source path", "Show Items that exists only in target path" and "Show items that are different", you will get the desired view.

A: The closest thing I've found was Diff All Files.
You can choose to combine all changed files into one and compare. Sadly there is no 'lines of context', however the code is open source and you can choose an external diff tool which may achieve this.


text:
Q: How do I pass in arguments to a curled script, that has been piped into the Python process? I have a Python script on a Github gist, which I can curl from my terminal with
curl -s https://gist.githubusercontent.com/.../script.py

The script has a main function that is executed, and I can pipe the output of the curl statement to Python, which executes the script.
curl -s https://gist.githubusercontent.com/.../script.py | python

The above statement works, but I want to provide some command line arguments to the script, without having to download it to a file. The problems I am facing are that the Python command treats any text following it as what to execute, and not as arguments for the piped file, so
curl -s https://gist.githubusercontent.com/.../script.py | python arg1 arg2

Does not work, nor does
curl -s https://gist.githubusercontent.com/.../script.py arg1 arg2 | python

How can I pass in both arguments to the file, either as standard input or command line options that my script can read?

A: From CLI help:

-      : program read from stdin (default; interactive mode if a tty)

So what you want is:
curl -s https://gist.githubusercontent.com/.../script.py | python - arg1 arg2

Note however, that - will also appear in sys.argv (in place of the script's filename)
$ echo "import sys; print sys.argv" | python - arg1 arg2
['-', 'arg1', 'arg2']

A: you could save the script locally and then execute it.
curl -o some_filename.py some_link
python some_filename.py arg1 arg2

you can also save a curl output to file with:
curl some_link > some_file.py


text:
Q: Android: Fail to add a button in a custom dialog Here is my code:
chartDialog = new Dialog(item_activity.this);
                chartDialog.setContentView(R.layout.customlayout);
                chartDialog.setTitle("Title                      ");
                TextView textItemDetailsDialog = (TextView) chartDialog.findViewById(R.id.textItemDetailsDialog);
                textItemDetailsDialog.setText("Details");
                img = (ImageView) chartDialog.findViewById(R.id.ImageView001);
                img.setImageBitmap(bitmap);
                Button toMap = (Button)findViewById(R.id.button_toMap);
                toMap.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        switchTabSpecial();
                    }
                });
                chartDialog.show();

However, it shows
03-26 23:30:10.822: E/AndroidRuntime(21394): java.lang.NullPointerException

at line:
toMap.setOnClickListener(new View.OnClickListener() {

Can I add a button in Dialog??
Please help...

A: As the Button is on the Dialog it should be as,
Button toMap = (Button)chartDialog.findViewById(R.id.button_toMap);


text:
Q: Installing pandas with dockerfile for ARM/V7 architecture gets stuck I want to build a Docker Image based on a Python 3.8 Image and then install some requirements including Pandas on a ARM/V7 platform. But when it comes to install the pip requirements the process gets stuck.
Is there any way to use a different base image or change something else in the Docker file to run pandas in a Docker image on a device with ARM/V7 architecture?
Here is the dockerfile:
FROM python:3.8@sha256:45fbccbc4681e8d9ef517d43f9d0eb8f17b2beac00b0f9697bbf85354ae8a266

WORKDIR /app
EXPOSE 8002/tcp

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .

CMD ["python3", "-m", "monitoring"]

The requirements.txt:
pandas==1.3.3
requests==2.26.0

When i am building the Image with docker build -t rfu . i get the following output:
Sending build context to Docker daemon   25.6kB
Step 1/7 : FROM python:3.8@sha256:45fbccbc4681e8d9ef517d43f9d0eb8f17b2beac00b0f9697bbf85354ae8a266
 ---> 0c665e140292
Step 2/7 : WORKDIR /app
 ---> Running in a5e6772c20f9
Removing intermediate container a5e6772c20f9
 ---> 5e7807e6f975
Step 3/7 : EXPOSE 8002/tcp
 ---> Running in d9f6cdc8aca1
Removing intermediate container d9f6cdc8aca1
 ---> bcd057ff5d87
Step 4/7 : COPY requirements.txt requirements.txt
 ---> d11ccce85d46
Step 5/7 : RUN pip install -r requirements.txt
 ---> Running in cd920fa4c18d
Collecting pandas==1.3.3
  Downloading pandas-1.3.3.tar.gz (4.7 MB)
  Installing build dependencies: started
  Installing build dependencies: still running...
  Installing build dependencies: still running...
  Installing build dependencies: still running...
  Installing build dependencies: still running...
  Installing build dependencies: still running...

This is where the process get stuck.

A: I guess it takes time for compiling... Just use precompiled packages from https://piwheels.org/
RUN pip install --index-url=https://www.piwheels.org/simple --no-cache-dir -r requirements.txt


text:
Q: Illegal unit of measurement error when typesetting chapter mark I have a class file like this
\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{tjutest}[2015/01/12 test commands]
\LoadClass[12pt,a4paper,openany]{book}

\newcommand*\MakePerPage[2][\@ne]{%
    \expandafter\def\csname c@pchk@#2\endcsname{\c@pchk@{#2}{#1}}%
    \newcounter{pcabs@#2}%
    \@addtoreset{pchk@#2}{#2}}
  \def\new@pagectr#1{\@newl@bel{pchk@#1}}
  \def\c@pchk@#1#2{\z@=\z@
    \begingroup
    \expandafter\let\expandafter\next\csname pchk@#1@\arabic{pcabs@#1}\endcsname
    \addtocounter{pcabs@#1}\@ne
    \expandafter\ifx\csname pchk@#1@\arabic{pcabs@#1}\endcsname\next
    \else \setcounter{#1}{#2}\fi
    \protected@edef\next{%
      \string\new@pagectr{#1}{\arabic{pcabs@#1}}{\noexpand\thepage}}%
    \protected@write\@auxout{}{\next}%
  \endgroup\global\z@}
\MakePerPage{footnote}

You can make the tex file like this.
\documentclass{tjutest}

\begin{document}
\frontmatter
\mainmatter
\chapter{The first}
\section{the first}
see if error exists
\end{document}

Then I got the error message like this.Can somebody help me?
! Illegal unit of measure (pt inserted).
<to be read again>
                   \global
l.6 \chapter{The first}

? x

If you don't mind, can you write down the process or way of you thinking about the problem not just the answer?

A: I guess from the name (but I'd never guess from the code) that the intention is to have per-page footnotes in which case I suggest you remove it all and just have
\RequirePackage[perpage]{footmisc}


text:
Q: Extra } or forgotten $ in equation with begin{cases} I've been staring at this for an hour now and don't see why I'm getting this error....can anyone help?
$k_\alpha = \begin{cases}
\frac{\log n}{\log \frac{n \log n}{m}} \left(1 + \alpha \frac{\log^2 \frac{n \log n}{m}}{\log \frac{n \log n}{m}} \right), & \text{if $\frac{n}{\text{polylog}(n)} \leq m \ll n \log n$} \\
\frac{m}{n} + \alpha \sqrt{2 \frac{m}{n} \log n} & \text{ if }n \log n \ll m \leq n \dot \text{polylog}(n) \\
\frac{m}{n} + \alpha \sqrt{2 \frac{m}{n} \log n \left( 1 - \frac{1}{\alpha} \frac{\log^2 n}{2 \log n} right)}, & \text{if $m \gg n \log(n)^3$}
\end{cases}$

A: You had wrong nesting of \text and math in the second line.
I suggest to use dcases* from mathtools, which automatically typesets the "conditions" part in text mode and use display style for the "formula" part.
\documentclass{article}
\usepackage{amsmath,mathtools}

\DeclareMathOperator{\polylog}{polylog}

\begin{document}

\[
k_\alpha =
\begin{dcases*}
\frac{\log n}{\log \frac{n \log n}{m}}
\left(
  1 + \alpha
  \frac{\log^2 \frac{n \log n}{m}}
       {\log \frac{n \log n}{m}}
\right),
& if $\dfrac{n}{\polylog(n)} \leq m \ll n \log n$
\\
\frac{m}{n} + \alpha \sqrt{2 \frac{m}{n} \log n}
& if $n \log n \ll m \leq n\polylog(n)$
\\
\frac{m}{n} + \alpha \sqrt{2 \frac{m}{n} \log n
\left(
  1 - \frac{1}{\alpha} \frac{\log^2 n}{2 \log n}
\right)},
& if $m \gg n \log^3 n$
\end{dcases*}
\]

\end{document}

Note also the definition for \polylog. I removed the multiplication sign which you probably used because of bad spacing with \text{polylog} and should have been \cdot (not \dot). I also changed \log(n)^3 into \log^3 n for consistency.

A: At least part of your difficulty keeping track of the $ signs is in contructions like
\text{if $\frac{n}{\text ...
which should be
\text{ if } \frac{n}{\text ...

so that don't have to enter math mode inside the \text{ } .


text:
Q: Epson XP-2100 printer driver breaks Mac OS X El Capitan boot I have a Macbook pro 2009 running both Mac OS X El Capitan and Ubuntu 21.04 and an Epson XP-2100 Wifi printer and scanner.
Installing the Epson recommended printer driver produces an error that was automatically reported to Apple.
The printer driver file :
mac2009% shasum /Volumes/Mac\ OS\
X/Users/alba/Downloads/Epson-Expression-Home-XP-2100-printer-driver-for-mac.dmg
e0012206ea2a471542134dfffb4e04491eb3d67a  /Volumes/Mac OS
X/Users/alba/Downloads/Epson-Expression-Home-XP-2100-printer-driver-for-mac.dmg

(Epson does not publish any hash of the file, which leaves a possibility of corruption.)
Thereafter, printing works but Mac OS X El Capitan does not boot any longer.  Booting in verbose mode stops with
AirPort: Limnk Up on en1
Got incomplete channel sequence length 0, should be 16
en1: ...
en1: ...
en1: ...
Unexpected payload found for message 9, dataLen 0
AirPort: RSN handshake complete on en1.single user mode

(I did not copy the ends of the lines beginning with en1:.)
Does anybody have an experience on another machine with El Capitan or another version of Mac OS X?
(On my machine the bug is reproducible after reinstalling Mac OS X.)
How to repair the Mac OS X system (apart from reinstalling) and safely install the printer driver  ?


text:
Q: How to set the left margins of enumerate items and itemizes items separately in global ways? A minimal working sample is as follows:
\documentclass{amsart}

\begin{document}
\begin{enumerate}
    \item maybe
    \item maybe
    \item maybe
\end{enumerate}

\begin{itemize}
    \item maybe
    \item maybe
    \item maybe
\end{itemize}

\end{document}

Goal: I hope that the left margin of enumerate items is 0, and also the left margin of itemize items is 0. I use the left margin for the space between the labels and left line of the type area.
Question: Are there global ways for theses? I know \setlength{\leftmargini}{ } can do it, but if we set up with that left margin of enumerate items as 0, then the left margin of itemize items can't be with that set up as 0.
The effect what I need is as follows:

A: I recommend using the enumitem package whenever you want to customise list environments. Using it you can set up different default behaviours for each list environment using \setlist - and even different behaviours for the different levels of nesting. For example, with
\setlist[enumerate]{leftmargin=10mm, label=\alph*)}
\setlist[itemize]{leftmargin=20mm}

For your desired output, with labels (1), (2), ... you do not need the label=\alph*) and can just use
 \setlist[enumerate]{leftmargin=10mm}

with whatever margin you would like. You can also define new list environments with commandslike
\newlist{mylist}{enumerate}{3}
\setlist[mylist]{...}

See the enumitem documentation for more details.
Here is the full code for the MWE above:
\documentclass{amsart}
\usepackage{enumitem}
\setlist[enumerate]{leftmargin=10mm, label=\alph*)}
\setlist[itemize]{leftmargin=20mm}

\begin{document}
\begin{enumerate}
    \item maybe
    \item maybe
    \item maybe
\end{enumerate}

\begin{itemize}
    \item maybe
    \item maybe
    \item maybe
\end{itemize}

\end{document}


text:
Q: Problem from mongoose: populate is not a function I have this code to create a new registration on RegistrationController, and the Registration Model
const Registration = require('../models/Registration');

module.exports = {
  async create(request, response) {
    const { user_id } = request.headers;
    const { eventId } = request.params;
    const { date } = request.body;

    const registration = await Registration.create({
      user: user_id,
      event: eventId,
      date
    });

    await registration
      .populate('event')
      .populate('user', '-password')
      .execPopulate(); //PROBLEM HERE

    return response.json(registration);
  },

const mongoose = require('mongoose');

const RegistrationSchema = new mongoose.Schema({
  date: String,
  approved: Boolean,
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User"
  },
  event: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Event"
  }
});

module.exports = mongoose.model('Registration', RegistrationSchema);

When i send a post request to insomnia, this error is shown:
(node:6260) UnhandledPromiseRejectionWarning: TypeError: registration.populate(...).populate is not a function. Can somebody help?

A: You need .find or .findOne, it will retrieve and populate from the DB the document that was just created :
await Registration
      .findOne({user: user_id})
      .populate('event')
      .populate('user', '-password')
      .lean() // faster, returns simple JSON
      .exec(); // returns a true Promise


text:
Q: Laravel: return multiple relationships I have the following table:

The table is called user_eggs and it stores the user eggs.
eggs are items with additional data (hatch_time)
As you can see, user 2 has 2 eggs, which are items 46 and 47.
My items table stores the item general information such as name, image, description, etc...
How I can return the user eggs using $user->eggs() including the item data in my items table of the egg item_id?
I tried:
User Model:
/**
     * Get the eggs
     */
    public function eggs()
    {
        return $this->belongsToMany(Egg::Class, 'user_eggs','user_id','item_id')
        ->withPivot('id','hatch_time');
    }

but $user->eggs() returns an empty array.
Any ideas?

A: A simple approach will be:
in your UserEgg model define:
    /**
     * Get the user associated with egg.
     */
    public function _user()
    {
        return $this->belongsTo('App\User','user_id');
    }
    /**
     * Get the item associated with egg.
     */
    public function item()
    {
        return $this->belongsTo('App\Item','item_id');
    }

then in your controller:
use the model to extract everything like this:
$userEggs = UserEgg::where('user_id',2)->get();
foreach($userEggs as $userEgg){
    $associateduser = $userEgg->_user;
    $associatedItem = $userEgg->item;
}

A: Short answer
If you loop through the user's eggs:
foreach($user->eggs as $egg){
    $item = Item::find($egg->pivot->item_id);
}

If you want to query:
$user->eggs()->wherePivot('item_id', 1)->get();

Long answer
From the Laravel Documentation
Retrieving Intermediate Table Columns
As you have already learned, working with many-to-many relations requires the presence of an intermediate table. Eloquent provides some very helpful ways of interacting with this table. For example, let's assume our User object has many Role objects that it is related to. After accessing this relationship, we may access the intermediate table using the pivot attribute on the models:
$user = App\User::find(1);

foreach ($user->roles as $role) {
    echo $role->pivot->created_at;
}

Notice that each Role model we retrieve is automatically assigned a pivot attribute. This attribute contains a model representing the intermediate table, and may be used like any other Eloquent model.
By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:
return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');

If you want your pivot table to have automatically maintained created_at and updated_at timestamps, use the withTimestamps method on the relationship definition:
return $this->belongsToMany('App\Role')->withTimestamps();

Filtering Relationships Via Intermediate Table Columns
You can also filter the results returned by belongsToMany using the wherePivot and wherePivotIn methods when defining the relationship:
return $this->belongsToMany('App\Role')->wherePivot('approved', 1);

return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]);


text:
Q: I set wlan but the no ping over wifi I set wlan0 config (uncomment bcm43 from blacklist):
root@NanoPC-T2:~# ifconfig -a
eth0      Link encap:Ethernet  HWaddr 5e:a5:4f:cc:83:8a
          inet addr:195.165.101.232  Bcast:195.165.101.255  Mask:255.255.255.0
          inet6 addr: fe80::7ca8:5fff:fecc:738a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:21331 errors:0 dropped:11440 overruns:0 frame:0
          TX packets:390 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1734079 (1.7 MB)  TX bytes:64331 (64.3 KB)
          Interrupt:48

ip6tnl0   Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          NOARP  MTU:1452  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:3958 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3958 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:293200 (293.2 KB)  TX bytes:293200 (293.2 KB)

sit0      Link encap:IPv6-in-IPv4
          NOARP  MTU:1480  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

usb0      Link encap:Ethernet  HWaddr e2:47:73:46:b9:8f
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

wlan0     Link encap:Ethernet  HWaddr 15:a1:a2:a3:c5:4e
          inet6 addr: fe80::25d4:a2ff:fea3:c54e/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:468 (468.0 B)

and also set /etc/network/interfaces
 cat /etc/network/interfaces
auto lo eth0
iface lo inet loopback
iface eth0 inet static
address 195.165.101.232
netmask 255.255.255.0
gateway 195.165.101.254

iface wlan0 inet static
address 195.165.101.232
netmask 255.255.255.0
gateway 195.165.101.254
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

and wpa_supplicant.conf
 cat /etc/wpa_supplicant/wpa_supplicant.conf
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=CN
network={
ssid="V01"
psk="123456"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP
auth_alg=OPEN
}

and I do this also ifconfig wlan0 up but when I disconnect Ethernet I can not connect or ping to that IP from wifi.
nmcli c
NAME      UUID                                  TYPE             DEVICE
V01    0c4435f2-7301-8574-9b1b-deb7fd2a7603  802-11-wireless  --
V1 1  80b21422-c7ea-568c-8b4c-6f1d8a9dc9f8  802-11-wireless  --

A: You cannot use the same IP address on several interfaces (you may combine several interfaces to one using bonding, though).
Thus (as you can see in your ifconfig output) wlan0 is not assigned an IPv4 address.


text:
Q: How can I improve garbage collector performance of .NET 4.0 in highly concurrent code? I am using the task parallel library from .NET framework 4 (specifically Parallel.For and Parallel.ForEach) however I am getting extremely mediocre speed-ups when parallelizing some tasks which look like they should be easily parallelized on a dual-core machine.
In profiling the system, it looks like there is a lot of thread synchronization going on because of the garbage collector. I am doing a lot of allocation of objects, so I am wondering how I can improve the concurrency while minimizing a rewrite of my code.
For example are there some techniques that can be useful in this situation:

*

*Should I try to manage the GC manually?

*Should I be using Dispose?

*Should I be pinning objects?

*Should I be doing other unsafe code tricks?

POSTSCRIPT:
The problem is not the GC running too often, it is that the GC prevents concurrent code from being running in parallel efficiently. I also don't consider "allocate fewer objects" to be an acceptable answer. That requires rewriting too much code to work around a poorly parallelized garbage collector.
I already found one trick which helped overall performance (using gcServer) but it didn't help the concurrent performance. In other words Parallel.For was only 20% faster than a serial For loop, on an embarrassingly parallel task.
POST-POSTSCRIPT:
Okay, let me explain further, I have a rather big and complex program: an optimizing interpreter. It is fast enough, but I want its performance when given parallel tasks (primitive operations built into my language) to scale well as more cores are available. I allocate lots of small object during evaluations. The whole interpreter design is based on all values being derived from a single polymorphic base object. This works great in a single-threaded application, but when we try to apply the Task Parallel Library to parallel evaluations there is no advantage.
After a lot of investigation into why the Task Parallel Library was not properly distributing work across cores for these tasks, it seems the culprit is the GC. Apparently the GC seems to act as a bottle-neck because it does some behind the scene thread synchronization that I don't understand.
What I need to know is: what exactly is the GC doing that can cause heavily concurrent code to perform badly when it does lots of allocations, and how we can work around that other than just allocating fewer objects. That approach has already occurred to me, and would require a significant rewrite of a lot of code.

A: If GC is running too often due to too many objects being allocated/GC-ed, try to allocate fewer of them :)
Depending on you scenario - try to reuse existing objects, create an object pool, use "lighter" objects that do not put so much memory pressure (or larger to reduce the number of objects allocated).
Do not try to "manage GC" by calling GC.Collect explicitly, it very rarely pays off (Rico Mariani says so)
or http://blogs.msdn.com/ricom/archive/2003/12/02/40780.aspx

A: 1) You can't and shouldn't manage the GC manually.
2) Dispose is only an indication to the GC, it will anyway pass whenever he feels right. :P
The only way to avoid these problems is to profile your app and try as much as possible to avoid allocating new objects.
When you've find what's going into the garbage collector, try some pooling technique to reuse those data and avoid recreating it every time.
EDIT :
Whenever the GC is running ALL threads must go in a sleep state to allow it to do his work. That's the reason of the slowdown if the collections are many as in your case. There is no possible other way to manage this than to reduce the new objects generation.

A: For your four points:

*

*See How can I improve garbage collector performance of .NET 4.0 in highly concurrent code? (1)

*You should dispose if your objects hold resources, especially resources to non-managed objects. Dispose gets executed immediately. A possible finalizer (~ Destructor in C++) gets only called when the GC runs and the object is removed from memory.

*Pinning the objects makes only sense if the object is passed to a non-managed piece of code, e.g. an unmanaged c++ dll. Othewise, leave the garbage collector to do its share in keeping the memory tidy. Pinning also can lead to memory fragmentation.

*Not if you don't have to.

One thing to think about, is to move the allocation out of your loops - if that is possible. In many cases when you can do this, it also allows you to reuse already allocated objects, thus providing additional performance (at least that what's my experience shows) (See also How can I improve garbage collector performance of .NET 4.0 in highly concurrent code?).
The grade of parallel execution always depends on the task you are doing, in case of an computation the maximum achievable parallelism is < n times, where n is the number of processors - pure computation. In case of input or output operations n will usually be exceeded.

A: I have an idea -- why not try an alternate GC implementation? .NET provides three.
http://blogs.msdn.com/maoni/archive/2004/09/25/234273.aspx
Based on your problem description, I'd be curious to see how the server GC works out for you, since it provides a separate heap per core. It's probably also worth looking into the Background GC mode that .NET 4 adds.
http://blogs.msdn.com/maoni/archive/2008/11/19/so-what-s-new-in-the-clr-4-0-gc.aspx
Hopefully that's a little more helpful to your specific case than the answers so far.

A: This is a fact of life.  Almost all memory management schemes serialize code that looks embarrassingly parallel to some degree.  I think C# has thread-local allocators, so it should only be serializing on collections.  Nonetheless, I'd recommend pooling/reusing your most frequently allocated objects and arrays and maybe convert some small, non-polymorphic objects to structs and seeing if that helps.

A:
In profiling the system, it looks like there is a lot of thread synchronization going on because of the garbage collector. I am doing a lot of allocation of objects, so I am wondering how I can improve the concurrency while minimizing a rewrite of my code.

Don't do a lot of allocation of objects. The only universal way to speed up your code is to make it do less work. If the GC takes too much time, there are two theoretical options:

*

*Implement a better GC, or

*Give the GC less work to do

The first point is pretty much impossible. It'd take a lot of hacking to replace the .NET GC in the first place, and it'd take a lot of work to design a GC that's even remotely as efficient as the .NET one.
The second point is really your only option: If a garbage collection requires synchronization, make sure that fewer collections take place. They generally occur when the gen0 heap is too full to satisfy an allocation request.
So make sure that doesn't happen. Don't allocate so many objects. You have several ways to avoid it:

*

*using (stack-allocated) structs instead of classes may help reduce the GC pressure. Especially small, short-lived objects would probably benefit from being converted to structs,

*Reuse the objects you allocate. Longer-lived objects are moved to the larger heaps where collections rarely take place. Move allocations out of loops, for example.

A:
what exactly is the GC doing that can cause heavily concurrent code to perform badly when it does lots of allocations

The .NET GC is probably serializing the copying and collection of your allocated objects. The .NET GC is a standard generational collector that splits the nursery (gen0) into separate arenas for separate cores/threads in order to handle some parallelism. But the collection of all the data allocated from all the cores is apparently done serially.
However, I am not convinced that the GC is the source of your problem in this case. There are many ways to achieve poor scalability on a multicore. Failing to take advantage of caches is another common one and it culminates in all cores stalling on accesses to shared memory, killing scalability in an almost undetectable way...

A: Parallel tasks and even raw Threading are not magic bullets to make your code go faster.  If you have any locks, resources, or only have a few cores you can slow code down my trying to be multi-threaded.  You also need to make sure you are not having context swaps and hopefully you have more then 4 cores.  (Don't forget the GC, CLR, Windows, as well as other applications and services are contending for resources/cycles.)
You should also know that pinning and unsafe code could slowdown some actions.  They require special operations from both the CLR and the GC to make sure that memory and resources are kept safe (for example the GC can't compact as well if you pin or if you are unsafe.)
The Parallel task library has been created for general purpose uses.  If you need highly optimized code you may need to manage your own threads as well.  (Unlike many of the blogs say... there are no magic bullets in this profession.)
Your best bet will be to create an instance of your worker class per thread to avoid the construction and deconstruction per action.  Check out ThreadStaticAttribute.  It is my understanding there are other options in .Net 4.0 but I have not had a chance to work with them yet.


text:
Q: Problema al guardar unos archivos al publicar una aplicación de windows Forms resulta que en la carpeta bin\Debug debo meter unos archivos para que al momento de generar el .exe e instalarlo, dichos archivos también queden
Cuando publico la aplicación en la opción Compilar --> Publicar, me generá el .exe, pero lo que meto en la carpeta bin\Debug no me queda. Como hago entonces para generar el .exe y me tome dichos archivos.
Muchas Gracias

A: En las propiedades del proyecto selecciona Eventos de Compilación e ingresas un comando para copiar algún archivo post compilación.
En el ejemplo de la imagen, se copia el archivo mi-archivo.dll en la carpeta bin/Debug después de compilar el proyecto

$(ProjectDir)/libs indica que el archivo a copiar se encuentra en la raiz del proyecto dentro de una carpeta llamada libs.


text:
Q: encountering poi exceptions while running my Java code The exceptions are :
         Exception in thread "AWT-EventQueue-1" org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:41)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:218)
at defg.jButton4ActionPerformed(defg.java:984)
at defg.access$900(defg.java:86)
at defg$9.actionPerformed(defg.java:547)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)

... a lot more [edited for brevity]

Code snipplet [copied from comment]:
try {
  Thread.sleep(1000);
}
catch (InterruptedException ex) {
  Logger.getLogger(def.class.getName()).log(Level.SEVERE, null, ex);
}

try {
  System.out.println("njfklasndjklasdnl");
  File inputFile = new File(str1);
  File inputFile1 = new File (str2);
  XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(inputFile));
  XSSFWorkbook wb1 =new XSSFWorkbook(new FileInputStream(inputFile1));
  System.out.println(wb1.getNumberOfSheets());
  XSSFSheet sheettemp=wb1.createSheet("temp");
  XSSFSheet sheeta= wb1.createSheet("Repeatitions");

A: Try creating a new project, adding only the necessary jars (P


text:
Q: NASM - Outputting string after applying caesar cipher Am trying to do a program which does the following: it takes a file's input: 10 characters, all CAPs, advances them all by 3 positions in the alphabet each, and those that go past the Z ascii code, then get 26 positions subtracted. Z->D, A->D, D->H, etc.
Code: character + 3
if (Code > 26)
Code: Code - 26
My readByte function, which does precisely what it says: each line is well commented!
mov ecx, 0
mov edi, buffer  ; buffer is memory address of 1st char of file

readByte:

mov al, [edi]   ; move x's position content to al
add al, 3       ; add 3 to al
cmp al, MAXHEX  ; compare with 'Z'
jg dec          ; if al > 'Z', jump to dec
call putChar    ; if al < 'Z', print char
jmp nextByte    ; grab next character!

dec:
sub al, 26      ; decrement al by 26
call putChar    ; print char
jmp nextByte    ; grab next char

nextByte:

cmp ecx,[filesize] ; compare counter and filesize I had returned from readFile
jge terminar       ; if it has read all chars, end program
inc ecx        ; increment counter
inc edi            ; advance to next file address position, so as to get next character
jmp readByte       ; go read the byte again

And this is the putChar macro, which was handed to us for the essay:
; putChar   - write a char to stdout (stdout)
;   Argument(or whatever you call it in assembly)
;      al: char to write
;   Return: has none
putChar:
    push ebx
    push ecx
    push edx
    push eax    ; al has the ascii code to write
    mov ecx, esp  ; esp points to top of stack
    mov edx, 1  ; write a character
    mov  eax, SYS_WRITE  ; 4
    mov  ebx, 1   ; channel of screen ecran - stdout
    int LINUX_CALL
    pop eax
    pop edx
    pop ecx
    pop ebx
    ret

Basically, I can get the program to work perfectly, if I change
add al, 3       ; add 3 to al

To a different value. I have no clue what's wrong. Spent atleat a dozen hours on this one simple thing.


text:
Q: Django accessing database When using the following LIMIT clause in the Django models API --
People.objects.all()[5000000:5000000+5]
Does the database have to go through all 5M records in order to return just these 5 records? Or is it non-linear in its access?

A: It will go at least through the index table for the primary key of your People table. This question has in my opinion nothing to do about how Django handles this. Django will handle it as your database will. Django's ORM will just transform it into a query similiar to this one:
SELECT * FROM peoples OFFSET 5000000 LIMIT 5;

A: In short it does do a scan until that point and get the number of records you specify. This actually depends on your database, different databases have different performance on this query. It is not a random access, you should expect the same records to be returned if you do this 5 times, assuming your data has not changed. If you do an order_by you'd have even more predictable results.


text:
Q: Multiple monitors simple workspace sharing I currently have the following config of workspaces:

1  2
3  4

If I plug a second monitor in is there a way to switch simply to:

1  |  2
3  |  4

I.e. no change to the configuration, but simply having two workspaces stacked vertically on each monitor. I'd be happy if they changed together and if horizontal movement was disabled.
Does any configuration like this exist, and secondly how quickly is it possible to move between configs?
I am using Ubuntu 14.04, gnome without Unity.


text:
Q: Using form_tag to create a button So I have this code in my views to create a button that approves all 5 star reviews. The issue I'm facing is that button_to doesn't hide the params and order_ids is about 200 order objects. So when I click on the button, I get the error
Request-URI Too Large WEBrick::HTTPStatus::RequestURITooLarge
I think I need to use the form_tag helper but I'm not too sure how to make a button with form_tag. Or how to link the two things.
<div style="margin: 0 0 50px 0">
  <%= button_to "Approve reviews with 5 stars",
    { action: :approve_reviews, order_ids: @orders, rating: 5 }
    , method: :post %>
</div>

A: You can simply add params:{} in the end to your button_to
<%= button_to "Approve reviews with 5 stars", action: :approve_reviews, params: {order_ids: @orders, rating: 5} %>
Note: by default the method will be post so you don't have to specify the method.
Hope it helps!

A: Try something like this:
<%= form_tag({ action: :approve_reviews, rating: 5 }) do -%>
  <%= hidden_field_tag 'order_ids', @orders %>
  <%= submit_tag 'Approve reviews with 5 stars' %>
<%= end -%>

A: I'd recommend doing it this way -

*

*It is a bad idea to send so much data through the URL

*Have a form and a hidden field that contains the values for the order IDs (and probably Rating, unless you have your routes configured for it)

*Have a simple button that just submits the form when clicked
<%= form_tag({ :action => :approve_reviews }) do -%>
    <%= hidden_field_tag :order_ids, :value => @orders %>
    <%= hidden_field_tag :rating, :value => 5 %>
    <%= submit_tag "Approve reviews with 5 stars" %>
 <% end -%>


text:
Q: C program division error? When i run the following code i get correct answers for addition,subtraction,multiplication but division gives me wrong answer:
#include<stdio.h>
#include<conio.h>

int main()
{
    int num1, num2, add, sub, mul, div;
    printf("Enter numbers \n");
    scanf_s("%d %d", &num1, &num2);

    add = num1 + num2;
    sub = num1 - num2;
    mul = num1 * num2;
    div = (float)(num1 / num2);   // typecasting

    printf("Addition answer = %d \n", add);
    printf("Subtraction answer = %d \n", sub);
    printf("Multiplication answer = %d \n", mul);
    printf("Division answer = %.2f \n", div);

    _getch();
    return 0;
    }

what would be the reason of Division = 0.00??

A: div = (float)(num1 / num2);   // typecasting

is wrong, you should cast the operands
div = (float)num1 / (float)num2;

Of course, you should have declared
float div;

and with all warnings a good compiler (like GCC invoked as gcc -Wall -g) would have noticed the discrepancy for printf
Actually, you'll better use double instead of float  since printf(3) with %.2f expects a double argument... (but a float value is promoted to a double one when passing arguments to printf ....)
So your code should actually be
double div = (double)num1 / (double)num2;
printf("Division answer = %.2f \n", div);

Read about floating point and the floating point guide and what every programmer should know about floating point

A: You declare div as an integer, but print it as a floating-point number. The binary formats of integers and floating point numbers are not the same, so it causes the wrong value to be printed.
Either declare div as a float, or print it as the integer it is.
You should build with more warnings, as this would have been the cause of two warnings: First the assignment of a float to an int, then the printing of an int as a float.

A: float num1, num2, add, sub, mul, div;

needs to be a float or it will floor down to 0.00
Or you need to cast them with a float

A: It is doing integer division. I.e whole numbers - then convert to floating point

A: dev is defined as an integer, and then printed with a %f format. You need to define it as a float.

A: #include<stdio.h>
#include<conio.h>

int main()
{
int num1, num2, add, sub, mul;
float div;
printf("Enter numbers \n");
scanf_s("%d %d", &num1, &num2);

add = num1 + num2;
sub = num1 - num2;
mul = num1 * num2;
div = (float)(num1 / num2);   // typecasting

printf("Addition answer = %d \n", add);
printf("Subtraction answer = %d \n", sub);
printf("Multiplication answer = %d \n", mul);
printf("Division answer = %.2f \n", div);

_getch();
return 0;
}

A: First of all you declared div as integer. so If you will store division of two float number in integer variable then you will get wrong answer.
You should declare div as float. Like,
float div;

and your type conversion should like,
div = (float)num1/(float) num2;

Then you will get correct answer.


text:
Q: Can Junkrat's RIP-Tire be healed? While playing Mercy in competitive play, I noticed that I could view the health my allied Junkrat's RIP-Tire. I was even shown a critical health indicator when the Tire had nearly been destroyed.
This made me wonder whether it was possible to heal an allied Junkrat's RIP-Tire, similar to D.Va's mech during a self-destruct.
I know that a RIP-Tire can be healed using health packs, but I'm not sure whether or not it can be healed by support heroes like Ana or Lucio.

A: You can not heal any Hero deployables or buildables in any way (with the exception of Torbjörn healing his own Turrets).
Though previously it was possible to heal Torbjorn's turrets and Junkrat's tire with health pick-ups, that was patched out at some point without making it into the patch notes.
Some examples of buildables not being healed:

*

*Torbjörn's Turret on Health Pickup

*Symettra's Shield Generator on Health Pickup

*Junkrat's Rip-Tire on Health Pickup

A: I don't have any source for the following apart from my own personal experience:
The Rip tire shares the same mechanic that the trap, torb's turret and Symetra's ultimate has:
They have HP that can heal from health packs but not from heroes.


text:
Q: how to access objective-c methods from c++ callback I want to use a c++ library in an objective-c objective. The c++ library informs my objective-c object about certain value changes of library objects. Therefore I pass a c++ callback function to the library. The callback function looks like this:
void positionChanged(int position)

Unfortunately there is no void* data argument in the callback that I could use to pass a pointer to my objective-c object. Normally I could use such a pointer to get access to my object variables and methods from the c++ callback function whenever the callback is be called. (And I can't change the callback function concerning that).
How can I make a connection between the c++ callback function and my objective-c object to have access to my objective-c object from the c++ callback?


text:
Q: Performance of $in when querying Mongo At the moment I am testing the performance of a Mongo query using $in, however I am using a test environment and we do not have all the same data we do in production. As a result, most of the records are not found during the query (but I expect most of them to be in production).
My question is this: Will the performance change depending on how many records are found?

A: It depends if you have created the index on the key you are going to put for $in query. So in that case it will have the time complexity of Log(n) where n will be the number of records in the collection which i think is the best complexity you can get.
But if you are asking about the data that will be returned from the DB server to the application server , yes it will have the impact but i think it should not be significant in todays time.


text:
Q: inequality involving $(xy+yz+zx)^3$ and the $pqr$ method For non-negative numbers $x$, $y$, and $z$ the claim is that:
$$(xy+yz+zx)^3+9 x^2 y^2 z^2 \geq 4 (x+y+z)(xy+yz+zx)xyz$$
Without loss of generality, one may assume that $x+y+z=1$ so that $xyz\le\frac{1}{27}$ and $xy+yz+zx\le\frac13$. I have not seen how Schur's inequality is helpful.

A: Let $xy=c$, $xz=b$ and $yz=a$.
Thus, we need to prove that
$$(a+b+c)^3+9abc\geq4(a+b+c)(ab+ac+bc)$$ or
$$\sum_{cyc}(a^3-a^2b-a^2c+abc)\geq0,$$ which is Schur.


text:
Q: Python proxy - receiving http header from the server I'm building a proxy server in Python and I got a question.
First I'll be showing you a part of my code that presents the receiving data from the client: If there is data from the client, it downloads the content of the requested website (By using the urllib library) and then sending to the client 200 OK with the content length and the content itself:
        data = currentSocket.recv(4096)
        if data == "":
            open_client_sockets.remove(currentSocket)
            print 'Conn is closed'
        else:

            dataSplit = data.split("\r\n")
            Host = HostFliter(dataSplit)
            print Host, " Host"
            if Host == "":
                break
            contentURL = urllib.urlopen(Host)
            content_to_send = contentURL.read()
            currentSocket.send("HTTP/1.1 200 OK\r\nContent-Length:"+str(len(content_to_send))+"\r\n\r\n"+str(content_to_send))
            contentURL.close()

**The variable "Host" contains the url of the website.
Now for the question:
Where do I get the headers from the server and then send them to the client?
**The libraries I use: socket, select, urllib.
**This is for the select library:
rlist, wlist, xlist = select.select([serverSocket] + open_client_sockets, open_client_sockets, [])

A: The HTTP response syntax is as follows

HTTP/1.1 200 OK
  Content-Type: text/html
  Content-Length: 38
Hello world!

So you need to send headers just before \r\n separated by \n in above format.


text:
Q: java.io.IOException: Corrupt form data: premature ending Am having a problem with my Jsp application while usind Oreilly's multipart classes.
The problem is that my app is running very well when I run it on some machines, but when I try running it on some servers for some reasons I dont understand, It throws this error :  java.io.IOException: Corrupt form data: premature ending
        at com.oreilly.servlet.multipart.MultipartParser.(MultipartParser.java:205)
        at com.oreilly.servlet.multipart.MultipartParser.(MultipartParser.java:119)
 The above is just part of the logs am getting.
Someone tell me:- why is it that the app runs very well on some servers, while it gives me a problem when I try to run it from a different one?
What could be possible solutions to my problem?
Am running glassfish server3 on all servers.

A: The ancient Oreilly multipart parser has some bugs. See also this related question for an overview Corrupt form data: premature ending (Resolved). Rather use Apache Commons FileUpload or just the new Servlet 3.0 builtin request.getPart() method. See also How to upload files to server using JSP/Servlet?

A: I found the answer to my problem. It's the server version I was using The latest glassfish release has issues and that was such.. I installed Glassfish3 for linux and it worked perfectly well!