text:
Q: nested if else syntax error php    it says syntax error t_else, what could be the problem?

it really is making me crazy for finding what did i do wrong in this code
what could be myy mistake here?
<?php
include("../mysql_connect.php");
if (isset($_POST['search_form'])) {
    $page1 = $_GET['page'];
    if ($page1 == "" || $page1 == 1) {
        $page1 = 0;
    }
    else {
        $page1 = ($page1 * 5) - 5;
    }
    $query = "select * from tbl_news where news_title like '$_POST[search]' || news_author like '$_POST[search]' ";
    $result = mysql_query($query);
    while ($row = mysql_fetch_array($result)) {
        ?>

            <col width="50%"></col>
            <col width="40%"></col>
            <col width="20%"></col>

                    a href="news_view.php?id=<?php echo $row['news_id']; ?>">
                    <img src="<?php echo $row['news_image_location'] . $row['news_image']; ?>" height="300" width="500">

                Title: <?php echo $row['news_title']; ?>

                Author: <?php echo $row['news_author']; ?>

                Date: <?php echo $row['news_date_filed']; ?>

        <?php
    }
    $query1 = "select * from tbl_news where news_title like '$_POST[search]' || news_author like '$_POST[search]'";
    $result1 = mysql_query($query1);
    $row1 = mysql_num_rows($result1);
    $pagecount = $row1 / 5;
    $pagecount = ceil($pagecount);

    for ($count = 1; $count <= $pagecount; $count++) {
        ?>

        <a href="news.php?page=<?php echo $count; ?>"><?php echo $count ?>

        <?php
    }
}
else{
    $page1 = $_GET['page'];
    if ($page1 == "" || $page1 == 1) {
        $page1 = 0;
    }
    else {
        $page1 = ($page1 * 5) - 5;
    }
    $query = "select * from tbl_news where news_status='Active' limit $page1,5";
    $result = mysql_query($query);
    while ($row = mysql_fetch_array($result)) {
        ?>

            <col width="50%"></col>
            <col width="40%"></col>
            <col width="20%"></col>

                    <a href="news_view.php?id=<?php echo $row['news_id']; ?>">
                        <img src="<?php echo $row['news_image_location'] . $row['news_image']; ?>" height="300"
                             width="500">

                Title: <?php echo $row['news_title']; ?>

                Author: <?php echo $row['news_author']; ?>

                Date: <?php echo $row['news_date_filed']; ?>

        <?php
    }
    ?>
    <?php
    $query1 = "select * from tbl_news where news_status='Active'";
    $result1 = mysql_query($query1);
    $row1 = mysql_num_rows($result1);
    $pagecount = $row1 / 5;
    $pagecount = ceil($pagecount);

    for ($count = 1; $count <= $pagecount; $count++) {
        ?>

        <a href="news.php?page=<?php echo $count; ?>"><?php echo $count ?>

        <?php # code...
    }
}
?>

here is the full code, of what errror gives me, please help me guys it takes me a a lot of time having this kind of problem i already tried everything i could but maybe you guys could me solve my problem hahahaha it really drained my mind here , im already mindblown on what is the my currently facing problem

A: You are missing < at the a tag inside the first while loop (exactly on line 21 when I copy/paste your code). That might be the reason it doesn't recognize the else statement, because it can't get to it properly.

A: try this code. may be it resolve your problem.
I have corrected some syntax mistake in your code.
 <?php
                  include("../mysql_connect.php");
                    if (isset($_POST['search_form'])) {
                      $page1=$_GET['page'];
                      if ($page1=="" || $page1==1) {
                          $page1=0;
                      }
                      else{
                          $page1=($page1*5)-5;
                      }
                      $query="select * from tbl_news where news_title like '$_POST[search]' || news_author like '$_POST[search]' ";
                      $result=mysql_query($query);
                      while ($row=mysql_fetch_array($result)) {
                  ?>

                                  <col width="50%"></col>
                                  <col width="40%"></col>
                                  <col width="20%"></col>

                                    <a href="news_view.php?id=<?php echo $row['news_id'];?>">
                                       <img src="<?php echo $row['news_image_location'].$row['news_image'];?>" height="300" width="500">

                                  Title: <?php echo $row['news_title'];?>

                                  Author: <?php echo $row['news_author'];?>

                                  Date: <?php echo $row['news_date_filed'];?>

                  <?php
                      }
                      $query1="select * from tbl_news where news_title like '$_POST[search]' || news_author like '$_POST[search]'";
                      $result1=mysql_query($query1);
                      $row1=mysql_num_rows($result1);
                      $pagecount=$row1/5;
                      $pagecount=ceil($pagecount);

                      for ($count=1; $count <= $pagecount ; $count++) {

     ?>

                                  <a href="news.php?page=<?php echo $count;?>"><?php echo $count?>

                <?php
                      }
                    }else{
                          $page1=$_GET['page'];
                          if ($page1=="" || $page1==1) {
                              $page1=0;
                          }
                          else{
                              $page1=($page1*5)-5;
                          }
                          $query="select * from tbl_news where news_status='Active' limit $page1,5";
                          $result=mysql_query($query);
                          while ($row=mysql_fetch_array($result)) {
                                            ?>

                                      <col width="50%"></col>
                                      <col width="40%"></col>
                                      <col width="20%"></col>

                                        <a href="news_view.php?id=<?php echo $row['news_id'];?>">
                                          <img src="<?php echo $row['news_image_location'].$row['news_image'];?>" height="300" width="500">

                                      Title: <?php echo $row['news_title'];?>

                                      Author: <?php echo $row['news_author'];?>

                                      Date: <?php echo $row['news_date_filed'];?>

                      <?php
                          }
                          $query1="select * from tbl_news where news_status='Active'";
                          $result1=mysql_query($query1);
                          $row1=mysql_num_rows($result1);
                          $pagecount=$row1/5;
                          $pagecount=ceil($pagecount);

                          for ($count=1; $count <= $pagecount ; $count++) {
                      ?>

                                      <a href="news.php?page=<?php echo $count;?>"><?php echo $count?>

                      <?php        # code...
                          }
                     }
                      ?>


text:
Q: how to use fiddler to make Post request I have capured the Post request from Fiddler , now i wanted to re execute this Post reqest from Fiddler itself.
Please suggest me steps to re execute the Post request from fiddler
I am using Fiddler4
Thanks

A: You can reissue requests in Fiddler in many ways. For instance, you can simply right-click any Session in the Web Sessions list and choose Replay from the context menu. Alternatively, you can drag and drop a Session to the Composer tab and edit it before resending.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best way to synchronize contacts I am developing an Android app. In this app, I have to sync contacts with "Android Contacts".
I read some complicate writing about this subject. For example:
http://www.c99.org/2010/01/23/writing-an-android-sync-provider-part-2/
This is good example for sync contacts but I don't think create a new account for this. So decide sync contacts manually and search again. I found ContentObserver.
how to listen for changes in Contact Database
My question is:
public class DenemeObserverActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Log.d("MyTag", "OnCreate---");
    //this.getApplicationContext().getContentResolver().registerContentObserver (ContactsContract.Contacts.CONTENT_URI, true, contentObserver);

    Cursor cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    cursor.setNotificationUri(this.getApplicationContext().getContentResolver(), ContactsContract.Contacts.CONTENT_URI);
    this.getApplicationContext().getContentResolver().notifyChange(ContactsContract.Contacts.CONTENT_URI, null);
    cursor.registerContentObserver(contentObserver);

}

private class MyContentObserver extends ContentObserver {

    public MyContentObserver() {
        super(null);
    }

    @Override
    public boolean deliverSelfNotifications() {
        Log.d("MyTag", "DeliverSelfNotifications---");
        return true;
        }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Log.d("MyTag", "onChanges---");
    }

}

MyContentObserver contentObserver = new MyContentObserver();

In this code if I remove these lines:
Cursor cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
cursor.setNotificationUri(this.getApplicationContext().getContentResolver(), ContactsContract.Contacts.CONTENT_URI);
this.getApplicationContext().getContentResolver().notifyChange(ContactsContract.Contacts.CONTENT_URI, null);
cursor.registerContentObserver(contentObserver);

and unmark:
//this.getApplicationContext().getContentResolver().registerContentObserver (ContactsContract.Contacts.CONTENT_URI, true, contentObserver);
I can handle changes contacts changes. But Android just calling onChange method.
If a try with this code (with cursor) when contacts change, I can't see any call for onChange().
How can I handle "Which row was changed?".
OR
Can I use AbstractThreadedSyncAdapter for sync contacts without a new Account, if so how?


text:
Q: Problems with setters in Java - Internet Bill Program Hi I am having some problems assigning values in the object I am trying to make, it is calling the variable I set originally and not the one I set using my setter method, the odd thing is that it seems to pass correctly through the first scanner as my math method works as it should here is the code:
main
package a2.internetbill;
import java.util.Scanner;

public class A2InternetBill {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    String type = "A";
    int nUsage = 0;
    String nAccountName = "Bob";
    // inititates objects
    Packages newPackageA = new Packages(type, nUsage, nAccountName, 0.0);

    Scanner in = new Scanner(System.in);

    //
    System.out.println("Please enter a package type(Must be A, B, C or D):\n\r");
    type = in.nextLine();
    newPackageA.setPackageType(type);

    System.out.println("Please Enter Your Name:\n\r ");

    newPackageA.setAccountName(in.nextLine());

    System.out.println("Please enter how much GB of Data you used: \n\r");

    newPackageA.setUsage(in.nextInt());

    String outPut;
    // do maths and prints formatted toString method
    newPackageA.moneyMath(type, nUsage, nUsage);
    outPut = newPackageA.toString();
    System.out.println(outPut);
    System.out.println(newPackageA.getAccountName() + newPackageA.getUsage() + newPackageA.getPackageType());
    // TODO code application logic here
        // instance variables

}

}
class
    /*
 * Makes internet package for specific user
 */
package a2.internetbill;

/**
 * 4 packages are:
 * PACKAGE A (IGNITE_60): 200GB usage for $49.99 per month.
 * Extra usage is $3.00 per GB.
 *
    PACKAGE B (IGNITE_30): 125GB usage for $39.99 per month.
    * Extra usage is $1.50 per GB.
    PACKAGE C (INTERNET_5): 25GB usage for $24.99 per month.
    * Extra usage is $5 per GB.

    PACKAGE D (UNLIMITED_USAGE): For $69.99 per month
    * unlimited access is provided.

 * @author sav
 */

    public class Packages {
    private String packageType;
    private int usage;
    private String accountName;
    public double runningTotal;

    //initiates a Packages object
    public Packages(String type, int nUsage, String nAccountName, double nRunningTotal){
        packageType = type;
        usage = nUsage;
        accountName = nAccountName;
        runningTotal = nRunningTotal;

    }

    // getters
    public String getPackageType(){
        return packageType;
    }

    public int getUsage(){
        return usage;
    }

    public String getAccountName(){
        return accountName;
    }

    // setters
    public void setPackageType(String type){
        type = packageType;
    }
    public void setUsage(int nUsage){
        nUsage = usage;

    }
    public void setAccountName(String nAccountName){
        nAccountName = accountName;
    }

    public void moneyMath(String type, int nUsage, double nRunningTotal){
        if (type.equals("A")){
            if (nUsage>=200){
                nRunningTotal = ((nUsage - 200) * 3) + 49.99;
                type = "Ignite_60";
                packageType = type;

            }
            else{
                nRunningTotal = 49.99;
                type = "Ignite_60";
                packageType = type;
            }
        }
        else if (type.equals("B")){
            if (nUsage>=125){
                nRunningTotal = ((nUsage - 125) * 1.5) + 39.99;
                type = "Ignite_30";
                packageType = type;
            }
            else{
                nRunningTotal = 39.99;
                type = "Ignite_30";
                packageType = type;
            }
        }
        else if (type.equals("C")){
            if (nUsage>=25){
                nRunningTotal = ((nUsage - 25) * 5) + 24.99;
                type = "Internet_5";
                packageType = type;
            }
            else{
                nRunningTotal = 24.99;
                type = "Internet_5";
                packageType = type;
            }
        }
        else if (type.equals("D")){
            nRunningTotal = 69.99;
            type = "Unlimited_Usage";
            packageType = type;
        }
        else{
            System.out.println("Something something something");
        }

    }

    //

    /**
     * Modified toString for specified outputs(formatted as assigned)
     * @return
     */
    @Override
    public String toString(){
        return ("Dear, \n\r" + accountName + " \n\r You have selected the : " + packageType + " package, and your current amount due is: $" + runningTotal);

    }
}

Please let me know how to use the scanner properly (I think that's what's causing the issue right now), thank you very much,

A: Your setters are incorrect.
public void setPackageType(String type){
    type = packageType;
}
public void setUsage(int nUsage){
    nUsage = usage;
}
public void setAccountName(String nAccountName){
    nAccountName = accountName;
}

Should be,
public void setAccountName(String nAccountName){
    accountName = nAccountName;
}
public void setPackageType(String type){
    packageType = type;
}
public void setUsage(int nUsage){
    usage = nUsage;
}


text:
Q: Android tabs icons I have 2 questions:
1. I have an activity with 3 tabs. I want an icon on each an icon. I've got 32x32 icons. When i place them on a tab and run my app with the emulator, the icons are blurred. But when I open the icons on my pc they are just fine.
2. I have the same problem with the options menu. When I place an icon on a option of the options menu and run the app with the emulator the icons are blurred. But when I open the icons on my pc they are just fine.
Does somebody have a solution?

A: you may try to increase your tab vertical size in the layout, because icons become blurry when there's not enough space and Android has to rescale them to fit.

A: There you get resized icons, you  can upload yours and will get them in the right size
http://android-ui-utils.googlecode.com/hg/asset-studio/dist/icons-tab.html#source.type=image&source.space.trim=0&source.space.pad=0.05&name=example
and her you see the desing lines
http://developer.android.com/guide/practices/ui_guidelines/icon_design_tab.html


text:
Q: The exponential integrals are the functions $E_n$ defined by $E_n(x)=\int_{1}^{\infty}(e^{xt}t^n)^{-1}dt$
In the response of the book says: Hint: Determine whether $E_n(x)$ is increasing or decreasing as a function of $n$
But I do not know how to interpret this help.
Any help or answer to this question would be greatly appreciated.

A:
Determine whether $E_n(x)$ is increasing or decreasing as a function of $n$.

It simply means that for any $x>0$ and $n\ge0$, we must have $E_{n+1}(x)\ge E_n(x)$. This is quite easy, since for any $t>1$, we have $(e^{xt}t^{n+1})^{-1}\ge(e^{xt}t^n)^{-1}$, and thus
$$\int_1^\infty(e^{xt}t^{n+1})^{-1}{\rm~d}t\ge\int_1^\infty(e^{xt}t^n)^{-1}{\rm~d}t\\\implies E_{n+1}(x)\ge E_n(x)$$

A: For every $x>0$, $(E_n(x))_{n=0}^\infty$ is a sequence.
For a fixed $x>0$, the sequence is increasing if $E_{n+1}(x)\geq E_n(x)$ for every $n\geq 0$. Same idea for decreasing
The nice thing about this specific recurrence relation is that you can see that the increasing/decreasing part independent of the choice of $x>0$, so the $x$ is not important for determining if the sequence is increasing/decreasing.


text:
Q: Resizing RadEditor's width on window.resize For some reason, I can't get my RadEditor to resize itself on window.resize. My javascript function getsCalled but nothing seems to modify the RadEditor's appearance.
In the first place, I thought it'd resize by itself but it's not...it is resizing only once its content is updated from server.
Here's my RadEditor:
 <telerik:RadEditor ID="RadEditor1" Runat="server"
                        OnClientLoad="OnRadEditorClientLoad"
                        OnClientCommandExecuting="OnClientCommandExecuting"
                        EnableResize="true" ContentAreaMode="Div"
                        AutoResizeHeight="true"
                        Height="20px"
                        Width="100%"
                        EditModes="Design"
                        Skin="Web20">
  </telerik:RadEditor>

Here's my javascript function:
window.onresize = ResizeControls;
    function ResizeControls() {
        var editor = $find("<%=RadEditor1.ClientID %>");
        editor.get_element().style.width = getDocWidth() + "px";
        editor.get_contentArea().style.width = getDocWidth() + "px";
    }

Where getDocWidth() is returning the correctly modified width. (And yes, the "px" gotta be there). If I check editor's width, it's been modified correctly...I jst need to refresh or repaint the control.
So, on first load, my RadEditor is taking 100% of window's width. But after window.resize from 1000px to 800px, the RadEditor's width is still 1000px.

Explicit solution: Remove Width=100% and adjust width in the OnClientLoad event:
 <telerik:RadEditor ID="RadEditor1" Runat="server"
                    OnClientLoad="OnRadEditorClientLoad"
                    OnClientCommandExecuting="OnClientCommandExecuting"
                    EnableResize="true" ContentAreaMode="Div"
                    AutoResizeHeight="true"
                    Height="20px"
                    EditModes="Design"
                    Skin="Web20">
  </telerik:RadEditor>

    function OnRadEditorClientLoad(editor, args) {
        editor.get_element().style.width = getDocWidth()= + "px";
    }

    window.onresize = AsjustRadEditorsWidth;
    function AsjustRadEditorsWidth() {
        var editor = $find("<%=EnonceContainer.ClientID %>");
        editor.get_element().style.width = getDocWidth() + "px";
    }

A: RadControls for ASP.NET AJAX Documentation RadEditor setSize
In addition to setSize method call, try to reset min-width and min-height css properties of editor's div element:
$telerik.$($find("<%=RadEditor1.ClientID %>")).css({"min-width": "", "min-height": ""});


text:
Q: Multithreaded program becomes nonresponsive on _multiple_ CPUs, but fine on a single CPU (when updating a ListView) Update: I've reproduced the problem! Scroll lower to see the code.
Quick Notes

*

*My Core i5 CPU has 2 cores, hyperthreading.

*If I call SetProcessAffinityMask(GetCurrentProcess(), 1), everything is fine, even though the program is still multithreaded.

*If I don't do that, and the program is running on Windows XP (it's fine on Windows 7 x64!), my GUI starts locking up for several seconds while I'm scrolling the list view and the icons are loading.
The Problem
Basically, when I run the program posted below (a reduced version of my original code) on Windows XP (Windows 7 is fine), unless I force the same logical CPU for all my threads, the program UI starts lagging behind by half a second or so.
(Note: Lots of edits to this post here, as I investigated the problem further.)
Note that the number of threads is the same -- only the affinity mask is different.
I've tried this out using two different methods of message-passing: the built-in GetMessage as well as my own BackgroundWorker.
The result? BackgroundWorker benefits from affinity for 1 logical CPU (virtually no lag), whereas GetMessage is completely hurt by this, (lag is now many seconds long).
I can't figure out why that would be happening -- shouldn't multiple CPUs work better than a single CPU?!
Why would there be such a lag, when the number of threads is the same?

More stats:
GetLogicalProcessorInformation returns:
0x0: {ProcessorMask=0x0000000000000003 Relationship=RelationProcessorCore ...}
0x1: {ProcessorMask=0x0000000000000003 Relationship=RelationCache ...}
0x2: {ProcessorMask=0x0000000000000003 Relationship=RelationCache ...}
0x3: {ProcessorMask=0x0000000000000003 Relationship=RelationCache ...}
0x4: {ProcessorMask=0x000000000000000f Relationship=RelationProcessorPackage ...}
0x5: {ProcessorMask=0x000000000000000c Relationship=RelationProcessorCore ...}
0x6: {ProcessorMask=0x000000000000000c Relationship=RelationCache ...}
0x7: {ProcessorMask=0x000000000000000c Relationship=RelationCache ...}
0x8: {ProcessorMask=0x000000000000000c Relationship=RelationCache ...}
0x9: {ProcessorMask=0x000000000000000f Relationship=RelationCache ...}
0xa: {ProcessorMask=0x000000000000000f Relationship=RelationNumaNode ...}

The Code
The code below should shows this problem on Windows XP SP3.
(At least, it does on my computer!)
Compare these two:

*

*Run the program normally, then scroll. You should see lag.

*Run the program with the affinity command-line argument, then scroll. It should be almost completely smooth.
Why would this happen?
#define _WIN32_WINNT 0x502

#include <tchar.h>
#include <Windows.h>
#include <CommCtrl.h>

#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "user32.lib")

LONGLONG startTick = 0;

LONGLONG QPC()
{ LARGE_INTEGER v; QueryPerformanceCounter(&v); return v.QuadPart; }

LONGLONG QPF()
{ LARGE_INTEGER v; QueryPerformanceFrequency(&v); return v.QuadPart; }

bool logging = false;
bool const useWindowMessaging = true;   // GetMessage() or BackgroundWorker?
bool const autoScroll = false;   // for testing

class BackgroundWorker
{
    struct Thunk
    {
        virtual void operator()() = 0;
        virtual ~Thunk() { }
    };
    class CSLock
    {
        CRITICAL_SECTION& cs;
    public:
        CSLock(CRITICAL_SECTION& criticalSection)
            : cs(criticalSection)
        { EnterCriticalSection(&this->cs); }
        ~CSLock() { LeaveCriticalSection(&this->cs); }
    };
    template<typename T>
    class ScopedPtr
    {
        T *p;
        ScopedPtr(ScopedPtr const &) { }
        ScopedPtr &operator =(ScopedPtr const &) { }
    public:
        ScopedPtr() : p(NULL) { }
        explicit ScopedPtr(T *p) : p(p) { }
        ~ScopedPtr() { delete p; }
        T *operator ->() { return p; }
        T &operator *() { return *p; }
        ScopedPtr &operator =(T *p)
        {
            if (this->p != NULL) { __debugbreak(); }
            this->p = p;
            return *this;
        }
        operator T *const &() { return this->p; }
    };

    Thunk **const todo;
    size_t nToDo;
    CRITICAL_SECTION criticalSection;
    DWORD tid;
    HANDLE hThread, hSemaphore;
    volatile bool stop;
    static size_t const MAX_TASKS = 1 << 18;  // big enough for testing

    static DWORD CALLBACK entry(void *arg)
    { return ((BackgroundWorker *)arg)->process(); }

public:
    BackgroundWorker()
        : nToDo(0), todo(new Thunk *[MAX_TASKS]), stop(false), tid(0),
        hSemaphore(CreateSemaphore(NULL, 0, 1 << 30, NULL)),
        hThread(CreateThread(NULL, 0, entry, this, CREATE_SUSPENDED, &tid))
    {
        InitializeCriticalSection(&this->criticalSection);
        ResumeThread(this->hThread);
    }

    ~BackgroundWorker()
    {
        // Clear all the tasks
        this->stop = true;
        this->clear();
        LONG prev;
        if (!ReleaseSemaphore(this->hSemaphore, 1, &prev) ||
            WaitForSingleObject(this->hThread, INFINITE) != WAIT_OBJECT_0)
        { __debugbreak(); }
        CloseHandle(this->hSemaphore);
        CloseHandle(this->hThread);
        DeleteCriticalSection(&this->criticalSection);
        delete [] this->todo;
    }

    void clear()
    {
        CSLock lock(this->criticalSection);
        while (this->nToDo > 0)
        {
            delete this->todo[--this->nToDo];
        }
    }

    unsigned int process()
    {
        DWORD result;
        while ((result = WaitForSingleObject(this->hSemaphore, INFINITE))
            == WAIT_OBJECT_0)
        {
            if (this->stop) { result = ERROR_CANCELLED; break; }
            ScopedPtr<Thunk> next;
            {
                CSLock lock(this->criticalSection);
                if (this->nToDo > 0)
                {
                    next = this->todo[--this->nToDo];
                    this->todo[this->nToDo] = NULL;  // for debugging
                }
            }
            if (next) { (*next)(); }
        }
        return result;
    }

    template<typename Func>
    void add(Func const &func)
    {
        CSLock lock(this->criticalSection);
        struct FThunk : public virtual Thunk
        {
            Func func;
            FThunk(Func const &func) : func(func) { }
            void operator()() { this->func(); }
        };
        DWORD exitCode;
        if (GetExitCodeThread(this->hThread, &exitCode) &&
            exitCode == STILL_ACTIVE)
        {
            if (this->nToDo >= MAX_TASKS) { __debugbreak(); /*too many*/ }
            if (this->todo[this->nToDo] != NULL) { __debugbreak(); }
            this->todo[this->nToDo++] = new FThunk(func);
            LONG prev;
            if (!ReleaseSemaphore(this->hSemaphore, 1, &prev))
            { __debugbreak(); }
        }
        else { __debugbreak(); }
    }
};

LRESULT CALLBACK MyWindowProc(
    HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    enum { IDC_LISTVIEW = 101 };
    switch (uMsg)
    {
        case WM_CREATE:
        {
            RECT rc; GetClientRect(hWnd, &rc);

            HWND const hWndListView = CreateWindowEx(
                WS_EX_CLIENTEDGE, WC_LISTVIEW, NULL,
                WS_CHILDWINDOW | WS_VISIBLE | LVS_REPORT |
                LVS_SHOWSELALWAYS | LVS_SINGLESEL | WS_TABSTOP,
                rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top,
                hWnd, (HMENU)IDC_LISTVIEW, NULL, NULL);

            int const cx = GetSystemMetrics(SM_CXSMICON),
                cy = GetSystemMetrics(SM_CYSMICON);

            HIMAGELIST const hImgList =
                ImageList_Create(
                    GetSystemMetrics(SM_CXSMICON),
                    GetSystemMetrics(SM_CYSMICON),
                    ILC_COLOR32, 1024, 1024);

            ImageList_AddIcon(hImgList, (HICON)LoadImage(
                NULL, IDI_INFORMATION, IMAGE_ICON, cx, cy, LR_SHARED));

            LVCOLUMN col = { LVCF_TEXT | LVCF_WIDTH, 0, 500, TEXT("Name") };
            ListView_InsertColumn(hWndListView, 0, &col);
            ListView_SetExtendedListViewStyle(hWndListView,
                LVS_EX_DOUBLEBUFFER | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
            ListView_SetImageList(hWndListView, hImgList, LVSIL_SMALL);

            for (int i = 0; i < (1 << 11); i++)
            {
                TCHAR text[128]; _stprintf(text, _T("Item %d"), i);
                LVITEM item =
                {
                    LVIF_IMAGE | LVIF_TEXT, i, 0, 0, 0,
                    text, 0, I_IMAGECALLBACK
                };
                ListView_InsertItem(hWndListView, &item);
            }

            if (autoScroll)
            {
                SetTimer(hWnd, 0, 1, NULL);
            }

            break;
        }
        case WM_TIMER:
        {
            HWND const hWndListView = GetDlgItem(hWnd, IDC_LISTVIEW);
            RECT rc; GetClientRect(hWndListView, &rc);
            if (!ListView_Scroll(hWndListView, 0, rc.bottom - rc.top))
            {
                KillTimer(hWnd, 0);
            }
            break;
        }
        case WM_NULL:
        {
            HWND const hWndListView = GetDlgItem(hWnd, IDC_LISTVIEW);
            int const iItem = (int)lParam;
            if (logging)
            {
                _tprintf(_T("@%I64lld ms:")
                    _T(" Received: #%d\n"),
                    (QPC() - startTick) * 1000 / QPF(), iItem);
            }
            int const iImage = 0;
            LVITEM const item = {LVIF_IMAGE, iItem, 0, 0, 0, NULL, 0, iImage};
            ListView_SetItem(hWndListView, &item);
            ListView_Update(hWndListView, iItem);
            break;
        }
        case WM_NOTIFY:
        {
            LPNMHDR const pNMHDR = (LPNMHDR)lParam;
            switch (pNMHDR->code)
            {
            case LVN_GETDISPINFO:
                {
                    NMLVDISPINFO *const pInfo = (NMLVDISPINFO *)lParam;
                    struct Callback
                    {
                        HWND hWnd;
                        int iItem;
                        void operator()()
                        {
                            if (logging)
                            {
                                _tprintf(_T("@%I64lld ms: Sent:     #%d\n"),
                                    (QPC() - startTick) * 1000 / QPF(),
                                    iItem);
                            }
                            PostMessage(hWnd, WM_NULL, 0, iItem);
                        }
                    };
                    if (pInfo->item.iImage == I_IMAGECALLBACK)
                    {
                        if (useWindowMessaging)
                        {
                            DWORD const tid =
                                (DWORD)GetWindowLongPtr(hWnd, GWLP_USERDATA);
                            PostThreadMessage(
                                tid, WM_NULL, 0, pInfo->item.iItem);
                        }
                        else
                        {
                            Callback callback = { hWnd, pInfo->item.iItem };
                            if (logging)
                            {
                                _tprintf(_T("@%I64lld ms: Queued:   #%d\n"),
                                    (QPC() - startTick) * 1000 / QPF(),
                                    pInfo->item.iItem);
                            }
                            ((BackgroundWorker *)
                             GetWindowLongPtr(hWnd, GWLP_USERDATA))
                                ->add(callback);
                        }
                    }
                    break;
                }
            }
            break;
        }

        case WM_CLOSE:
        {
            PostQuitMessage(0);
            break;
        }
    }
    return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

DWORD WINAPI BackgroundWorkerThread(LPVOID lpParameter)
{
    HWND const hWnd = (HWND)lpParameter;
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0) > 0 && msg.message != WM_QUIT)
    {
        if (msg.message == WM_NULL)
        {
            PostMessage(hWnd, msg.message, msg.wParam, msg.lParam);
        }
    }
    return 0;
}

int _tmain(int argc, LPTSTR argv[])
{
    startTick = QPC();
    bool const affinity = argc >= 2 && _tcsicmp(argv[1], _T("affinity")) == 0;
    if (affinity)
    { SetProcessAffinityMask(GetCurrentProcess(), 1 << 0); }

    bool const log = logging;  // disable temporarily
    logging = false;

    WNDCLASS wndClass =
    {
        0, &MyWindowProc, 0, 0, NULL, NULL, LoadCursor(NULL, IDC_ARROW),
        GetSysColorBrush(COLOR_3DFACE), NULL, TEXT("MyClass")
    };
    HWND const hWnd = CreateWindow(
        MAKEINTATOM(RegisterClass(&wndClass)),
        affinity ? TEXT("Window (1 CPU)") : TEXT("Window (All CPUs)"),
        WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT,
        CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);

    BackgroundWorker iconLoader;
    DWORD tid = 0;
    if (useWindowMessaging)
    {
        CreateThread(NULL, 0, &BackgroundWorkerThread, (LPVOID)hWnd, 0, &tid);
        SetWindowLongPtr(hWnd, GWLP_USERDATA, tid);
    }
    else { SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)&iconLoader); }

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0) > 0)
    {
        if (!IsDialogMessage(hWnd, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        if (msg.message == WM_TIMER ||
            !PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
        { logging = log; }
    }

    PostThreadMessage(tid, WM_QUIT, 0, 0);
    return 0;
}

A: Based on the inter-thread timings you posted at http://ideone.com/fa2fM, it looks like there is a fairness issue at play here.  Based solely on this assumption, here is my reasoning as to the apparent cause of the perceived lag and a potential solution to the problem.
It looks like there is a large number of LVN_GETDISPINFO messages being generated and processed on one thread by the window proc, and while the background worker thread is able to keep up and post messages back to the window at the same rate, the WM_NULL messages it posts are so far back in the queue that it takes time before they get handled.
When you set the processor affinity mask, you introduce more fairness into the system because the same processor must service both threads, which will limit the rate at which LVN_GETDISPINFO messages are generated relative to the non-affinity case.  This means that the window proc message queue is likely not as deep when you post your WM_NULL messages, which in turn means that they will be processed 'sooner'.
It seems that you need to somehow bypass the queueing effect.  Using SendMessage, SendMessageCallback or SendNotifyMessage instead of PostMessage may be ways to do this.  In the SendMessage case, your worker thread will block until the window proc thread is finished its current message and processes the sent WM_NULL message, but you will be able to inject your WM_NULL messages more evenly into the message processing flow.  See this page for an explanation of queued vs. non-queued message handling.
If you choose to use SendMessage, but you don't want to limit the rate at which you can obtain icons due to the blocking nature of SendMessage, then you can use a third thread.  Your I/O thread would post messages to the third thread, while the third thread uses SendMessage to inject icon updates into the UI thread.  In this fashion, you have control of the queue of satisfied icon requests, instead of interleaving them into the window proc message queue.
As for the difference in behaviour between Win7 and WinXP, there may be a number of reasons why you don't appear to see this effect on Win7.  It could be that the list view common control is implemented differently and limits the rate at which LVN_GETDISPINFO messages are generated.  Or perhaps the thread scheduling mechanism in Win7 switches thread contexts more frequently or more fairly.
EDIT:
Based on your latest change, try the following:
...

                struct Callback
                {
                    HWND hWnd;
                    int iItem;
                    void operator()()
                    {
                        if (logging)
                        {
                            _tprintf(_T("@%I64lld ms: Sent:     #%d\n"),
                                (QPC() - startTick) * 1000 / QPF(),
                                iItem);
                        }
                        SendNotifyMessage(hWnd, WM_NULL, 0, iItem); // <----
                    }
                };

...

DWORD WINAPI BackgroundWorkerThread(LPVOID lpParameter)
{
    HWND const hWnd = (HWND)lpParameter;
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0) > 0 && msg.message != WM_QUIT)
    {
        if (msg.message == WM_NULL)
        {
            SendNotifyMessage(hWnd, msg.message, msg.wParam, msg.lParam); // <----
        }
    }
    return 0;
}

EDIT 2:
After establishing that the LVN_GETDISPINFO message are being placed in the queue using SendMessage instead of PostMessage, we can't use SendMessage ourselves to bypass them.
Still proceeding on the assumption that there is a glut of messages being processed by the wndproc before the icon results are being sent back from the worker thread, we need another way to get those updates handled as soon as they are ready.
Here's the idea:

*

*Worker thread places results in a synchronized queue-like data structure, and then posts (using PostMessage) a WM_NULL message to the wndproc (to ensure that the wndproc gets executed sometime in the future).

*At the top of the wndproc (before the case statements), the UI thread checks the synchronized queue-like data structure to see if there are any results, and if so, removes one or more results from the queue-like data structure and processes them.

A: The issue has less to do with thread affinity and more to do with telling the listview that it needs to update the list item every time you update it. Because you do not add the LVIF_DI_SETITEM flag to pInfo->item.mask in your LVN_GETDISPINFO handler, and because you call ListView_Update manually, when you call ListView_Update, the list view invalidates any item that still has its iImage set to I_IMAGECALLBACK.
You can fix this in one of two ways (or a combination of both):

*

*Remove ListView_Update from your WM_NULL handler. The list view will automatically redraw the items you set the image for in your WM_NULL handler when you set them, and it will not attempt to redraw items you haven't set the image for more than once.

*Set LVIF_DI_SETITEM flag in pInfo->item.mask in your LVN_GETDISPINFO handler and set pInfo->item.iImage to a value that is not I_IMAGECALLBACK.
I repro'd similar awful behavior doing a full page scroll on Vista. Doing either of the above fixed the issue while still updating the icons asynchronously.

A: *

*Its plausible to suggest that this is related to XPs hyper threading/logical core scheduling and I will second IvoTops suggestion to try this with hyper-threading disabled. Please try this and let us know.
Why? Because:
a) Logical cores offer bad parallelism for CPU bound tasks. Running multiple CPU bound threads on two logical HT cores on the same physical core is detrimental to performance. See for example, this intel paper - it explains how enabling HT might cause typical server threads to incur an increase in latency or processing time for each request (while improving net throughput.)
b) Windows 7 does indeed have some HT/SMT (symmetrical multi threading) scheduling improvements. Mark Russinovich's slides here mention this briefly. Although they claim that XP scheduler is SMT aware, the fact that Windows 7 explicitly fixes something around this, implies there could be something lacking in XP. So I'm guessing that the OS isn't setting the thread affinity to the second core appropriately. (perhaps because the second core might not be idle at the instant of scheduling your second thread, to speculate wildly).

*You wrote "I just tried setting the CPU affinity of the process (or even the individual threads) to all potential combinations I could think of, on the same and on different logical CPUs".
Can we try to verify that the execution is actually on the second core, once you set this?
You can visually check this in task manager or perfmon/perf counters
Maybe post the code where you set the affinity of the threads (I note that you are not checking the return value on SetProcessorAffinity, do check that as well.)
If Windows perf counters dont help, Intel's VTune Performance Analyzer is helpful for exactly this kind of stuff.
I think you can force the thread affinity manually using task manager.
One more thing: Your core i5 is either Nehalem or SandyBridge micro-architecture. Nehalem and later HT implementation is significantly different from the prior generation architectures (Core,etc). In fact Microsoft recommended disabling HT for running Biztalk server on pre-Nehalem systems.  So perhaps Windows XP does not handle the new HT architecture well.

A: This might be a hyperthreading bug. To check if that's what causing it run your faulty program with Hyperthreading turned off (in the bios you can usually switch it off). I have run into two issues in the last five years that only surfaced when hyperthreading was enabled.


text:
Q: using a sheet in an excel user defined function The VBA I'm trying to write is fairly simple but Ive never written VBA and coming from the visual studio & C# world, this truly is hell!!
So I'll really be grateful for any help/pointers/hints here

So I have two important sheets. The Range sheet has 2 values per date. It needs a result, The Calc sheet takes two values and gets me a result.
I want to Put the Current, and OneYear values for each date into the Calc sheet and get the result into the result column.
So I tried defining a UDF but I learned later I cannot modify sheet contents in a UDF.
I tried recording a macro and then hoped to go from there, but I got something like this:
Range("A2").Select
Sheets("24Feb05-24FEB10").Select
Range("K9").Select
ActiveCell.FormulaR1C1 = "=Calc!R[-8]C[-10]"
Range("K9").Select

Im assuming R1C1 is Row and Column but why on earth does it say -8 and -10!??
Can someone get me in the right direction?
Note: There are about 2000+ dates.
Hope my question is clear!

Update
I'll clear up a few more things:
Im grossly simplifying the Calc sheet, in reality, it needs 5 values (there are columns upto SixYears) And then that sheet calls about 4 other sheets and does some finance calculations that some non-tech-savvy guy wrote.
I tried to get the finance guy to express to me in algebra what he's doing, so I could just write up a C# function.
I also tried writing a UDF, but like I said it needs to put in the values and get the result, which means the UDF will modify the sheet.
Function Func1(txt As Variant) As String
//Returns the nth element from a delimited text string
    Dim txt As String
    txt = text
   Sheet4.Cells(1, 1) = txt
   Func1 = Sheet4.Cells(2, 1)//get the result value'
End Function

Basically Im having a head ache learning/understand VBA syntax and the API.
Im looking for maybe a small example of how I would take values from one sheet into another and then get the some other values back? Maybe in a loop!?

A: You might be making this more complicated than you need to. As a programmer, I'm sure you appreciate that when learning a new system, a little time with the help, Google, "Dummies" books, etc. is time well spent. Excel emphasizes a very different programming style than, say, C#.
So, here are some options, starting with the simplest and most Excel-idiomatic:
1) Use a formula in your result column. If the calculation you want to do is simple enough, this is the way to go. As a trivial example, say your calculation is just adding the two numbers. You'd put the formula
=B2+C2

into cell E2, and then drag it down the E column. Excel will know what to do and make forumlas for E3=B3+C3 and so on.
You can do quite a lot with just formulas. Excel has many built-in worksheet functions, and you can find tons of material on the web and in the bookstore.
2) Write a UDF in VBA and call it from the result column. A UDF is a function that doesn't modify anything else in the worksheet. It just calculates a result based on its input parameters. You would write a UDF when you have something too complex to do in a formula, or when you want to use the formula in multiple places. (Note that dragging a forumla across a Range is idiomatic Excel and counts as "one place" for DRY purposes).
So, to write a UDF (let's use the addition example, but you'd write more complex logic), you'd put a function like this into a VBA code module:
Public Function myUDF(current, oneYear)
    myUDF = current + oneYear
End Function

You'd then put the formula
=myUDF(B2, C2)

into cell E2 and drag that down the E column.
Note that I've neglected stuff like error handling in this example. This is one reason why formulas are more "Excel" than UDFs. Now you have to start writing code that departs from Excel's declarative functional style, and it's a different mental model.
EDIT:
2.5) Use an Excel Data Table - I'm embarrased that I forgot this before, but if you have exactly one or two cells that are your independent parameters, and exactly one cell that is your result, then Excel has a built-in "what-if" analysis tool that you can use. The name "data table" is regrettable since both of those words are so heavily overloaded, but that's what it's called. You tell Excel what your input(s) and output are, and it will do what you want. See:
http://office.microsoft.com/en-us/excel-help/calculate-multiple-results-by-using-a-data-table-HP010072656.aspx
Here is the little intro from that link:

A data table is a range of cells that
  shows how changing one or two
  variables in your formulas (formula: A
  sequence of values, cell references,
  names, functions, or operators in a
  cell that together produce a new
  value. A formula always begins with an
  equal sign (=).) will affect the
  results of those formulas. Data tables
  provide a shortcut for calculating
  multiple results in one operation and
  a way to view and compare the results
  of all the different variations
  together on your worksheet.

3) Write a macro that uses your calc sheet like it was a function. You might do this if you've got really complex logic on that sheet, and it's too hard to convert to VBA because it changes all the time or because it's being developed by an Excel user who doesn't know VBA and isn't familiar with imperative programming. I'm not going to supply code, but the pseudocode might look like this:
Public Sub doCalc()
    'for each cell in the result column
        'copy the corresponding current and oneYear cells to the calc sheet
        'Excel will recalc the calc sheet
        'copy the result cell on the calc sheet back to the Range sheet in the right place
    'end
End Sub

This is now departing pretty far from the "Excel way", since you have to set up your data yourself, and then run the macro. If you go back and change some of the "inputs", you need to re-run the macro. (This can be automated to some extent, using Worksheet events.)
Lot's of programmers who are new to Excel jump right to this step, relegating Excel to a giant grid control and neglecting the reason it exists in the first place - automatic recalculation.
EDIT IN RESPONSE TO ADDITIONAL INFO IN QUESTION:
O.K., it looks like case (3) is appropriate because you have a complex sheet not easily manually translated into VBA or C# code. Here is some (oversimplified, hardcoded, lacking EH, etc.) code to give you more of an idea of how to do this in VBA:
First, there is the VBA macro that pretends it's a UDF. Note that it is a Sub, not a function, and you don't call it from a formula. You call subroutines in response to the user doing something like choosing a menu option or pressing a command button:
Public Sub fakeFunct(input1, input2, outputRng As Range)
    CalcSheet.[b1] = input1
    CalcSheet.[b2] = input2

    'Excel recalcs what's in cell B3 if you have it set to automatic recalcualation

    outputRng = CalcSheet.[b3]
End Sub

In this example, 'CalcSheet' is the "code name" of your worksheet module. (For more about this, see Chip Pearson's excellent website: http://www.cpearson.com/excel/codemods.htm)
You'd actually call the above macro from another one that loops through your "inputs":
Public Sub loopFakeFunct()
    Dim i As Long
    For i = 2 To 2000
        Call fakeFunct(RangeSheet.Cells(i, 2), RangeSheet.Cells(i, 3), RangeSheet.Cells(i, 5))
    Next i
End Sub

This is the thing you call in response to user action, or from the Worksheet_Change event, etc. It will be slow and clunky, and I'm leaving a lot of practical VBA stuff out, but it should be enough to get you started. (I used 'RangeSheet' instead of 'Range' as a sheet code name to avoid conflicts with the Range class and the Application.Range method defined by Excel.)
4) Use some third-party tool that converts your worksheet into a UDF that you can then call as in (2). There are commerical tools out there that will take your sheet, let you specifiy which cells are inputs and outputs, and then generate C++ code or whatever that can be compiled into an XLL add-in.
5) Wait for Microsoft to do this:
http://research.microsoft.com/en-us/um/people/simonpj/papers/excel/excel.htm
6) Use Resolver One:
http://www.resolversystems.com/products/resolver-one/
It has a feature that allows you to use a whole workbook as a function in another one, or I think in any Python code.

A: You recorded your macro in "relative" mode. R[-8]C[-10] means: the cell 8 rows above and 10 columns to the left of current cell.

A: Its usually best in cases like this to work within the Excel paradigm rather than convert to the C# way:
Not sure why you need a UDF rather than the Excel formulae which your Finance guy has coded: why can't you/finance guy just code some fomulae to feed the inputs to the finance guy sheets, then write some more formulae to feed the results back?
If you really need to do this with VBA then J Tolle has given you the basic architecture for a repetitive loop but I would recommend looking at doing it with formulae first.


text:
Q: C++ & Boost: I'm trying to find an example TCP program with a server that accepts connections from multiple clients A chat program would be a good enough example.
Just need a server that can accept multiple connections from the clients, and the server needs to be able to send messages to individual clients.
I plan to turn this into a distributed computing program to work with multiple Neural Networks.

A: Asio is the Boost library that handles networking. There's a chat server example listed here.

A: I cannot give you an example progam. But to write a server things that you have to do:
1. server will listen at a port for connection
2. thread pool which will accept the connection and serve request
3. write the server code in thread safe manner
You have to use socket programming A good link for that http://beej.us/guide/bgnet/
you can use win32 api in windows and  posix for linux


text:
Q: How do I design a C# visual motif that looks like visual studio error list How do I design a C# visual motif that looks like visual studio error list?
--I have a program that examines the user provided inputs, and I would like to send errors back to the user in a format similar to the "error list" display in Visual Studio 2005.

A: A ListView with the view propterty set to  "Details" possibly.


text:
Q: dynamic url(separated by slash) paramters get to array? (eg : /category,cat1,cat2/types,type1,type2) have a good day guys!, im currently working on eCommerce like product filter,controller get request from front-end main category and parameters separated by slash('/'). URL parameters send like this:
example.com/skin-care/categories,facial-cleansers-toners/collection,classic/skin-types,normal,soft

these URL open when user select attributes from filter. so after example.com/skin-care/ is totally dynamic.
/skin-care  - main category
after first slash separate, all parameters dynamic attributes.
eg : /{attribute},value1,value1,..
so above examples have 1 main category slug and, 3 attributes (categories,collection,skin-types) and values of that attributes
i just need get these attributes to Associative array. just like this:
$attributes = ['categories' => ['facial-cleansers-toners'],
        'collection' => ['classic'],
        'skin-types' => ['normal','soft']
        ];

thank you

A: your url is:
$static_url = "http://example.com/skin-care/categories,facial-cleansers-toners/collection,classic/skin-types,normal,soft";

first of all, we have to parse your URL to get our needed parameters :
$url_components = parse_url($static_url);

this variable outputs 3 items scheme, host and path. we need just path from here, so:
$url_path = $url_components['path'];

in the next level, we need to remove the first / character from the string and explode the string by / character:
$url_path_params = ltrim($url_path, $url_path[0]);
$url_attributes = explode('/', $url_path_params);

in this section we have the main category that maybe you need:
$main_category = $url_attributes[0]; // skin-care

we don't need the first item ($main_category = 'skin-care') here so:
array_shift($url_attributes);

in the last step we got the $url_attributes that we need to fill in the attributes array with foreach loop and explode the string by , just like this:
$attributes = [];
foreach ($url_attributes as $attribute_key => $attribute_value) {
    $each_attribute = explode(',', $attribute_value);
    $cat = array_shift($each_attribute);

    $attributes[$cat] = $each_attribute;
}

if you get output from $attributes you got your needed data. in var_dump output this returns:

you can access to skin_types by: $attributes["skin-types"].
Check the whole source in PHP Sandbox


text:
Q: Jquery Common function to hide elements by attribute I have many checkboxes and related textboxes in the page. The textboxes are hidden by default and show only if its related checkbox is checked. How should I write a common function for this, instead of a function for every checkbox.
http://jsfiddle.net/6SCMc/
something..like..:
$("input[type=checkbox]").click( function() {
    var x = $(this).attr("name");
$("[id=x]").toggle(this.checked);
});

The 'name' of the checkbox will be the id of its textbox.

A: You need to:
1) Include jQuery in your fiddle
2) Use change() event instead of click()
3) Concatenate your x variable properly using +
$("input[type=checkbox]").change( function() {
    var x = $(this).attr("name");
    $("#" + x).toggle(this.checked);
});

Updated Fiddle

A: You dont need a attribute selector in this context, since you are targeting an id, just use the Id selector like below,
Try,
$("#" + $(this).attr("name")).toggle(this.checked);

Full code,
$("input[type=checkbox]").change( function() {
   $("#" + $(this).attr("name")).toggle(this.checked);
});

A: Include jQuery in your fiddle and also :
$("input[type=checkbox]").click( function() {
    var x = $(this).attr("name");
    $("[id="+x+"]").toggle(this.checked);
});

A: Since your textboxes immediately follow the checkboxes, you can do something like:
$('input[type=checkbox]').click(function() {
    $(this).next().css('display', this.checked ? 'block': 'none');
});

A: If your question is, how do you accomplish this show/hide functionality without binding a function call to each checkbox? Then solution is, to bind a function to a div that wraps the table, or to the table itself. Then when onClick on the div fires, traverse down the child dom elements and if a checkbox is checked, show or hide the text as necessary. So something like the following:
$("wrapper_div_id").click(function() {
   var checkboxes = $(this).find(":checkbox")
   for (var i = 0; i < checkboxes.length; i++) {
      // insert code here to show/hide. Sorry, I got lazy to finish writing the rest of this
      // but you get the idea.
   }
})

A: check this one
http://jsfiddle.net/6SCMc/4/
$('input[type=checkbox]').click(function(){
                if( $(this).is(":checked") ){

                    $(this).next().show()
                }else{

                }
});


text:
Q: Get list of supported opcodes Is there a way to get a list of supported opcodes for a given architecture? Such as a listing in /proc similar to /proc/cpuinfo.

A: If you are referring to assembly instructions the two general approaches are:
Check desired functionality against flags output from cpuinfo, example output:

flags     : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov
  pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx
  pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl
  xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor
  ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2
  x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand
  lahf_lm abm ida arat epb xsaveopt pln pts dtherm tpr_shadow vnmi
  flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms
  invpcid

The second approach is to attempt to execute the assembly instruction and see if something bad happens.
As already stated the actual opcodes are not possible to see as the assembly instructions (on intel at least) are translated into op-codes which are executed by the processor.


text:
Q: Never-ending warnings about partial argument match I am constantly getting warnings about partial argument matches at times when it doesn't seem appropriate.  For instance, the below code when there are NO arguments:
require(tidyverse)
#> Loading required package: tidyverse
x <- structure(list(unitid = 100654, year = 2006, state_of_residence_when_student_was_first_admitted = "Alabama",
                    state_of_residence_original_line_number_on_survey_form = "Alabama",
                    first_time_degree_certificate_seeking_undergraduate_students = 651,
                    first_time_degree_certificate_seeking_undergraduate_students_who_graduated_from_high_school_in_the_past_12_months = 602), class = c("tbl_df",
                                                                                "tbl", "data.frame"), row.names = c(NA, -1L))

x
#> # A tibble: 1 x 6
#>   unitid  year state_of_reside… state_of_reside… first_time_degr…
#>    <dbl> <dbl> <chr>            <chr>                       <dbl>
#> 1 100654  2006 Alabama          Alabama                       651
#> # ... with 1 more variable:
#> #   first_time_degree_certificate_seeking_undergraduate_students_who_graduated_from_high_school_in_the_past_12_months <dbl>

Created on 2018-11-15 by the reprex package (v0.2.1)
The warning that I get is:
Warning messages:
1: In seq.default(along = x) :
partial argument match of 'along' to 'along.with'
2: In seq.default(along = x) :
partial argument match of 'along' to 'along.with'

And I get this all the time for various different code.  Does this happen to others? Is it a known issue with tidyverse (my searches yielded nothing). Or have I screwed something up in my settings that is causing this?

A: Jenny Bryan solved this for me.  It is a bug in R 3.5.1 which has been fixed, but the version with that fix has not been released yet.
See bug report here:
https://bugs.r-project.org/bugzilla/show_bug.cgi?id=17449

A: These options control the partial matching warnings:

*

*warnPartialMatchArgs: (logical) If TRUE, warns if partial matching is used in argument matching.

*warnPartialMatchAttr: (logical) If TRUE, warns if partial matching is used in extracting attributes via attr.

*warnPartialMatchDollar: (logical) If TRUE, warns if partial matching is used for extraction by $.

check if they're set and where they're set from and either disable it wholly or around the parts you just want to be less noisy.
Also ref: http://kevinushey.github.io/blog/2015/02/02/rprofile-essentials/


text:
Q: How customize Angular/Asp.NetCore/IdentityServer Login Template of visual studio? I created a .net core Webapplication with Angular template in Visual Studio 2019.
To modify the default Login UI, I used the Scaffold Identity in ASP.NET Core projects:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-3.1&tabs=visual-studio
I generated the Login Page with the following method:
 public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");

        if (ModelState.IsValid)
        {
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, set lockoutOnFailure: true
            var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                _logger.LogInformation("User logged in.");
                return LocalRedirect(returnUrl);
            }
            if (result.RequiresTwoFactor)
            {
                return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning("User account locked out.");
                return RedirectToPage("./Lockout");
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return Page();
            }
        }

        // If we got this far, something failed, redisplay form
        return Page();
    }

I changed the Login UI successfully.
By Login the _signInManager.PasswordSignInAsync returned True.
But the redirect functionality doesn´t work.
The ReturnUrl = ""
How can I configure the redirect URL = http://localhost:4200 = Angular client url (as origin) ?
Note: I start Angular Project and debug it with visual studio code and the API (Asp.net core) run seperated in Visual Studio (Not like the Angular template in VS).
Angular side configuration:

let applicationPaths: ApplicationPathsType = {
  DefaultLoginRedirectPath: location.origin + '/',
  ApiAuthorizationClientConfigurationUrl: `https://localhost:44326/_configuration/${ApplicationName}`,
  Login: `authentication/${LoginActions.Login}`,
  LoginFailed: `authentication/${LoginActions.LoginFailed}`,
  LoginCallback: `authentication/${LoginActions.LoginCallback}`,
  Register: `authentication/${LoginActions.Register}`,
  Profile: `authentication/${LoginActions.Profile}`,
  LogOut: `authentication/${LogoutActions.Logout}`,
  LoggedOut: `authentication/${LogoutActions.LoggedOut}`,
  LogOutCallback: `authentication/${LogoutActions.LogoutCallback}`,
  LoginPathComponents: [],
  LoginFailedPathComponents: [],
  LoginCallbackPathComponents: [],
  RegisterPathComponents: [],
  ProfilePathComponents: [],
  LogOutPathComponents: [],
  LoggedOutPathComponents: [],
  LogOutCallbackPathComponents: [],
  IdentityRegisterPath: '/Identity/Account/Register',
  IdentityManagePath: '/Identity/Account/Manage'
};

Asp.Net core Startup:
public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    builder.AllowAnyOrigin();
                    builder.AllowAnyMethod();
                    builder.AllowAnyOrigin();
                    builder.AllowAnyHeader();
                });
        });

        // configure identity
        services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddIdentityServer()
        .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

        services.AddAuthentication()
            .AddIdentityServerJwt();

        services.AddControllersWithViews()
        .AddNewtonsoftJson(options =>
           options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()
       );

        services.AddRazorPages();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApiVersionDescriptionProvider provider)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            //app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseCors();
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseSwagger();
        app.UseSwaggerUI(
            options =>
            {
                // build a swagger endpoint for each discovered API version
                foreach (var description in provider.ApiVersionDescriptions)
                {
                    options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
                }
            });

        app.UseRouting();
        app.UseAuthentication();
        app.UseIdentityServer();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });
    }

A: I changed the configuration in appsettings and now it work:
   "IdentityServer": {
    "Clients": {
      "BauDrApi": {
        "Profile": "SPA",
        "RedirectUri": "http://localhost:4200/authentication/login-callback",
        "logoutUri": "http://localhost:4200/authentication/logout-callback"
      }
    },
    "Key": {
      "Type": "Development"
    }
  },


text:
Q: Computer crashes / automatically reboots on opening Facebook in any browser For my work in a library I administer a couple of pcs, which can be used by visitors to browse the web. I keep seeing a very strange issue, that leaves me completely stomped.
When a user goes on Facebook the computer freezes for a couple of seconds, then the browser closes, an error message pops up, saying "InitiateSystemShutdown failed.". The message closes at once and the computer reboots.
This doesn't always happen, half the time Facebook works fine.
The environment is as follows:

*

*All PCs run Windows 7 (from the same disk image).

*Windows, Flash and Java are fully patched.

*The problem occurs with all recent versions of IE, Firefox, Opera or Chrome. (Although it feels as if it happens most with Chrome.)

*The PCs are protected by Norton Antivirus and when they reboot, they are completely reset by Faronics Deep Freeze.

*The PCs access the internet through an Ubuntu gateway server somewhere in the town hall. It applies a  content filter and scans for viruses.

I am completely lost. Can anyone give me a pointer on where the problem might be? Or what I could do to narrow down the problem?

A: Turned my comment into answer......

"InitiateSystemShutdown failed." is an API call to shutdown computer.
  Did you check the event logs to see what app is calling it? Faronics?
  System? Like Xavier mentioned, could be a virus and it got on your
  image.

Why is NetLoan/Facebook locking up the browsers/computers? IS it activeX? (not with the gecko & webkit browsers). Adobe Flash? Who knows...
Create a new reference image from scratch and redeploy


text:
Q: UnboundLocalError is seen after few clean runs I see unboundlocalerror at random times. Could you please point me how to fix this?
def find_switch_and_port_cis(wwn):
    with open('zones_list.txt') as fin:
        for line in islice(dropwhile(lambda L: wwn not in L, fin), 1, 15, 1):
            if 'connected interface' in line:
                interface = re.findall(':(\S+)', line)
            elif 'switch name' in line:
                switch_name = re.findall(':(\S+)', line)
        print(wwn, ' is connected to interface:' , interface[0], ' on switch:', switch_name[0])

find_switch_and_port_cis(wwn)

The code gives the expect output:
50:01:43:80:01:1b:42:f6  is connected to interface: fc2/17  on switch: c3-cs9513-02

After few runs but after few runs it throws:
UnboundLocalError: local variable 'interface' referenced before assignment


text:
Q: Get Altitude, Bearing, speed and GPS Accuracy Hy guys, i need to find altitude, bearing and gps accuracy in my iPhone app. i've done this on my android app. in android, i did it like this :
public void onLocationChanged(Location location) {
                if (isBetterLocation(location, lastValidLocation)
                        && isEnable) {
                    lastValidLocation = location;

                    longitude = location.getLongitude();
                    latitude = location.getLatitude();
                    altitude = location.getAltitude();
                    speed = location.getSpeed();
                    accuracy = location.getAccuracy();
                    bearing = location.getBearing();
                    locationProvider = location.getProvider();

                    onPositionChanged(
                            LocationService.this,
                            new GeoPoint(location.getLongitude(), location
                                    .getLatitude()));
                }
            }

how can i do the same thing in iOS ?
i've tried to get it from CLLocation, but it return null/0,0000/-1.0000 ..
btw, i get this result when i test it on iOS Simulator.
Thanks.
Regards.

A: The simulator is not a good place to test Core Location stuff. It only simulates a specific location but if you want to test speed, bearing etc. you're better of trying on a real device.
You need to use the class CLLocationManager (Apple doc) and fetch the data using the delegate protocol available. For example, if you want the heading you implement the method locationManager:didUpdateHeading: and call the method startUpdatingHeading on the location manager.


text:
Q: About trait Index implement of Vector in Rust I check Index trait in doc and find return type of index() is &T.
Then I write this function to get value from vector:
fn get_value_test(a: usize, v: &Vec<i32>) -> i32 {
    v[a]
}

My question is: why v[a] is i32 but &i32? Because i32 ...have a known size at compile time are stored entirely on the stack, so copies of the actual values are quick to make? (from here)
It looks like Rust have hidden rule to convert type in this situation?

A: There was a small misguidance here. Although the method prototype for Index<Idx> is fn index(&self, index: Idx) -> &T, the syntactical operator x[i] does dereference the output from that &T:

container[index] is actually syntactic sugar for *container.index(index) [...]. This allows nice things such as let value = v[index] if the type of value implements Copy.

So there you go. Your function is indeed returning a copy of the value from the vector, but not from an implicit conversion. If the original intent was to really retrieve a reference to that value, you would do &x[i].
See also:

*

*Meaning of the ampersand '&' and star '*' symbols in Rust

*Does Rust automatically dereference primitive type references?


text:
Q: Alternative to np.where when requiring numerous changes to a column in a DataFrame In Python, if I have a data frame in which I want to alter the contents in a particular column from one specific value to another, I so far use the following method using numpy:
df["Country"] = np.where(df["Country"] == "UK", "United Kingdom", df["Country"])
df["Country"] = np.where(df["Country"] == "USA", "United States", df["Country"])

I have about 100 of these types of changes, which looks ungainly in code. Can an example be provided in how to alter the above code in a way that would look more elegant when having numerous extra changes?


text:
Q: Beaglebone black, DLP2000evm cape problem with mono(c#) I am using this image (bone-debian-9.5-lxqt-armhf-2018-10-07-4gb) in my beaglebone black, and also i use DLPDLC2000 EVM projector as a cape.
recently i  followed this link (https://www.ofitselfso.com/Beagle/InstallingMonoOnTheBeagleboneBlack.php)  and install mono in my beaglebone.
i installed mono and then test it with the sample(hello word.exe and another .exe file which i made it in my laptop) and the beaglebone and DLP workperfectly.
the problem is: after restart the beaglebone black, i can see the default screen of dlp but then the dlp have no any lights, I can just see (-) in north right corner and it just blinking
please let me know , what is the problem?
thanks


text:
Q: LibGDX Model Instance color is not passed to Vertex Shader I'm stuck with the following problem for a couple hours now:
In LibGDX, I want to render a ModelInstance with a custom shader like this:
modelBatch.render(modelInstance, shader);

Regarding the shader, I call
shader = new CustomShader();
shader.init();

in the game's create() method.
The CustomShader class looks like this (cut down to the big methods):
public class CustomShader implements Shader {

    ShaderProgram shaderProgram;
    Camera camera;
    RenderContext renderContext;

    @Override
    public void init() {

        shaderProgram = new ShaderProgram(
                Gdx.files.internal("core/assets/Shaders/VertexShader.glsl").readString(),
                Gdx.files.internal("core/assets/Shaders/FragmentShader.glsl").readString()
        );

        if (!shaderProgram.isCompiled()) {

            throw new GdxRuntimeException("Shader program inside water shader is not compiled yet:\n" + shaderProgram.getLog());
        }

        System.out.println("Shader compiled successfully");

        ShaderProgram.pedantic = false;
    }

    @Override
    public void begin(Camera camera, RenderContext renderContext) {

        this.camera = camera;
        this.renderContext = renderContext;

        shaderProgram.begin();
        shaderProgram.setUniformMatrix("u_projViewTrans", camera.combined);
    }

    @Override
    public void render(Renderable renderable) {

        shaderProgram.setUniformMatrix("u_worldTrans", renderable.worldTransform);
        renderable.meshPart.render(shaderProgram);
    }
}

For the vertex shader, I copy-pasted some code, that is supposed to be a simple pass-through shader:
attribute vec3 a_position;
attribute vec4 a_color;

uniform mat4 u_worldTrans;
uniform mat4 u_projViewTrans;

varying vec4 v_color;

void main() {

    v_color = a_color;

    gl_Position = u_projViewTrans * u_worldTrans * vec4(a_position, 1.0);
}

The thing is, the ModelInstance (whether is being made by calling createBox, or by constructing it tri-by-tri with a ModelBuilder) is always rendered flat-red.
The fragment shader does not seem to be the problem; if I hardcode v_color inside the vertex shader like
v_color = vec4(0, 1, 0, 1);

the model gets rendered in green as it should.
What I cannot achieve, is the model being rendered in the color defined by its material.
It seems, that the java code doesn't pass the color down to the vertex shader.
It would be really great if one of you knew the answer; I'm fighting with that problem for ages now.
Thanks in advance!
Edit:
As I only need the shader for ModelInstances of a single model that only has one base color, I don't really need the color, nor the material. Instead, I declare the color as a uniform vec3 inside the vertex shader. This kinda works for the moment, but it is not, what I really want.
So if anybody knows, how the vertex shader can get the color of the rendered Renderable, I'm still open for solutions :)


text:
Q: asyncstorage with useReducer does not save the values i am  new to reactnative, i was trying to build todo app using useReducer and asyncstorage but not able to achieve that, i have read every article and related questions i am able to do it using useState but did not got the result with useReducer.
Any help/suggestions will be appreciated. Thank You .

const MainScreen = () => {
  const getData = async () => {
    try {
      const data = await AsyncStorage.getItem('itemlist');
      return (output = JSON.parse(data));
    } catch (e) {

    }
  };

  React.useEffect(() => {
    getData();
  }, []);

  const [text, setText] = React.useState('');// for textinput

  const { dispatch } = useContext(NotesContext);

  const handleSubmit = async () => {
    try {
      const output = JSON.stringify(state);
      await AsyncStorage.setItem('itemlist', output);
    } catch (error) {
      console.log(error);
    }

    if (text) {
      dispatch({ type: 'ADD_TODO', payload: text });
    }
    setText('');
  };

  //this is my reducer function below
  export const TodoReducer = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return state.concat({
        task: action.payload,
        id: uuid.v4(),
        complete: false,
      });

    case 'DELETE_TODO':
      return state.filter((todo) => todo.id !== action.payload);
    default:
      throw new Error();
  }
};


text:
Q: Purchased font in Hugo Academic not showing on all modern browsers/computers I am trying to use a purchased font in a Hugo Academic website, built with the hugodown R package, but it's only partially working. The font shows up fine in the Preview on RStudio, and on Chrome on my laptop (both on localhost and when deployed to netlify). However, it reverts to the fallback font on Safari on my laptop and on both Safari and Chrome on a different laptop (those are the only two browsers I've tested it with).
The purchased font is LEMONMILKPro (though I have the same trouble with all the fonts that I've tried to declare through @font-face, rather than using Google Fonts). The fallback font is Raleway.
Here's the set-up:

*

*font files (.woff, .woff2) saved in static/fonts

*@font-face declarations in assets/css/custom.css (and repeated for good measure in assests/scss/custom.scss):

@import url("//hello.myfonts.net/count/3c07c5");

@font-face {
  font-family: 'LEMONMILKPro-Medium';
  src: local('LEMONMILKPro-Medium'), url('fonts/LEMONMILKPro-Medium.woff2') format('woff2'), url('fonts/LEMONMILKPro-Medium.woff') format('woff');
}
@font-face {
  font-family: 'LEMONMILKPro-Regular';
  src: local('LEMONMILKPro-Regular'), url('fonts/LEMONMILKPro-Regular.woff2') format('woff2'), url('fonts/LEMONMILKPro-Regular.woff') format('woff');
}
@font-face {
  font-family: 'LEMONMILKPro-Light';
  src: local('LEMONMILKPro-Light'), url('fonts/LEMONMILKPro-Light.woff2') format('woff2'), url('fonts/LEMONMILKPro-Light.woff') format('woff');
}
@font-face {
  font-family: 'LEMONMILKPro-UltraLight';
  src: local('LEMONMILKPro-UltraLight'), url('fonts/LEMONMILKPro-UltraLight.woff2') format('woff2'), url('fonts/LEMONMILKPro-UltraLight.woff') format('woff');
}

*

*font theme (emk_font_set), saved in data/fonts and linked to in config/_default/params.toml, includes:

# Font families
heading_font = "LEMONMILKPro-Regular"
body_font = "LEMONMILKPro-UltraLight"
nav_font = "LEMONMILKPro-UltraLight"

*

*So that I can use Raleway as a back-up font when LEMONMILKPro, isn't working, custom.css and custom.scss also contains

html {
  font-family: "LEMONMILKPro-UltraLight", "Raleway", sans-serif;
}

h1, h2, h3 {
  font-family: "LEMONMILK-Regular", "Raleway", sans-serif;
  text-transform: uppercase;
}

The whole set-up is at https://github.com/EllaKaye/hugodown-website.
The website itself is (temporarily) at https://gallant-shaw-c70134.netlify.app/.
I've pieced together what I've done so far from https://github.com/gcushen/hugo-academic/issues/1061 (though updated slightly for Hugo Academic v4.8) and https://css-tricks.com/snippets/css/using-font-face/. I've read at least a dozen posts/forum queries around this topic and haven't been able to resolve this issue.
I bought LEMONMILKPro and the appropriate licenses on myfonts.com which provided a webkit, including a css stylesheet (and the @import line above), but in order to (attempt to) get that working with Hugo, I've copied the contents of that into custom.scss and custom.css, and tweaked the @font-face declarations and the font file names and locations to match the above local fonts GitHub issue.
Any idea how to get my purchased working on all (modern) browsers on all computers? Thank you!


text:
Q: Error while starting new IPython console in Spyder While I was training a neural network with Pybrain, my computer crashed and I had to reboot it. Now Spyder, Python, IPython seem to work fine, however, when trying to open a new IPython console in Spyder, I get the following error:
Error in sitecustomize; set PYTHONVERBOSE for traceback:
TypeError: 'NoneType' object is not callable
Traceback (most recent call last):
File "C:\Users\Mi\Anaconda3\lib\site‑packages\spyderlib\widgets\externalshell\start_ipython_kernel.py", line 167, in
from IPython.kernel.zmq.kernelapp import IPKernelApp
File "C:\Users\Mi\Anaconda3\lib\site‑packages\IPython\__init__.py", line 48, in
from .core.application import Application
File "C:\Users\Mi\Anaconda3\lib\site‑packages\IPython\core\application.py", line 22, in
from IPython.config.application import Application, catch_config_error
File "C:\Users\Mi\Anaconda3\lib\site‑packages\IPython\config\__init__.py", line 6, in
from .application import *
File "C:\Users\Mi\Anaconda3\lib\site‑packages\IPython\config\application.py", line 19, in
from IPython.config.configurable import SingletonConfigurable
File "C:\Users\Mi\Anaconda3\lib\site‑packages\IPython\config\configurable.py", line 14, in
from IPython.utils.text import indent, wrap_paragraphs
File "C:\Users\Mi\Anaconda3\lib\site‑packages\IPython\utils\text.py", line 28, in
from IPython.external.path import path
File "C:\Users\Mi\Anaconda3\lib\site‑packages\IPython\external\path\__init__.py", line 2, in
from path import *
File "C:\Users\Mi\Anaconda3\lib\site‑packages\path.py", line 122, in
__version__ = pkg_resources.require('path.py')[0].version
TypeError: 'NoneType' object is not callable

The error does not seem to interfere with the execution of Python scripts however I am wondering if I accidentally messed something up. I searched the internet but found nothing that could explain this error.
I am using Python 3.4.3 64 bit with the Anaconda 2.3.0 distribution.

A: Either upgrade setuptools or try
pip install --upgrade --force setuptools fixed it. Either one or the other should fix the problem.

A: The accepted answer is correct in that it is a setup tools problem, but I couldn't use pip install --upgrade --force setuptools, that complained about not being able to find easy-install.pth
Instead I was able to upgrade setuptools using easy-install itself with:
easy_install --upgrade setuptools, hope that helps someone who was stuck like me.

A: I have the same problem. and setuptools did not fix my error.
finally, run
conda update path.py

fix my error. You could check this link: https://github.com/spyder-ide/spyder/issues/2679

A: conda update qt pyqt

conda update spyder

pip install -U spyder

This worked for me


text:
Q: Mef import into objects created after compose I Compose the Container at startup and later on create a Instance of a object that has a Import property. This property is Null when I try to use it.
How does MEF handle objects created later on. I refuse to believe you have to instantiate all objects at startup.

A: You don't have to create instances as soon as you create the container, that wouldn't be any real help for anyone. How are you creating your instances? Here are some examples, given an example class:
[Export]
public class MyClass
{
    [Import]
    public MyOtherClass OtherClass { get; set; }
}

I could:
var myClass = container.GetExportedValue<MyClass>(); // This would automatically compose.

var myExport = container.GetExport<MyClass>();
var myClass = myExport.Value; // This would automatically compose.

var myClass = new MyClass();
container.SatisfyImportsOnce(myClass); // Manually compose your part.

Or manually wind it all together using a CompositionBatch, etc.


text:
Q: XNA 3.1 Laggy movement I have Windows XP SP3.
I created the default XNA project in version 3.1 and added these simple lines to the pregenerated code:
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;

    SpriteBatch spriteBatch;
    Rectangle rectangle = new Rectangle(80, 80, 100, 100);
    Texture2D textureTrain;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";

        //TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 10);
    }
...

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        // TODO: use this.Content to load your game content here
        textureTrain = Content.Load<Texture2D>("MyBitmap1");
    }
...

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // TODO: Add your update logic here
        rectangle.X = rectangle.X + 1;
        rectangle.Y = rectangle.Y + 1;

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here
        spriteBatch.Begin();
        spriteBatch.Draw(textureTrain, rectangle, Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

as simple as this ! But the movement is very laggy, it flickers, I can't even look at it.
If I compare it to some flash games it's incomparable. Why is this? What am I doing wrong?

A: Because your are using the X and Y components of the Rectangle, your calculation will be rounded to the nearest whole number. You want granularity in this case, fine, precise movements.
i.e.
Vector2 position = new Vector2(0.1f, 0.1f);
//Some Arbitrary movement
float speed = 0.008f;
position.X += (float)((speed * position.X);
position.Y += (float)((speed * position.Y);

spriteBatch.Begin();
spriteBatch.Draw(textureTrain, position, rectangle, Color.White);
spriteBatch.End();


text:
Q: How to fix the no 'setup' error in cogs in discord.py? I am getting an error :-  Extension 'cogs.Funny' has no 'setup' function. but I have added the setup function so how do I fix it?
import discord
from discord.ext import commands
import random

class Funny(commands.Cog):
    def __init__(self,client):
        self.client = client

    @commands.command()
    async def rps(self,ctx):
        e = discord.Embed(Title = "Rps",description = "Please react with  for rock,  for paper and ✂ for scissors",color = discord.Colour.blue())
        m = await ctx.send(embed = e)
        z = ['rock','scissors','paper']
        def check(reaction, user):
            return user == ctx.author and str(reaction.emoji) in ['','','✂']

        await m.add_reaction('')
        await m.add_reaction('')
        await m.add_reaction('✂')

        try:
            reaction, user = await self.client.wait_for("reaction_add", check=check)
        except:
            pass
        else:
            if str(reaction.emoji) == '':
                a = random.choice(z)
                if a == 'rock':
                    new = discord.Embed(title = "Result",description = f"The bot chose {a} and u chose rock so its a tie",color = discord.Colour.purple())
                    await m.edit(embed = new)
                elif a == 'scissors':
                    new = discord.Embed(title = "Result",description = f"The bot chose {a} and u chose rock so You Won!!",color = discord.Colour.green())
                    await m.edit(embed = new)
                else:
                    new = discord.Embed(title = "Result",description = f"The bot chose {a} and u chose rock so You lost :(",color = discord.Colour.red())
                    await m.edit(embed = new)

            if str(reaction.emoji) == '':
                a = random.choice(z)
                if a == 'paper':
                    new = discord.Embed(title = "Result",description = f"The bot chose {a} and u chose paper so its a tie",color = discord.Colour.purple())
                    await m.edit(embed = new)
                elif a == 'rock':
                    new = discord.Embed(title ="Result",description =  f"The bot chose {a} and u chose paper so You Won!!",color = discord.Colour.green())
                    await m.edit(embed = new)
                else:
                    new = discord.Embed(title ="Result",description =  f"The bot chose {a} and u chose paper so You lost :(",color = discord.Colour.red())
                    await m.edit(embed = new)
            if str(reaction.emoji) == '✂':
                a = random.choice(z)
                if a == 'scissors':
                    new = discord.Embed(title = "Result",description = f"The bot chose {a} and u chose scissors so its a tie",color = discord.Colour.purple())
                    await m.edit(embed = new)

                elif a == 'paper':
                    new = discord.Embed(title ="Result",description = f"The bot chose {a} and u chose scissors so You Won!!",color = discord.Colour.green())
                    await m.edit(embed = new)
                else:
                    new = discord.Embed(title ="Result",description = f"The bot chose {a} and u chose scissors so You lost :(",color = discord.Colour.red())
                    await m.edit(embed = new)

def setup(client):
    client.add_cog(Funny(client))
    print("fun is loaded")

Edit:- I forgot to tell how  it loads it:-
extensions = [
            'cogs.Funny'
]
if __name__ == "__main__":
    for extension in extensions:
        try:
            client.load_extension(extension)
        except Exception as e:
            print(f"error while loading {extension}",file=sys.stderr)


text:
Q: GETDATE() in SqlServer 2008 is entering different date time on Server than client I am inserting the current date time using GETDATE() in a procedure in SQL SERVER 2008, but GETDATE() is entering different time on server than local server after deploying an application.
I inserted record on 2015-10-28 15.10.07 but on server GETDATE() is inserting 2015-10-28 09:37:17.877, why time difference?

A: The dates and time are different as you used the function at two separate times on two separate machines.
GETDATE() returns the current database system timestamp as a datetime value without the database time zone offset.
This value is derived from the operating system of the computer on which the instance of SQL Server is running.
Source: https://msdn.microsoft.com/en-us/library/ms188383.aspx

A: Your local server and the main server are running on different time zones.
The difference would be removed if you can connect to your main server from your local server and in that particular connection window execute SELECT GETDATE() ..
Hope it helps.


text:
Q: How to display images from SD card in a GalleryView I am trying to display all the images stored in SD card in a Gallery View.
I have tried using the content provider (android.provider.MediaStore.images.Media class),  but seem to be getting stuck at a point. Not sure if this is the way to go about it.
Here is my code so far:
        String[] colsNeeded = new String[]{Media._ID, Media.TITLE};
    Uri mMedia = Media.EXTERNAL_CONTENT_URI;

    //Create a cursor using the URI & column names needd
    Cursor c = managedQuery(mMedia, colsNeeded, null, null, Media.DATE_TAKEN + " ASC");

    //What kind of adapter should I create here
    //that contains images from the cursor??
    SpinnerAdapter sa = null; //This is the point I get stuck

    //Set the adapter of the gallery view
    Gallery galleryPetPhotos = (Gallery)findViewById(R.id.GalleryPetPhotos);
    galleryPetPhotos.setAdapter(sa);

Just a nudge in the right direction would be greatly appreciated.

A: This blog post has a good example on that. It shows you how to do the adapter: http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html
However I would be extending a CursorAdapter instead of a BaseAdapter.


text:
Q: Updating an arraylist of objects in Firestore I have an array list of objects and I want to update my array-list with new data
but, I get an error "Could not deserialize object. Expected a List, but got a class java.util.HashMap (found in field 'students')"
here's my database

Here's the method that's responsible for updating the arraylist
   private void update(){
    Map<String, Object> updatedlist = new HashMap<>();
    for(int i=0; i<studentsList.size(); i++){
        updatedlist.put("name", studentsList.get(i).getName());
        updatedlist.put("id", studentsList.get(i).getId());
        updatedlist.put("attended", studentsList.get(i).isAttended());
    }
    DocumentReference document = db.collection("Records").document(rid);
    document.update("students", updatedlist);
}

for clarification, studentslist is an arraylist of students object ( List < students > studentslist )
I tried converting the array-list to a hash-map as well as updating the list as an array-list but I got an error from both ways.


text:
Q: send and receive data in a https websrevice using soap in iOS - Obj-C Currently I am getting error like "The server cannot service the request because the media type is unsupported." In below steps and I am using soap service to a HTTPS webservice.
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

A: I had resolved this issue by binding HTTPS with HTTP. Now i can access the same webservice with SOAP.


text:
Q: port forwarding in emule I am now connecting to my laptop to my modem using a cable without a router. Testing TCP and UDP in emule fails
Starting TCP connection test...
TCP test failed! UDP test will not be performed.

Connection test finished.

Results in detail:

* TCP connection test failed.
  It was not possible, to establish a TCP connection to your eMule.

Some remarks:
My operating system is Windows 7.  In "Windows Firewall with Advanced Security" that both TCP and UDP for emule have "All Ports" for "Local ports" and "Remote ports". I am not sure if I have other firewalls working too. How to check that?
I have turned off the firewall in my modem, which is Motorola SBG900.
my laptop is from Lenovo. Does the lenovo system software have its own firewall?
my ISP is comcast cable, not sure if emule's default TCP port 17423 and UDP port 11391 would be banned?
my antivirus software is Windows Security Essentials, where I didn't see it has any firewall.

I use the software CurrPorts to see the usage of ports on my computer. Below is a screenshot. Is it normal that the Local Address for emule is 0.0.0.0?

Thanks, harrymc!
(1) But I have turned off the firewall of the modem, does the modem still place restriction on port forwarding?
(2) when I try to specify the ports of emule in this modem, I did not find places to specify which is the protocal, TCP or UDP, for each port. Instead I find an option called "Template", which let me choose one from HTTP, FTP etc but not TCP and UCP. Where can I input TCP or UDP? And which one should I choose for "Template"?
(3) Now I am connecting a router Linksys WRT54GL to the modem via a cable and connecting my laptop to the router via wireless network.
In the Linksys router for each port I have to specify the IP Address in the form of 192.168.1.x, which I guess it is the one of my laptop, which is 192.168.1.102?
If I have to specify the ports of emule again in the modem, is the "LAN ip address" in the form of 192.168.0.x the same as the ip of my laptop when it is connected to the modem by cable directly without using Linksys router?
I tried the above but TCP test still fails not to say UDP.
If I want to specify the ip to be any number in the last field, i.e. all 192.168.1.x for router and all 192.168.0.x for modem, how to specify them?

A: Your router is going to also act as a firewall, so you'll have to open the ports in it as well.  Check out PortForward.com for help, they may even have pre-made instructions for your particular router.
Edit:
From Portforward get the PFPortCheck utility, turn off eMule and use the port checker to test your eMule ports, it will at least help you eliminate eMule as your problem point.
Then, after testing with Portchecker instead of eMule, turn OFF the Windows firewall to eliminate it as a suspect (in case one of the rules you mentioned is misconfigured) and test again.
Unfortunatly there's no 'one way' to check if you have any other firewalls running.

A: @Tim: Your modem is misnamed "cable modem", but it's really a router.
You must forward the eMule ports to your computer.
From its manual:

Gateway > PORT FORWARDING — status Page
Use this page to display the
  configured port forwarding entries on
  the SBG900 LAN. The fields are the
  same as on the Gateway > PORT
  FORWARDING — config Page:

EDIT
You can have only one DMZ computer.
What you should do:

*

*Ensure that only the modem box
distributes DHCP IP addresses so all
machines are on the same network
segment (if I understood correctly
that's the one that's connected to the
internet).

*The router shouldn't set itself up as DHCP server
and shouldn't try to give itself the
same IP address as the modem.

*In the modem config, set the DHCP
server modem to fix the IP of the
designated DMZ machine to be always the same.

*In the modem config, define the
designated machine as DMZ.

This is it.

A: type 192.168.1.1 in your browser. see what pops up (usually will ask for a password). see what model router you have - as techie007 already suggested, go to portforward.com and try to find instructions on how to enable port forwarding for that specific model. do a test at portforward.com for that port.
try then and let us know what happens ...