Q:

change Apache document root in XAMPP

I have just downloaded a website which contains static html pages from a hosting to my localhost (XAMPP) and saved it to a subdirectory in XAMPP htdocs directory.
When I view the local website in browser, all css, js files and images were missing. I checked the HTML source code and saw that it's all using relative path for css/js or href link. For example:
Text Link

It works on the hosting, but on my localhost, it points to http://localhost/contact instead of http://localhost/bf/contact (my subdirectory name is bf). This structure is applied to all css, js files too and they could not be loaded.
I have tried to add .htaccess file to my subdirectory:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !bf/
RewriteRule (.*) /bf/$1 [L]

But it still not works. I don't want to manually change all src, href, and link in every HTML pages to fix this. There would be a way to make Apache recognize the root is /bf instead of / , applied to all files in this directory only. Please help !
Thank you very much !

A:

You can get this work by setting apache virtual host at locally as describe below:
For example in ubuntu /etc/apache2/httpd.conf,
If you are using XAMPP on window that is the case, then the httpd.conf file should be C:\xampp\apache\conf\httpd.conf.
Please follow below steps to configure your local sites at local server:
------------
Step 1
------------
i.e
<VirtualHost *:80>
  ServerName test.demo.tst ( Any name you want to set )
  DocumentRoot "C:/xampp/htdocs/bf"
   <Directory "C:/xampp/htdocs/bf">
      AllowOverride All
      Order allow,deny
      Allow from all
   </Directory>
  #RackEnv development
  ErrorLog C:/xampp/htdocs/bf/logs/test.demo.tst_error
  CustomLog C:/xampp/htdocs/bf/logs/test.demo.tst_access common
</VirtualHost>

------------
Step 2
------------
Than you need to restart apache service

------------
Step 3
------------
Than you need to do setting in your hosts files
for example in hosts file place below entry

127.0.0.1       test.demo.tst

------------
Step 4
------------
Than you can access this url test.demo.tst local server.

I hope this informations would be helpful to you.


Q:

built in methods for Django CBV's

I am learning Django out of pure passion and I seem to have trouble understanding some core principles of Django that really give me headackes and i tried searching online and reading the docs but i don't seem to fully understand. I'll just simply shoot the questions and try to be clear . I apologise for anything stupid I say . I am just trying to get my knowledge straight.
1. What is a "request"?
OK, so I am thinking of a GET request for a webpage but online i see python code like self.request.user.is_superuser and i am thinking of an User object fetched and displayed to the template to which i can apply User methods. It is clearly more to this request than i already know.
2. CBV's built in methods. The get methods. How do they execute? In what order.
I noticed programmers override these methods sometime . If i redefine more than one method in a CBV i start getting weird behaviour.
For example if i declare and redefine 2 methods in a Detail View get_object() and get_queryset() which of them will be executed first after calling the view? Being a method it should be called somehow in order to execute but i don't know the order how  these methods are called for a CBV if there is more than one. Probably i should only define one of them, not both.
3. Queryset. Is it a list?
I have an ideea  what querysets are and that you can apply filters to them but what do they return? Do they return objects of the model i am querying?.
OK so, if i have a DetailView CBV and override the get_queryset() method will this return on object and pass it to my template?. Here I am using a filter but what if am not using a filter. What will the CBV return? Will it return the entire set of objects?
class UserDetailView(LoginRequiredMixin,DetailView):
    context_object_name='user_detail'
    model=models.User
    template_name='basicapp/user_detail.html'
    def get_queryset(self, *args, **kwargs):
        qs = super().get_queryset(*args, **kwargs)
        if not self.request.user.is_superuser:
            qs = qs.filter(pk=self.request.user.pk)
        return qs

4. Can you kindly recommend a Udemy course, video course or book where querysets, CBV methods and ORM are explained clearly?
Preferably video cause it makes so much difference when i see the code working
The thing is I understood how the MVT mechanism works but these class built in methods and overriding them gives me a lot of problems . I never encountered them before and when i start using them  I feel like as if  i am walking in the dark .
Sorry for the long post.
Thanks

A:

What is a request?

It is a HttpRequest object [Django-doc]. This is an object that contains data about the request the client made to the server. For example this contains an attribute .method [Django-doc] that contains a string like 'GET', 'POST', 'PATCH', etc. that specifies the request method used.

but online i see python code like self.request.user.is_superuser and I am thinking of an User object fetched and displayed to the template to which I can apply User methods.

One can install middleware [Django-doc], this is tooling that pre-processes the request, or post-processes the response. Normally the AuthenticationMiddleware [Django-doc] is added in the settings.py file by default. This will add an extra attribute .user to the request that lazily loads the user that has been logged in. If you would remove this middleware, the .user attribute will no longer exist.

CBV's built in methods. The get methods. How do they execute? In what order.

That depends on the specific class-based view. The documentation however specifies how most methods are performed. For example for a ListView [Django-doc], the documentation mentions the method flowchart:

Method Flowchart

setup()
dispatch()
http_method_not_allowed()
get_template_names()
get_queryset()
get_context_object_name()
get_context_data()
get()
render_to_response()

It also links to the methods that explain what these are doing.
In essence, each class-based view can have methods like get, post, put, patch, etc. Based on the method of the request, the request is dispatched to the method with the same name.

Queryset. Is it a list?

No. A QuerySet is an object that more or less represents a query that you can perform on the database. QuerySets are lazy. That means that as long as you do not iterate over them or for example call len(…) over these, they will not make that query. If you iterate, etc. over these, they will make a query to the database, and then you iterate over the result of the query. The results are normally wrapped in model objects (unless you use functions like values(…) [Django-doc] or values_list(…) [Django-doc].

Can you kindly recommend a Udemy course, video course or book where querysets, CBV methods and ORM are explained clearly?

It might help to start with the Django tutorials. These go step-by-step over the architecture of Django. The documentation on the QuerySet API explains how you can make querysets. The page on Query expressions gives examples on how to make more advanced queries. Finally the Django documentation also has a page on class-based views.


Q:

add class to widget_shopping_cart_content in woocommerce

I want to add class to widget_shopping_cart_content in WooCommerce without JS and Jquery. I want to filter fragment in function file.
JS and jquery are not working on this file.
I have found this code in class-wc-ajax.php file and I want to modify this code.
public static function get_refreshed_fragments() {
        ob_start();

        woocommerce_mini_cart();

        $mini_cart = ob_get_clean();

        $data = array(
            'fragments' => apply_filters( 'woocommerce_add_to_cart_fragments', array(
                    'div.widget_shopping_cart_content' => '
' . $mini_cart . '
',
                )
            ),
            'cart_hash' => apply_filters( 'woocommerce_add_to_cart_hash', WC()->cart->get_cart_for_session() ? md5( json_encode( WC()->cart->get_cart_for_session() ) ) : '', WC()->cart->get_cart_for_session() ),
        );

        wp_send_json( $data );
    }

I want to add dropdown-menu class in this
' . $mini_cart . '
'; but how can I didn't know.
Can please any one help me.

A:

Option 1: str_replace();
add_filter('woocommerce_add_to_cart_fragments', 'mm_string_replace_add_to_cart_fragments');

function mm_string_replace_add_to_cart_fragments($fragments){

    return $fragments['div.widget_shopping_cart_content'] = str_replace('class="widget_shopping_cart_content"', 'class="widget_shopping_cart_content dropdown-menu"', $fragments['div.widget_shopping_cart_content']);

}

This does not require additional call to woocommerce_mini_cart() and is much faster but less flexible then other method mentioned below.
Option 2: Overwrite the get_refreshed_fragments function
add_filter('woocommerce_add_to_cart_fragments', 'mm_change_add_to_cart_fragments');

function mm_change_add_to_cart_fragments(){
    ob_start();

    woocommerce_mini_cart();

    $mini_cart = ob_get_clean();

    return array(
        'div.widget_shopping_cart_content' => '
' . $mini_cart . '
',
                )

}

Essentially we are recalling the entire function but with some modifications. So first run on get_refreshed_fragments goes to waste. This is not ideal solution but this is what we have at hand. Use this if you want to modify the html in more detail.


Q:

Using \let with \csname inside a macro

So, I was looking for a way to set some commands to one of a few alternative definitions (i.e. setting \mycommand to one version of the command or others with a simple command invocation), and was hoping to be able to do that with \let and \csname, but trying to compile the following produces no output and complains about missing \begin{document}, extra \endcsname and missing \endcsname inserted.
\documentclass{article}

\newcommand*\letprefix[2]{%
\expandafter\let\csname#1\endcsname\csname#1#2\endcsname %
}

\newcommand*\mycommandversion{I want to use this as ``\\mycommand''}
\letprefix{mycommand}{version}

\begin{document}
Hello!
\mycommand
\end{document}

I've also tried using \def and \newcommand instead of \let and in both cases the document does get built but \mycommand doesn't print anything (the document only contains "Hello!") without any errors or warnings.
I tried it unsuccesfully with lualatex, pdflatex and pdftex with the following:
\def\letprefix #1#2{%
\expandafter\let\csname#1\endcsname\csname#1#2\endcsname %
}

\def\mycommandversion {I want to use this as ``\\mycommand''}
\letprefix{mycommand}{version}

Hello!
\mycommand
\bye

I'm not very familiar with using macros to define other macros, I haven't found anything about using \let in this way (maybe it isn't possible?) and can't understand why the version with \def and \newcommand wouldn't work based on what I found about those instead. Any pointers on how to achieve what I'm trying to do and why this code doesn't work?

A:

With etoolbox you already have a handy tool:
\documentclass{article}
\usepackage{etoolbox}

\newcommand*\letprefix[2]{%
  \csletcs{#1}{#1#2}%
}

\newcommand*\mycommandversion{I want to use this as ``\textbackslash mycommand''}
\letprefix{mycommand}{version}

\begin{document}
Hello!
\mycommand
\end{document}

No need to remember complex sequences of \expandafter.

A:

The problem with the OP's syntax is that the first \csname of the \let was expanded into a token, but not the 2nd.  One nice trick (learned from David C) is that you can insert \expandafter inside a \csname, just before the \endcsname, to expand the next thing that follows, before closing out the first \csname expansion!  That is what I do here, so that both \csnames are expanded into cs-tokens, before the \let is evaluated.
\documentclass{article}

\newcommand*\letprefix[2]{%
  \expandafter\let\csname#1\expandafter\endcsname\csname#1#2\endcsname}

\newcommand*\mycommandversion{I want to use this as ``\textbackslash
  mycommand''}
\letprefix{mycommand}{version}

\begin{document}
Hello!
\mycommand
\end{document}

A:

The answer of Steven B. Segletes says it all.
An alternative less efficient approach is exchanging tokens after applying \csname..\endcsname:
\documentclass{article}

\newcommand\exchange[2]{#2#1}%
\newcommand*\letprefix[2]{%
  \expandafter\exchange\expandafter{\csname#1#2\endcsname}{%
    \expandafter\let\csname#1\endcsname= %
  }%
}%

\newcommand*\mycommandversion{%
  I want to use this as ``\textbackslash mycommand''%
}%

\letprefix{mycommand}{version}

\begin{document}
Hello!
\mycommand
\end{document}

(The image comes from a link to the .jpg-file of Steven B. Segletes' answer.)

A more "generic" approach to the matter could be a macro \NameToCs:
The TeXbook explains a nice feature when it comes to defining macros: In the &langleparameter text&rangle of a macro-definition you can use #{-notation for a macro whose last argument will be delimited by a left curly brace { which—unlike other argument-delimiters—will be re-inserted as if it had been left in place.
Thus I sometimes use a macro-mechanism \NameToCs which processes an argument which is delimited by a left curly brace ({) and another argument which is nested in curly braces.
The argument nested in curly braces is taken for the name of a &langlecontrol sequence token&rangle which is to be constructed via \csname..\endcsname.
\NameToCs works as follows:
\NameToCs&langlestuff not in curly braces&rangle{NameOfCs}
→
&langlestuff not in curly braces&rangle\NameOfCs
(If you wish to obtain only the control-sequence-token \NameOfCs, then you can leave &langlestuff not in curly braces&rangle empty: \NameToCs{NameOfCs} → \NameOfCs)
\makeatletter
\newcommand\exchange[2]{#2#1}%
\@ifdefinable\NameToCs{\long\def\NameToCs#1#{\romannumeral0\innerNameToCs{#1}}}%
\newcommand\innerNameToCs[2]{\expandafter\exchange\expandafter{\csname#2\endcsname}{ #1}}%
\makeatother

There are various uses for such a macro:

\NameToCs{foo} → \foo
\NameToCs\string{foo} → \string\foo
\NameToCs\meaning{foo} → \meaning\foo
\NameToCs\global\long\def{foo}... → \global\long\def\foo...
\NameToCs\newcommand*{foo}... → \newcommand*\foo...
\NameToCs\NameToCs\global\let{foo}={bar} → \NameToCs\global\let\foo={bar}  → \global\let\foo=\bar

Usage-example 6 can be applied in your scenario:
\documentclass{article}

\makeatletter
\newcommand\exchange[2]{#2#1}%
\@ifdefinable\NameToCs{\long\def\NameToCs#1#{\romannumeral0\innerNameToCs{#1}}}%
\newcommand\innerNameToCs[2]{\expandafter\exchange\expandafter{\csname#2\endcsname}{ #1}}%
\makeatother

\newcommand*\mycommandversion{%
  I want to use this as ``\textbackslash mycommand''%
}%

\newcommand*\letprefix[2]{%
  \NameToCs\NameToCs\let{#1}= {#1#2}%
}%

\letprefix{mycommand}{version}

\begin{document}
Hello!
\mycommand
\end{document}

(The image comes from a link to the .jpg-file of Steven B. Segletes' answer.)

Be aware that a simple \let-assignment does not always work out for control-sequences which initiate the carrying-out of a "macro-based mechanism" that internally consists of several macros.

This is the case, e.g., with LaTeX commands that process optional arguments defined in terms of \newcommand or with LaTeX commands that are defined as robust macros by \DeclareRobustCommand.
With such commands the command \LetLtxMacro of the package letltxmacro takes care of the internal macros also.
This is also the case with commands defined in terms of xparse's \NewDocumentCommand.


Q:

Do apps compiled with kinect sdk beta still work with new runtime frameworks

I have an app that was created in kinect sdk beta and I need to execute it in an app that I am creating. My current project is with sdk beta but in the future the whole is going to be ported to the latest kinect sdk. So my question is: will that original app still be executed and still run with the latest microsoft kinect frameworks, drivers etc???

A:

I have created an app on BETA SDK and it runs perfectly with newly installed drivers (obtained by simply connecting a kinect to a usb port) So i suppose they are still included and still run perfectly. But the future is foggy because when the SDK moved from beta to the official it also moved "offices" (from Microsoft Research to Microsoft IEB) and many breaking changes where introduced including namespaces so it is unclear whether they will still run


Q:

Choosing a clever solution: SQL Server or file processing for bulk data?

We have a number of files generated from a test, with each file having almost 60,000 lines of data. Requirement is to calculate number of parameters with the help of data present in these files. There could be two ways of processing the data :

Each file is read line-by-line and processed to obtain required parameters
The file data is bulk copied into the database tables and required parameters are calculated with the help of aggregate functions in the stored procedure.

I was trying to figure out the overheads related to both the methods. As a database is meant to handle such situations, I am concerned with overheads which may be a problem when database grows larger.
Will it affect the retrieval rate from the tables, consequently making the calculations slower? Thus will file processing be a better solution taking into account the database size? Should database partitioning solve the problem for large database?

A:

If you set up indexes correctly you won't suffer performance issues.  Additionally, there is nothing stopping you loading the files into a table and running the calculations and then moving the data into an archive table or deleting it altogether.


Q:

How to properly pass sprites to a std::vector without destroying the sprite's texture in SFML?

From the official SFML tutorials, The White Box Problem:-
"When you set the texture of a sprite, all it does internally is store a pointer to the texture instance. Therefore, if the texture is destroyed or moves elsewhere in memory, the sprite ends up with an invalid texture pointer." Thus you will see a sprite without a texture.
I have a class called World. In this class I made a 2d integer array called level and a vector of type Block called blocks. Now I wanted to store the 'Block' objects inside the vector whenever level[ i ][ j ] = 1.
header file of the 'World' class:-
#ifndef WORLD_H
#define WORLD_H
#include <vector>
#include "Block.h"
#include "Grass.h"
#include <SFML/Graphics.hpp>

using namespace std;

class World
{
    public:
        World();
        void draw(sf::RenderWindow *window);
        vector<Block> blocks;

    private:
        int level[12][16];
        int wd;
        int hi;
};

#endif // WORLD_H

cpp file of the 'World' class :-
#include "World.h"
#include "Grass.h"
#include "Block.h"
#include <iostream>
#include <SFML/Graphics.hpp>

using namespace std;

World::World() : level{
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1},
        {1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1},
        {1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1},
        {1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
    }
{
    wd = 16;
    hi = 12;
    int count = 1;
    //make a 'Block' object and pass it in the vector when level[ i ][ j ] = 1.
    for(int i = 0; i<hi; i++)
    {
        for(int j = 0; j<wd; j++)
        {
            if(level[i][j] == 1)
            {
                Block block(j*50, i*50);
                blocks.push_back(block);
            }
        }
    }
}
void World::draw(sf::RenderWindow *window)
{
    for(unsigned int i = 0; i<blocks.size(); i++)
    {
        blocks[i].draw(window);
    }
}

The 'Block' class has two members - sf::Texture blockT and sf::Sprite block. It also has a draw(RenderWindow *window) method. This is how the 'Block' class is made :-
header file for block class
#ifndef BLOCK_H
#define BLOCK_H
#include <iostream>
#include <SFML/Graphics.hpp>

using namespace std;

class Block
{
    public:
        Block(float x, float y);
        void draw(sf::RenderWindow *window);

    private:
        sf::Texture blockT;
        sf::Sprite block;
};

#endif // BLOCK_H

cpp file for 'Block' class
#include "Block.h"
#include <iostream>
#include <SFML/Graphics.hpp>

using namespace std;

Block::Block(float px, float py)
{
    if(!(blockT.loadFromFile("textures/block.png")))
    {
        cout<<"Could not load block texture."<<endl;
    }
    block.setTexture(blockT);
    block.setPosition(sf::Vector2f(px, py));
    cout<<px<<endl;
    cout<<py<<endl;
}

void Block::draw(sf::RenderWindow *window)
{
    window->draw(block);
}

When I run the program, in place of blocks, only white box is shown. I don't understand how the texture is getting destroyed. This is what the output looks like :-

As you can see, the white places are sprites each of size 50*50 without any texture.
Edit: The Main Function :-
int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "Untitled game");
    window.setVerticalSyncEnabled(true);
    Player player;
    World world;

    //variables

    while(window.isOpen())
    {
        //event handling

        //updating

        //drawing
        window.clear(sf::Color::Black);
        world.draw(&window);
        window.display();
    }

    return 0;
}

A:

When I asked this question I didn't knew much about sprites and textures, but then I learned quite a lot from the internet and sfml tutorials. Actually what I was doing in the program was not correct. I was storing the texture in a local scope which was getting destroyed at the end of the scope. Textures should be stored at a global scope.
In fact, one should use vertex array and map texture coordinates to its vertices, instead of making thousands of sprites,  as it is  faster and more convenient for the graphics card. The lesser the number of calls to the 'draw' function, the better is the performance of the game. So a million sprite objects means a million calls to the 'draw()' function of your application which reduces performance.
Tutorials about the use of vertex arrays in sfml can be found in sfml's website, in the tutorials section.
 http://www.sfml-dev.org/


Q:

SAX XMLParser not working

I have followed multiple online tutorials on how to set up a SAX XML parser for the Android platform but none of them seem to work! Whats the problem? Heres my code:
Imports:
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.util.Log;

This Code is in a method that I know gets called, but why doesent logcat show "TESTING"?
 try {
                URL XMLURL = new URL("https://gdata.youtube.com/feeds/api/videos?q=Crystallize+Lindsey+Stirling+Offical+Music+Video&orderby=relevance");
                SAXParserFactory SPF = SAXParserFactory.newInstance();
                SAXParser SP = SPF.newSAXParser();

                DefaultHandler mainHandler = new DefaultHandler(){

                    @Override
                    public void startElement(String uri, String localName,
                            String qName, Attributes attributes)
                            throws SAXException {

                        if(localName.equals("Link")){

                            String possibleURL = attributes.getValue("href");
                            Log.i("TEST","TESTING");
                        }

                    }
                };

                SP.parse(new InputSource(XMLURL.openStream()),mainHandler);
            } catch (Exception e) {
                e.printStackTrace();

            }

Thanks for any and all help!

A:

This is a namespace issue.
SAXParserFactory SPF = SAXParserFactory.newInstance();
SAXParser SP = SPF.newSAXParser();

is giving you a parser that doesn't properly handle namespaces.
If you change the startElement to check qName for the value "link", your code will work, but that's sort of a band-aid fix.
There are namespaces in this document, though this element is in the default namespace http://www.w3.org/2005/Atom specified for the document.
You should tell the parser factory to give you a namespace-aware parser:
SAXParserFactory SPF = SAXParserFactory.newInstance();
SPF.setNamespaceAware(true);
SAXParser SP = SPF.newSAXParser();

And then you'll get the expected result without changing the startElement method, except you do have to look for the right value, i.e., check for "link" instead of "Link".


Q:

Are alkenes or alkynes reduced first with diimide?

I know that $\ce{NH2NH2}/\ce{H2O2}$ is used as an reducing agent for selective reduction of alkenes and alkynes. $\ce{NH2NH2}$ reacts with $\ce{H2O2}$ to form diimide ($\ce{N2H2}$), which then undergoes a percicylic mechanism with the alkene/alkyne to give the reduced product.
My textbook had this question: what does the reaction of but-1-en-3-yne (vinylacetylene) with 1 equivalent of $\ce{N2H2}/\ce{H2O2}$ give?
Now my question is which reacts first? I know that in electrophillic reactions the alkene has greater reactivity than the alkyne but this is a pericyclic mechanism so i am not sure about it. The given answer is that alkene part reacts, not the alkyne.

A:

Your given answer to the textbook question is seemingly correct. I said seemingly, because this reaction is not well understood to date, even though its first introduction was given at time as far as 1929 (Ref.1). The reaction was mostly hidden without getting attention in literature until to the middle of 20th century. This is mostly because the reactive species of the reaction, the unstable molecule, diimide ($\ce{HN=NH}$) was not well understood.
By 1960's, the unstable $\ce{HN=NH}$ was generated in a variety of ways such as oxydation of hydrazene (by $\ce{H2O2}$ or atmospheric $\ce{O2}$), or decarboxylation of azodecarboxylic acid, or thermal decomposition of p-toluenesulfonylhydrazene. It reacts with alkynes (e.g., diagram A below; Ref.2) and unhindered alkenes (e.g., diagram B below; Ref.3) to transfer two hydrogens in a cyclic process (diagram C below; Ref.4), resulting in a strictly cis reduction. This is the mildest way of performing such reductions. As shown in the diagram A below, one generally useful application of this reduction by diimide is it did not cleave the weak $\ce{C-I}$ bond during the reduction process. Most other reducing agents will cause competing or complete cleavage of the $\ce{C-I}$. The most important advantage in this case is in the conversion of iodoalkyne to vinyl iodide, it gives predominantly the cis-isomer. In addition, it is note worthy that this method of reduction with diimide does not lead to the cleavage of other sensitive functions such as $\ce{O-O}$ and $\ce{N-O}$ bonds.

To my understanding, the type of functions reduced by diimide are depend on the way it was generated. Besides, the rate determining step is always the rate of diimide generation. In general, trans-alkenes react more rapidly than cis-alkenes. During the mechanistic study of reaction, it was reported that diimide reduction of symmetrical multiple bonds proceeds readily. Those bonds included $\ce{C=C}$, $\ce{C#C}$,$\ce{N=N}$, and $\ce{O=O}$. On the other hand, more polar functions such as $\ce{C=O}$, $\ce{C#N}$,$\ce{C=N}$, and $\ce{O-N=O}$ are either very slowly reduced or not reduced at all (Ref.4).
The table 1 has given some uniques alkene substrates used in this process (Ref.5). In this research, 2-nitrobenzenesulfonylhydrazene has been used to generate diimide in situ.

Abstract of Ref.5: A one-pot protocol for the formation of 2-nitrobenzenesulfonylhydrazide (NBSH) from commercial reagents and subsequent alkene reduction is presented. The transformation is operationally simple and generally efficient for effecting diimide alkene reductions. A range of 16 substrates have been reduced, highlighting the unique chemoselectivity of diimide as a reduction system.

A recent publication has shown that diimide can be generated by refluxing haydrazene in air (with solvent). The reduction of diimide generated by this method gives somewhat different results. For example, a norbornene derivative gives 100% conversion in Table 1. However, similar substrate used in Ref.6 has given only 42% yield (Entry 15; Ref.6). Further, a styrene derivative (cis-1-phenylpropene) gives 61% conversion in Table 1. Yet, styrene substrate used in Ref.6 (should be better since it is a terminal alkene) has given only 16% yield (Entry 17; Ref.6). Therefore, it is very convincing that the outcome is highly depend on the metheod of generating diimide,
Based on all, the result of the reaction in the question is uncertain.

References:

J. Hanus, J. Voříšek, "Action de L'hydrazine sur Quelques Acides Incomplets $\ce{C_nH_{2n-2}O_2, \ C_nH_{2n-4}O_2,\ C_nH_{2n-6}O_2}$," Collect. Czech. Chem. Commun. 1929, 1, 223-227 (https://doi.org/10.1135/cccc19290223).
Scott E. Denmark, Shyh-Ming Yang, “Total Synthesis of (+)-Brasilenyne. Application of an Intramolecular Silicon-Assisted Cross-Coupling Reaction,”  J. Am. Chem. Soc. 2004, 126(39), 12432-12440 (https://doi.org/10.1021/ja0466863).
James D. White, Rich G. Carter, Kurt F. Sundermann, Markus Wartmann, “Total Synthesis of Epothilone B, Epothilone D, and cis- and trans-9,10-Dehydroepothilone D,” : J. Am. Chem. Soc. 2001, 123(23), 5407-5413 (https://doi.org/10.1021/jo9710137).
E. E. van Tamelen, R. S. Dewey, M. F. Lease, W. H. Pirkle, “Selectivity and Mechanism of Diimide Reductions,” J. Am. Chem. Soc. 1961, 83(20), 4302-4302 (https://doi.org/10.1021/ja01481a057).
Barrie J. Marsh, David R. Carbery, “One-Pot o-Nitrobenzenesulfonylhydrazide (NBSH) Formation−Diimide Alkene Reduction Protocol,” J. Org. Chem. 2009, 74(8), 3186-3188 (https://doi.org/10.1021/jo900237y).
Hao Chen, Jianmin Wang, Xuechuan Hong, Hai-Bing Zhou, Chune Dong, "A simple and straightforward approach toward selective C=C bond reduction by hydrazine," Canadian Journal of Chemistry 2012, 90(9), 758-761 (https://doi.org/10.1139/v2012-057). Here is the available PDF of the article through Science Gate.


Q:

how to switch/select what code to use while doing cross compiling

I am using the +build tag to define what to compile based on the architecture.
For code that only runs on UNIX/BSD I use this:
// +build freebsd netbsd openbsd dragonfly darwin
// +build amd64

And for linux I have:
// +build linux

The name of the files containing the source code is like this:
watchpid.go
watchpid_linux.go

The files contains the same method signature but different approaches.
func watchPid() {
  // kqueue for UNIX, BSD
  // for loop cross-platform version (linux)
}

In case I would like to test/compile for example the linux version on a Mac OS X, is there a easy switch/trick to do it instead of editing the +build tag  or renaming the files?

A:

Use GOOS=linux go build
Check out https://golang.org/cmd/go/#hdr-Environment_variables and http://dave.cheney.net/2015/08/22/cross-compilation-with-go-1-5


Q:

Profile Memory Between Requests in Rails to Find Leaks

I've got a Rails 4.2.1 app that has a memory leak. I'm hosting on Heroku and when in production my memory continues to grow until the server starts paging. I'm trying to source out the leak - and wanted to know if there is a way I can debug the memory allocations still active after a request / response. If I can get that, I can curl my pages a few times to warm any globals then siege to see what memory is leaking. Any way to do  this?

A:

The rack-mini-profiler gem allows you to get a count of objects in memory by class (and allocated by the current request). It also dumps some of the most frequent objects such as strings - I've found it very helpful for diagnosing memory leaks.


Q:

Fatal error: Class 'Mage_Groupdeals_Helper_Data' not found in magento\app\Mage.php on line 547

I installed groupdeals extension and now when I uninstalled it. Its giving frontend error:

Fatal error: Class 'Mage_Groupdeals_Helper_Data' not found in
  C:\xampp\htdocs\magento\app\Mage.php on line 547

Backend is working fine for me..
I cleared cache, session files and done lots of changes told in stackoverflow question answers like
1) magento-fatal-error-class-mage-foomancommon-helper-data-not-found
2) magento-php-fatal-error-class-xxxxxx-not-found-in-mage-php-on-line-516
3) magento-1-7-fatal-error-class-mage-profile-helper-data-not-found-in-mage-php
and so on.

A:

We need more details about the extension. Without that, we cannot point to a specific reason of this error.
However, this error most probably occurs to due to in-proper uninstallation of groupdeal extension. So make sure you have removed every bit of files of that extension.
The possible locations where you can find files related to this extension is :

1) app\etc\modules\{Namespace_Module.xml}
2) app\code\{community|local}\{Namespace}
3)
  app\design\frontend\base\default\layout\{layout_update_file_of_extension.xml}
4)
  app\design\frontend\base\default\template\{directories_specific_to_this_extension}
5) app\design\adminhtml\{base |
  default}\default\layout\{layout_update_file_of_extension.xml}
6) app\design\adminhtml\{base
  |default}\template\{directories_specific_to_this_extension}
7) skin\{frontend | adminhtml}\{base | default
  }\default\{any_skin_files_related_to_extension}


Q:

Do older repositories no longer work with newer Ubuntu version?

I was hoping to be able to install the awesome Mint Menu in my Gnome Flashback session on Ubuntu 14.04.
Looking around the web, it seemed this was possible, and my searching has led me to this repository, which claims to have ported the Mint Menu to Gnome. At least, as far as I understand it.
However, it seems the repository stopped being maintained around Ubuntu version 11, three years ago. I tried adding the repository and installing Mint Menu anyway, hoping that just because it was old didn't mean it was necessarily unusable. However, it didn't install, giving me unresolvable package dependency issues, which I've learned to not try and solve myself.
Is there no backwards compatibility between repositories? If someone stops maintaining a repository, is it basically dead and useless?

A:

Is there no backwards compatibility between repositories?

Yes, there is but to some extent. For Ubuntu versions you can use repositories through the versions that are not end of life but mixing releases is not recommended.
1 problem you will run into is when there is a big change in the default software. Ubuntu went from Gnome to Unity so any tool depending on the old style will be buggy or completely useless. That probably includes that Mint Menu.

If someone stops maintaining a repository, is it basically dead and useless?

Ubuntu will move the default repositories to an archive so these are still usable to Ubuntu users. How others deal with this is up to them. Personal archives tend to be available on launchpad for all releases (even those end of life).


Q:

Problems with my WHERE clause (SQL)

I'm trying to write a query that returns the following columns:
owner_id,
number_of_concluded_bookings,
number_of_declined_bookings,
number_of_inquiries

However, the problem is that my WHERE clause messes up the query because I am querying the same table. Here is the code:
SELECT owner_id,
Count(*) AS number_of_cancelled_bookings
FROM bookings
WHERE state IN ('cancelled')
GROUP BY owner_id
ORDER BY 1;

It's easy to retrieve the columns individually, but I want all of them. Say I wanted number_of_concluded_bookings as well, that would mean I'd have to alter the WHERE clause ...
Help is greatly appreciated!

A:

Consider conditional aggregations:
SELECT owner_id,
       SUM(CASE WHEN state='concluded' THEN 1 ELSE 0 END) AS number_of_concluded_bookings,
       SUM(CASE WHEN state='cancelled' THEN 1 ELSE 0 END) AS number_of_cancelled_bookings,
       SUM(CASE WHEN state='declined' THEN 1 ELSE 0 END) AS number_of_declined_bookings,
       SUM(CASE WHEN state='inquiries' THEN 1 ELSE 0 END) AS number_of_inquiries
FROM bookings
GROUP BY owner_id


Q:

edit the first word on each line of multiple text file in multiple folder using batch script

I have multiple text files in multiple folder.
In each text files, it consist of this;
0 0.211328 0.386111 0.088281 0.197222
3 0.283984 0.319444 0.067969 0.161111
2 0.387109 0.514583 0.102344 0.112500

I would like to edit the first number on each line to 0, which will look like this;
0 0.211328 0.386111 0.088281 0.197222
0 0.283984 0.319444 0.067969 0.161111
0 0.387109 0.514583 0.102344 0.112500

so far after scouring through stack overflow, i managed to do the code successfully using this script;
@echo off
setlocal EnableDelayedExpansion
FOR /L %y IN (1,1,10000) DO IF EXISTS %y.txt (
    (for /F "tokens=1*" %a in (%y.txt) do (
        FOR /F %c IN ("!var:~0,1!") DO echo 0 %b
        )
    )
) >%y_.txt

however this only works if my .txt filename is a number. I set the range to 10000 because I'm processing over thousands of textfiles in 1 folder. And, this code create a new textfile with the name %y_.txt which %y hold the name of the accessed file and I add _ to avoid filename confusion.
I might need the new text file to just replace the old ones with the same name but by using %y as the new filename doesn't work.
hold on, that's not only it.
I also might need to edit all other .txt files which is located in the one upper folder from this one. The tree folder looks pretty much like this;
   D:
    ├───Folder-A
    │   ├───folder-1
    │   │   ├──1.txt
    │   │   ├──2.txt
    │   │   └──3.txt
    │   └───folder-2
    │       ├──a.txt
    │       └──b.txt
    │
    └───Folder-B
        ├───folder-x
        │   ├──8.txt
        │   ├──9.txt
        │   └──10.txt
        └───folder-y
            ├──y.txt
            └──z.txt

The previous code only works if I am in a specific folder directory and it doesn't go into subfolders.
I tried using dir /b/s *.txt but I'm not sure where to put it.
I hope someone could help me out here. By the way, this is my first time using batch script and also my first task as a graduate trainee. Thanks for your help :D

A:

this will recursively go through the sub directories and find all .txt files and replace the first item with in each line with 0
@echo off
for /f "delims=" %%a in ('dir /b /s /a-d *.txt') do (
    for /f "tokens=1*" %%i in ('type %%~a') do (
     (echo 0 %%j)>>"%%~dpna.tm"
  )
   if exist "%%~dpna.tm" move /Y "%%~dpna.tm" "%%~fa"
 )

Note before you run this! This will create a temp file with the content of the original, once it made the relevant change, it will rename the file to the original (from temp file) so please do not run this in your prod env, until you have tested it in a dummy dir All levels of your dummy directory needs to have temp text files, else this will replace every first whitespace occurring word with a 0
You might also want to add pushd "C:\somedir" after @echo off and popd at the end of the script to ensure it runs the the directory you want it to run in.


Q:

Parsing XML namespaced nodes

I am relatively new to Go but struggling with a basic task. I am parsing a GPX file using the "encoding/xml" package and have the following example xml data;
<gpx creator="StravaGPX" version="1.1" xmlns="http://www.topografix.com/GPX/1/1"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3">
 <metadata>
  <time>2013-02-16T10:11:25Z</time>
 </metadata>
 <trk>
  <name>Demo Data</name>
  <trkseg>
   <trkpt lat="51.6395658" lon="-3.3623858">
    <ele>111.6</ele>
    <time>2013-02-16T10:11:25Z</time>
    <extensions>
     <gpxtpx:TrackPointExtension>
      <gpxtpx:atemp>8</gpxtpx:atemp>
      <gpxtpx:hr>136</gpxtpx:hr>
      <gpxtpx:cad>0</gpxtpx:cad>
     </gpxtpx:TrackPointExtension>
    </extensions>
   </trkpt>

So far I am able to get at the most basic info with the following types;
type Gpx struct {
    Creator string `xml:"creator,attr"`
    Time string `xml:"metadata>time"`
    Title string `xml:"trk>name"`
    TrackPoints []TrackPoint `xml:"trk>trkseg>trkpt"`
}

type TrackPoint struct {
    Lat float64 `xml:"lat,attr"`
    Lon float64 `xml:"lon,attr"`
    Elevation float32 `xml:"ele"`
    Time string `xml:"time"`
    Temperature int `xml:"extensions>gpxtpx>atemp"`
}

Where I am failing to parse is in TrackPoint.Temperature. I cannot get the tag right to match the namespaced nodes underneath extensions.
Any suggestions as to where I am going wrong?

A:

You're targeting a namespace instead of a variable name in your TrackPoint.Temperature xml instructions.
Change
Temperature int `xml:"extensions>gpxtpx>atemp"`

To
Temperature int `xml:"extensions>TrackPointExtension>atemp"`

Here's a working copy in the playground.
package main

import (
    "fmt"
    "encoding/xml"
    )

type Gpx struct {
    Creator string `xml:"creator,attr"`
    Time string `xml:"metadata>time"`
    Title string `xml:"trk>name"`
    TrackPoints []TrackPoint `xml:"trk>trkseg>trkpt"`
}

type TrackPoint struct {
    Lat float64 `xml:"lat,attr"`
    Lon float64 `xml:"lon,attr"`
    Elevation float32 `xml:"ele"`
    Time string `xml:"time"`
    Temperature int `xml:"extensions>TrackPointExtension>atemp"`
}

func main() {
    data := `<gpx creator="StravaGPX" version="1.1" xmlns="http://www.topografix.com/GPX/1/1"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3">
 <metadata>
  <time>2013-02-16T10:11:25Z</time>
 </metadata>
 <trk>
  <name>Demo Data</name>
  <trkseg>
   <trkpt lat="51.6395658" lon="-3.3623858">
    <ele>111.6</ele>
    <time>2013-02-16T10:11:25Z</time>
    <extensions>
     <gpxtpx:TrackPointExtension>
      <gpxtpx:atemp>8</gpxtpx:atemp>
      <gpxtpx:hr>136</gpxtpx:hr>
      <gpxtpx:cad>0</gpxtpx:cad>
     </gpxtpx:TrackPointExtension>
    </extensions>
   </trkpt>
  </trkseg>
 </trk>
`
    g := &Gpx{}
    _ = xml.Unmarshal([]byte(data), g)
    fmt.Printf("len: %d\n", len(g.TrackPoints))
    fmt.Printf("temp: %v\n", g.TrackPoints[0].Temperature)
}


Q:

What is the APPCMD.EXE syntax to remove all IP Address and Domain Restrictions from a website?

I have the syntax to add the initial Restricted IPs.  I just need syntax to remove all IPs for automation purposes.
C:\Windows\System32\inetsrv\appcmd.exe set config "ParentSite" /section:system.webServer/security/ipSecurity /allowUnlisted:false /commit:apphost
C:\Windows\System32\inetsrv\appcmd.exe set config "ParentSite" /section:system.webServer/security/ipSecurity /+"[ipaddress='192.168.1.100',allowed='true'" /commit:apphost

I do know setting allowUnlisted to true effectively accomplishes my underlying goal.  I just want things to be clean in IIS.
C:\Windows\System32\inetsrv\appcmd.exe clear config "ParentSite/ChildSite" /section:system.webServer/security/ipSecurity /commit:apphost
C:\Windows\System32\inetsrv\appcmd.exe set config "ParentSite/ChildSite" /section:system.webServer/security/ipSecurity /allowUnlisted:true /commit:apphost

A:

There is an additional parameter ("delete") you can add to the "clear" command to force IIS to remove the section as well as clearing the contents of it;
C:\Windows\System32\inetsrv\appcmd.exe clear config "ParentSite/ChildSite" /delete:true /section:system.webServer/security/ipSecurity /commit:apphost

I've tested this on server 2012 R2 / IIS 8.5, but it also exists on versions at least as low as server 2008 R2 IIS 7.5


Q:

Kinect-Matlab: Get joint angle information

I am a beginner at kinect and I want to use it with matlab. I need joint angle information out of the skeleton data. What is the easiest way to do this?
Thanks.

A:

I am not good with Mat lab, but try to use c# with Visual Studio. Use the SkeletonBasics-WPF in the Microsoft SDK´s as a template to add this code:
public class Angles
    {
    public double AngleBetweenTwoVectors(Vector3D vectorA, Vector3D vectorB)
        {
            double dotProduct;
            vectorA.Normalize();
            vectorB.Normalize();
            dotProduct = Vector3D.DotProduct(vectorA, vectorB);

            return (double)Math.Acos(dotProduct)/Math.PI*180;
        }

        public byte[] GetVector(Skeleton skeleton)
        {
            Vector3D ShoulderCenter = new Vector3D(skeleton.Joints[JointType.ShoulderCenter].Position.X, skeleton.Joints[JointType.ShoulderCenter].Position.Y, skeleton.Joints[JointType.ShoulderCenter].Position.Z);
            Vector3D RightShoulder = new Vector3D(skeleton.Joints[JointType.ShoulderRight].Position.X, skeleton.Joints[JointType.ShoulderRight].Position.Y, skeleton.Joints[JointType.ShoulderRight].Position.Z);
            Vector3D LeftShoulder = new Vector3D(skeleton.Joints[JointType.ShoulderLeft].Position.X, skeleton.Joints[JointType.ShoulderLeft].Position.Y, skeleton.Joints[JointType.ShoulderLeft].Position.Z);
            Vector3D RightElbow = new Vector3D(skeleton.Joints[JointType.ElbowRight].Position.X, skeleton.Joints[JointType.ElbowRight].Position.Y, skeleton.Joints[JointType.ElbowRight].Position.Z);
            Vector3D LeftElbow = new Vector3D(skeleton.Joints[JointType.ElbowLeft].Position.X, skeleton.Joints[JointType.ElbowLeft].Position.Y, skeleton.Joints[JointType.ElbowLeft].Position.Z);
            Vector3D RightWrist = new Vector3D(skeleton.Joints[JointType.WristRight].Position.X, skeleton.Joints[JointType.WristRight].Position.Y, skeleton.Joints[JointType.WristRight].Position.Z);
            Vector3D LeftWrist = new Vector3D(skeleton.Joints[JointType.WristLeft].Position.X, skeleton.Joints[JointType.WristLeft].Position.Y, skeleton.Joints[JointType.WristLeft].Position.Z);
            Vector3D UpVector = new Vector3D(0.0, 1.0, 0.0);

            double AngleRightElbow = AngleBetweenTwoVectors(RightElbow - RightShoulder, RightElbow - RightWrist);
            double AngleRightShoulder = AngleBetweenTwoVectors(UpVector, RightShoulder - RightElbow);
            double AngleLeftElbow = AngleBetweenTwoVectors(LeftElbow - LeftShoulder, LeftElbow - LeftWrist);
            double AngleLeftShoulder = AngleBetweenTwoVectors(UpVector, LeftShoulder - LeftElbow);

            byte[] Angles = {Convert.ToByte(AngleRightElbow), Convert.ToByte(AngleRightShoulder),Convert.ToByte(AngleLeftElbow),Convert.ToByte(AngleLeftShoulder)};
            return Angles;
        }
}

Insert this at the top. Call the GetVector() method here:
 private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {

            Skeleton[] skeletons = new Skeleton[0];

            using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
            {
                if (skeletonFrame != null)
                {
                    skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
                    skeletonFrame.CopySkeletonDataTo(skeletons);

                }
            }

            using (DrawingContext dc = this.drawingGroup.Open())
            {
                // Draw a transparent background to set the render size
                dc.DrawRectangle(Brushes.Black, null, new Rect(0.0, 0.0, RenderWidth, RenderHeight));

                if (skeletons.Length != 0)
                {
                    foreach (Skeleton skel in skeletons)
                    {
                        RenderClippedEdges(skel, dc);

                        if (skel.TrackingState == SkeletonTrackingState.Tracked)
                        {
                            this.DrawBonesAndJoints(skel, dc);
                            Angles MyAngles = new Angles();
                            byte[] ReadyAngles = MyAngles.GetVector(skel);
                            RightElbow.Text = ReadyAngles[0].ToString();
                            RightShoulder.Text = ReadyAngles[1].ToString();
                            LeftElbow.Text = ReadyAngles[2].ToString();
                            LeftShoulder.Text = ReadyAngles[3].ToString();
                            byte[] SequenceStart = {255};

                            if (ArduinoPort.IsOpen)
                            {
                                ArduinoPort.Write(SequenceStart,0,1);
                                ArduinoPort.Write(ReadyAngles, 0, 4);
                            }
                        }
                        else if (skel.TrackingState == SkeletonTrackingState.PositionOnly)
                        {
                            dc.DrawEllipse(
                            this.centerPointBrush,
                            null,
                            this.SkeletonPointToScreen(skel.Position),
                            BodyCenterThickness,
                            BodyCenterThickness);
                        }
                    }
                }

                // prevent drawing outside of our render area
                this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, RenderWidth, RenderHeight));
            }
        }

As you can see I added 4 textboxes as I am calculating 4 Angles (RS, LF, RE, LE). These Angles are being passed to the textbox in my .xaml file. I hope this works for you.


Q:

custom taxonomy sort order not working

I have created a custom taxonomy named product_categories.
It has three fields :

for banner image
for category image and
for sort order.

I have added 10 categories in it giving its sort order input also.
Now i want to show this in sorting order but it is not working.
In pt-categories input for sort order is this

<?php _e('Product Sort Order'); ?>

    <input id="banner-url" name="term_meta[sort_order]" type="text" style="width: 100%;" value="<?php echo $term_meta['sort_order'] ? $term_meta['sort_order'] : ''; ?>" />
    <?php _e(' '); ?>

Saving funtion is this
    function save_product_categories_custom_fields($term_id)
    {
    if (isset($_POST['term_meta'])) {
        $t_id = $term_id;
        $term_meta = get_option("taxonomy_term_$t_id");
        $cat_keys = array_keys($_POST['term_meta']);
        foreach ($cat_keys as $key) {
            if (isset($_POST['term_meta'][$key])) {
                $term_meta[$key] = $_POST['term_meta'][$key];
            }
        }
     //save the option array
        update_option("taxonomy_term_$t_id", $term_meta);
    }
}

Here is the categories called
function getLatestProducts() {
$args = array(
  'post_status' => 'publish',
  'post_type' => 'products',
  'posts_per_page' => 12,
  'meta_key'        => '_cus_sort_order',
  'orderby'         => 'meta_value_num',
  'order' => 'ASC'
);
?>
<?php
                $args = array(
                'orderby' => 'name',
                );
                $terms = get_terms('product_categories', $args);
                foreach($terms as $term) {
               $prod_meta = get_option("taxonomy_term_".$term->term_id);
                    ?>
                <a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
                <?php
                    echo '';    ?>

                <a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
                <?php echo $term->name;?>

It is showing the categories names and images but not in sorted order.

A:

You have a mistake in your code of Categories Called
Corrected Code
function getLatestProducts() {
    $args = array(
    'post_status' => 'publish',
    'post_type' => 'products',
    'posts_per_page' => 12,
    'meta_key'        => '_cus_sort_order',
    'orderby'         => 'meta_value_num, name',
    'order' => 'ASC'
);
            $terms = get_terms('product_categories', $args);
            foreach($terms as $term) {
           $prod_meta = get_option("taxonomy_term_".$term->term_id);
                ?>
            <a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
            <?php
                echo '';    ?>

            <a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
            <?php echo $term->name;?>

I have removed an array of argument which is called after main arguments array. As the below mentioned argument array is overriding the above mentioned arguments array.
Removed Arguments Array
$args = array(
    'orderby' => 'name',
);

Hope this helps!


Q:

how can i get the right value and set in text view with image pager adapter?

What I have is a class called FullImageActivity2 which displays images and I can flip between images with a pager adapter also in this activity I have a TextView which should display an item id for each image and it takes it values from a string array. I could connect the TextView with the value but the value does not change when I flip the image, I mean that I want each image to be connected with it's id and when I flip the image it should change and display the correct image.
here is my activity code :
public class FullImageActivity2 extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_image_activity2);
        String[] nameArray={"Su6670","SU10670","PB6670","PB10670"};
        TextView itemid=(TextView)findViewById(R.id.itemid);
         //get intent data

 //Selected image id
Integer[] newArray={R.drawable.bottle1,R.drawable.bottle2,R.drawable.bottle3,R.drawable.bottle4};

    ImageAdapter imageAdapter = new ImageAdapter(this, newArray);
    List<ImageView> images = new ArrayList<ImageView>();

    for (int i1 = 0; i1 < imageAdapter.getCount(); i1++) {
        ImageView imageView = new ImageView(this);

        imageView.setImageResource(imageAdapter.mThumbIds[i1]);

        itemid.setText(nameArray[i1]);

        images.add(imageView);
    }

    // Finally create the adapter
    ImagePagerAdapter imagePagerAdapter = new ImagePagerAdapter(images);
    ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
    viewPager.setAdapter(imagePagerAdapter);
    for (int m=0; m<imagePagerAdapter.getCount();m++){
          itemid.setText(nameArray[m]);
    }

    }
}

and here is the image pager adapter code :
 public class ImagePagerAdapter  extends PagerAdapter{
            private List<ImageView> images;

            public ImagePagerAdapter(List<ImageView> images) {
                this.images = images;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                ImageView imageView = images.get(position);
                container.addView(imageView);
                return imageView;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(images.get(position));
            }

            @Override
            public int getCount() {
                return images.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object o) {
                // TODO Auto-generated method stub
                  return view == o;
            }
        }

it always display the value PB10670 in the TextView. How can I fix this problem?

A:

You have to set a OnPageChangeListener to your ViewPager like
viewPager.setOnPageChangeListener(new OnPageChangeListener()
{

    @Override
    public void onPageSelected(int arg0)
    {
        itemid.setText(nameArray[arg0]);
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2)
    {
    }

    @Override
    public void onPageScrollStateChanged(int arg0)
    {
    }
});

This way whenever you flip your image the text in your TextView will change depending on the current position.


Q:

Since Control.CreateChildControls is marked as protected internal, it should not be visible inside

I can’t figure out why Control.CreateChildControls is visible in web page’s code-behind class. Namely, Control.CreateChildControls is defined as protected internal, which means that method is visible only to derived classes located inside the same assembly as Control class. So how is that possible since as as far as I know, web-page class is not compiled into same assembly  as Control class ( System.Web.dll )?
thanx

A:

Unfortunately, the wording of 'protected internal' is misleading. It means 'protected' or 'internal' and not 'protected' and 'internal'.
In your %program files%\microsoft visual studio 9.0\vc#\Specifications\1033, you have the C# reference manual, this is at section 1.6.2.
Therefore a derived class can use it.


Q:

Adjust jQuery code to show/hide div in CodeIgniter

I'm moving my site from HTML/CSS into CodeIgniter. Have some experience with PHP, but not much with jQuery.
The jQuery script I was using to .show()/.hide()
s worked fine with HTML pages, but doesn't work in CodeIgniter. I know what the script does (and I have attempted a few hours worth of modifications), but can't get it to function properly in CodeIgniter.
Here's what's happening: When I click on the  link, a new page opens, instead of opening the view into the
. Because of CodeIgniter's controllers, I'm not actually opening the page. I think this is where the difficulty is, but am not sure.
On the CodeIgniter side: I’ve already autoloaded the JavaScript library, and I am calling the script in the header. Here’s the jQuery code (HTML below):
$(document).ready(function() {

    var hash = [removed].hash.substr(1);
    var href = $('#nav li a').each(function(){
        var href = $(this).attr('href');
        if(hash==href.substr(0,href.length-5)){
            var toLoad = hash+'.html #content';
            $('#content').load(toLoad)
        }
    });

    $('#nav li a').click(function(){

    var toLoad = $(this).attr('href')+' #content';
    $('#content').hide('fast',loadContent);
    $('#load').remove();
    $('#wrapper').append('LOADING...');
    $('#load').fadeIn('normal');
    [removed].hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
    function loadContent() {
        $('#content').load(toLoad,'',showNewContent())
    }
    function showNewContent() {
        $('#content).show('normal',hideLoader());
    }
    function hideLoader() {
        $('#load').fadeOut('normal');
    }
    return false;

    });
});

and the HTML:

Option 1

Option 2

Messages

<div id="rightcol"

A:

After you make sure your JS code is valid, try to put the preventDefault method, to prevent browser from following the anchor link.
JSLint is a great tool for checking your JS scripts.


Q:

Short story about amnesiac man sent to a prison planet

Plot Summary/Details
The protagonist appears in a teleportation station, apparently very sick.  His first thoughts are about a mishap in the teleportation process, and is trying to recall the steps you're supposed to take to keep it together until the worst of it passes.  The man recovers shortly, but realizes he's not in the teleportation station near his home, but in a completely foreign place. He also sees there is no return teleporter. Completely unaware of how he got to this place, or why he's there, he exits the station and tries to find help in the town outside.
The man asks passersby for help, but is ignored at best, and treated roughly at worst.  It is a very unfriendly place.  Parched with thirst, he approaches a woman who has a mug or cup of something.  He asks her for a drink, but she clutches the drink to her chest, saying something like "mine, mine.  I carried wood for my share." She sullenly directs him to a large structure where he can get water instead.
I'm a little fuzzy on how the next part of the story goes.  At some point, he meets a seasoned old man, who has been living on the planet for some time.  I believe this man explains to the protagonist he is on a planet used exclusively as a prison for "the worst of the worst", or something like that.  The idea behind it being, it was a foolproof way for society to deal with the worst offenders, in a way that cost little and represented no risk.  There is no way off the planet, which is uninhabited, outside of the town/city the prisoners call home.   The only non-prisoners are the staff inside the structure where the protagonist was told to get water.  There is a water and food dispenser set into the outside wall, and a small chamber a seriously ill or injured prisoner can submit themselves for treatment.  There is no other way to access the structure.
The protagonist, now horrified that he's been put on a planet with hardened criminals, wants nothing more than to see one of the staff and try to explain to them that a terrible mistake has been made.  He enters the chamber, but the computer scanners detect that there is nothing physically wrong with him, and he is put back outside the structure.  The older man has a sort of "I told you so" attitude, but  takes the despondent protagonist under his wing.
We learn that the older man is a serial murderer, who poisoned a number of people before being caught.  His skills with chemistry also make him a skilled brewer, though, and thus popular.  The prisoners figured out long ago how to ferment and distill a local plant into a rough, but potent alcohol.  This is what the woman in the first part of the story was carrying in her mug.  The older man jokes he knows a few tricks that would make it taste more palatable, but his history as a poisoner make people wary of his "additions."
The older man treats the protagonist to a mug or two of the beverage, and tries to get him acclimated to his surroundings and some of the other prisoners.  Despite this, the protagonist becomes increasingly desperate, and finally seizes upon the idea of injuring himself so he can gain access to the staff.  He asks the older man to cut off a joint of one of his fingers.  The older man complies, but his sadistic nature kicks in during the process, and he gleefully hacks off two entire fingers.
The protagonist again lies down in the chamber, and this time is accepted into the structure.  He wakes to find himself strapped to a table, with a doctor working on him, and several well-armed security personnel in close proximity.  The protagonist pleads his case, and asks the doctor to search his records to see the mistake that has been made.  The doctor, moved by the protagonist's plea, does so.   It is then that we learn the protagonist is not there by mistake.   He brutally murdered his own wife, and was sentenced to the planet justly.  He simply has forgotten due to whatever trauma he suffered when he was teleported to the surface.
The story closes with the protagonist being treated and returned to the outside world.  The story closes with the protagonist, still unable to remember his crimes and in total denial, saying something to the effect of "how am I ever going to get home to see my wife now?"
Publication timeframe
I think this one is late 2000's, or even 2010's.  I'm pretty sure I read it in a sci-fi magazine (can't remember which one, obviously), and not an anthology or other collection.

A:

"Waiting Place", a short story by Harry Harrison in his Matter Transmitter series; originally published in Galaxy Magazine, June 1968; previously identified as part of the answer to this question. The ending:

The metal coffin lid opened, and Jomfri sat up, dizzy. They had drugged him; he was hazy; they had tended his wounds.
"But they wouldn't help me. They wouldn't even look in the records to prove my innocence. A mistake. A fault in the matter transmitter, and I am condemned because of it."
He looked at the bloodstained bandages, and something hurt in his head.
"Now I'll never get home to my wife," he sobbed.


Q:

Function arity of a first-class function

I'm rewriting PHP type system and working on implementation of a more pure language. I'm implementing as much as I can in question of purism as functional and object-oriented language, like method-chaining, types as objects, message-passing, conditionals as methods and some other features http://github.com/haskellcamargo/rawr. In this, functions will be instance of  Func class and after I'll do a transcompiler for it, because PHP has gone so far as it is. Func will not limit to unary functions as parameters, but will check if, when called, the number of arguments matches exactly the  number of expected arguments:
$add = Func(function(Number $x) {
  return Func(function(Number $y) use ($x) {
    return $x -> add ($y);
  });
});

Where add will be a function where I don't need to control its arity, as much as it is unary and works by currying. But when I work with functions that receive multiple parameters, my problem appears. Let's take as example a simple function that outputs a name in the screen:
$say_name = Func(function(String $name) {
  $name -> outputln();
});

$say_name requires 1 unique parameter but how can I assert that it will receive n parameters, being n the arity of this anonymous function?
$say_name -> invoke("Test"); might work, but $say_name -> invoke("Test", 1); also works because I'm not getting a way to know the arity of a anonymous function.
function () { return func_num_args(); }
This will return the number of arguments passed to it. I need to know the number of required arguments to x, something like:
function x(Int $i, Functor $j) { return a_magic_function_that_returns_it_all(); }
And outputs me something like array(2) { [0]=> Int [1]=> Functor }. Can somebody help me with that?

A:

Solved with usage of ReflectionFunction:
 $add = function($x, $y) { return $x + $y; };
 $x = new ReflectionFunction($add);
 $args = $x->getParameters();
 var_dump(count($args)); // 2


Q:

Several Brother printer models not printing

I have two Brother printers : an MFC-9330CDW and a QL-1050.
Since Ubuntu 16.04 doesn't seem to provide drivers for these models, I downloaded and installed drivers from the Brother website.
The printers were automagically detected by Ubuntu, and anyway I was able to delete and add them again through the CUPS server interface (http://localhost:631).
However in both case I am not able to print any document.  Even the test page won't print (though the "self test page" does) : it appears briefly in the queue, then disappears silently.
I suspect an issue with CUPS filters, since it does print when using lpr -o raw.
What could be the problem ?
Side note : I noticed that the Brother website advices ia32-libs or lib32stdc++ as requirements for Debian 64 and Ubuntu 64, but apt says there are no such packages.

A:

The "side note" is actually the issue : Brother only provides 32-bit drivers, they don't work as is on 64-bit distributions.
The drivers should work after installing these packages instead of the missing ones suggested by Brother :
sudo apt-get install lib32z1 lib32ncurses5 lib32stdc++6

(Actually they may not all be needed, please someone test them separately and edit this answer accordingly.)


Q:

What is the most succinct way to use '!=' operator when comparing multiple values to the same variable?

EDIT:
I did not mean efficiency as in the program running more efficiently, but I meant it as a quicker way to program the if statement.
I am trying to find a way to reduce my code for efficiency.
For example: if(x!=10 && x!=20 && x!=30){} //etc`
I tried this, and I tried multiple other methods:
if(x!=(10 && 20 && 30){}

It does not work. Is there a way to reduce the size of this if statement?

A:

One way would be to use a switch:
switch (x)
{
    case 10:
    case 20:
    case 30:
        break;
    default:
        // do something ...
        break;
}

Another way is to use an array (or equivilent STL container, like std::vector or std::array):
#include <algorithm>

const int okValues[] = {10, 20, 30};
const int *end = &okValues[3];

if (std::find(okValues, end, x) == end)
{
    // do something ...
}

#include <vector>
#include <algorithm>

std::vector<int> okValues;
okValues.push_back(10);
okValues.push_back(20);
okValues.push_back(30);

/* or, in C++11 and later:
std::vector<int> okValues {10, 20, 30};
*/

if (std::find(okValues.begin(), okValues.end(), x) == okValues.end())
{
    // do something ...
}

// C++11 and later only...

#include <array>
#include <algorithm>

std::array<int, 3> okValues = {10, 20, 30};

if (std::find(okValues.cbegin(), okValues.cend(), x) == okValues.cend())
{
    // do something ...
}

Another way is to use a std::set:
#include <set>

const int arr[] = {10, 20, 30};
const std::set<int> okValues(arr, arr+3);

/* or, in C++11 and later:
const std::set<int> okValues {10, 20, 30};
*/

if (okValues.find(x) == okValues.end()) // or cend() in C++11 and later
{
    // do something ...
}

Or, in the very specific case of your particular 3 example values:
int result = x / 10;
int remainder = x % 10;

if ((result < 1) || (result > 3) || (remainder != 0))
{
    // do something...
}


Q:

Disable scientific notation on axes using Bokeh

How can you disable scientific output of numbers on an axis in bokeh?
For example, I want 400000 and not 4.00e+5
In mpl: ax.get_xaxis().get_major_formatter().set_scientific(False)

A:

You can disable scientific notation with this:
fig = plt.figure(title='xxx', x_axis_type='datetime')
fig.left[0].formatter.use_scientific = False

A:

Note that as of Bokeh v0.9.1, Marek's answer will no longer work due to changes in the interface for Charts. The following code (from GitHub) is a fully-functional example of how to turn off scientific notation in a high level chart.
from bokeh.embed import components
from bokeh.models import Axis
from bokeh.charts import Bar
data = {"y": [6, 7, 2, 4, 5], "z": [1, 5, 12, 4, 2]}
bar = Bar(data)
yaxis = bar.select(dict(type=Axis, layout="left"))[0]
yaxis.formatter.use_scientific = False
script, div = components(bar)
print(script)
print(div)

The key lines are:
yaxis = bar.select(dict(type=Axis, layout="left"))[0]
yaxis.formatter.use_scientific = False


Q:

Why am I getting mime-type of .csv file as "application/octet-stream"?

I'm working on a PHP application that must import an excel file into MySQL. So I need to convert the excel file to .csv format. But when I want to get its type using $_FILE['something']['type'] , I get application/octet-stream as its mime-type;
I think there is something wrong here. Because I gathered the list below as a .csv file mime-type:
text/comma-separated-values,
text/csv,
application/csv,
application/excel,
application/vnd.ms-excel,
application/vnd.msexcel

What's the matter ?

A:

In times like these, the official HTTP specification is always helpful. From RFC 2616 7.2.1 (my emphasis added):

Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".

The cause of your issue is that the server accepting the file upload does not itself know what type of file has been uploaded. Why? Because it relies on the the HTTP message which sent the file to specify a Content-Type header to determine the exact mime-type. The browser has likely not sent a Content-Type header and the server has assumed application/octet-stream as per the official HTTP specification excerpt above. It's also possible that the client uploading the file opted not to determine the mime type of the file it was uploading and sent the Content-Type: application/octet-stream header itself.
Now, when we consider this in conjunction with the PHP manual entry regarding POST file uploadsdocs, we see the following:

$_FILES['userfile']['type']
The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.

So as you can see, even if $_FILES['userfile']['type'] is specified, it only corresponds to the Content-Type header sent by the client. This information can easily be faked and should not be relied upon. If you need to be sure that the uploaded file is of a specific type, you'll have to verify that yourself.

A:

application/octet-stream is always used if the mime type is not known.


Q:

Change Value of Linq Grouping

I have the following Grouping:
IGrouping<string, Tuple<IFileInfo, XDocument>>

I'd like to convert this to the simplified grouping of just:
IGrouping<string, XDocument>

What's the simplest way to do this?
Additional information:
The initial group was created from a list of
IEnumerable<Tuple<IFileInfo, XDocument>> myList

by calling
myList.GroupBy(x => GetSomePropertyToGroupBy(x.Item2));

To return a list of
IEnumerable<IGrouping<string, Tuple<IFileInfo, XDocument>>>

It's the IGrouping> aspect of this list that I want to filter down to just contain the XDocument from the Tuple, not the IFileInfo.

A:

Looking at your comment, you can use this GroupBy overload to select the key and the element:
IEnumerable<IGrouping<string, XDocument>> groups =
    myList.GroupBy(
        x => GetSomePropertyToGroupBy(x.Item2),
        x => x.Item2);


Q:

Equals button in calculator doing nothing (Android Developer Tools)

I cant really figure out, I am beginner to programming, doing it for about 2 months. I have made calculator for Android, but problem is that equals button does nothing.
Setting up different variables:
Button one,two,three,four,five,six,seven,eight,nine,zero,plus,minus,divide,multiply,dot,equals;
ImageButton clear;
TextView result;
String theresult;

All buttons except equals just append respective text to variable result.
Here is code of only equal button(created just plus to test, but failed):
    equals = (Button) findViewById(R.id.equals);
    equals.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            String expression = String.valueOf(result);

            if(expression.contains("+")){
            String[] numbers = expression.split("\\+");
            String no1 = numbers[0];
            String no2 = numbers[1];

            Double numb1 = Double.valueOf(no1);
            Double numb2 = Double.valueOf(no2);
            Double added = numb1+numb2;

            theresult = String.valueOf(added);
            result.setText(theresult);

            }
        }
    });

I have used if here, so that I can use else if to make other operations work. Later on I will use Try-Catch block too. Thank you for your time!
Full code of MainActivity.java
package org.example.calc;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class MainActivity extends Activity {

Button one,two,three,four,five,six,seven,eight,nine,zero,plus,minus,divide,multiply,dot,equals;
ImageButton clear;
TextView result;
String theresult;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    result = (TextView) findViewById(R.id.result);

    one = (Button) findViewById(R.id.one);
    one.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("1");
        }
    });

    two = (Button) findViewById(R.id.two);
    two.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("2");
        }
    });

    three = (Button) findViewById(R.id.three);
    three.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("3");
        }
    });

    four = (Button) findViewById(R.id.four);
    four.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("4");
        }
    });

    five = (Button) findViewById(R.id.five);
    five.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("5");
        }
    });

    six = (Button) findViewById(R.id.six);
    six.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("6");
        }
    });

    seven = (Button) findViewById(R.id.seven);
    seven.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("7");
        }
    });

    eight = (Button) findViewById(R.id.eight);
    eight.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("8");
        }
    });

    nine = (Button) findViewById(R.id.nine);
    nine.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("9");
        }
    });

    zero = (Button) findViewById(R.id.zero);
    zero.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("0");
        }
    });

    dot = (Button) findViewById(R.id.dot);
    dot.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append(".");
        }
    });

    clear = (ImageButton) findViewById(R.id.clear);
    clear.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.setText("");
        }
    });

    plus = (Button) findViewById(R.id.plus);
    plus.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("+");
        }
    });

    minus = (Button) findViewById(R.id.minus);
    minus.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("-");
        }
    });

    divide = (Button) findViewById(R.id.divide);
    divide.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("/");
        }
    });

    multiply = (Button) findViewById(R.id.multiply);
    multiply.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            result.append("x");
        }
    });

    equals = (Button) findViewById(R.id.equals);
    equals.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            result.getText();
            String expression = String.valueOf(result);

            if(expression.contains("+")){
            String[] numbers = expression.split("\\+");
            String no1 = numbers[0];
            String no2 = numbers[1];

            Double numb1 = Double.valueOf(no1);
            Double numb2 = Double.valueOf(no2);
            Double added = numb1+numb2;

            theresult = String.valueOf(added);
            result.setText(theresult);

            }
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

A:

Just do thus:
@Override
public void onClick(View v) {
    String expression = result.getText().toString();
    // Log.d("LOG", expression);

    if(expression.contains("+")){
        (...)

Maybe work. No need of using String.valueOf()


Q:

SQL Server 2005 Browser Service

I've been doing a little work with SQL Server and C# and every time I run the darn thing the connection times out unless I start services.msc and manually restart the service (SQL Browser Service). It's already set to automatic, does anyone know why it would do this? I'm not an advanced programmer, more of an intermediate one. Once I do restart this service it works fine as long as I keep using it. If I stop using it for more than 30 minutes I have to restart it again.

A:

Have you checked the SQl Server Log and the windows event log?
Can you supply some more info., such as the C# code you are using to open/close the connection, the connection string etc.


Q:

JQuery on click event on Href

I am appending data dynamically to my table as:
function myFunctionEdit()
{

var table = document.getElementById("nomiTable");
var len = table.rows.length;
var row = table.insertRow(len);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);

cell1.innerHTML = len;
cell2.innerHTML = name;
cell3.innerHTML = dob;
cell4.innerHTML = relation;
cell5.innerHTML = share;
cell6.innerHTML = "";

$('#editNomiModal').modal('hide');
return false;
}

My table structure is:

..

..Dynamically generated columns...

JQuery Function on #editNominHref click:
$("#editNominHref").on('click', function(e)
{
alert($(this).closest('tr').index());
});

Problem:
The method does not work on dynamically generated Edit Hrefs. Any help would be highly appreciated.

A:

Use event delegation for same.
$(document).on('click', '#editNominHref', function(e)
{
    alert($(this).closest('tr').index());
});


Q:

Twisted + Gtk - shutdown not working properly

Using Python 2.6, Twisted 10.1, and GTK+ 2.22, with latest pygtk installed, I'm having problems on shutdown. When I close my application and shut down the reactor (using the gtk2reactor of course), the application simply freezes.
I've poked around the twisted source and added debug messages. What ends up happening is, the 'shutdown' event fires, PortableGtkReactor.crash is called, which calls gtk.main_quit. The event gets processed at the end of ReactorBase.runUntilCurrent. When the function returns, control goes to ReactorBase.iterate, which returns control to PortableGtkReactor.simulate, which goes back to... the gtk.main() call. It looks like gtk just doesn't quit.
Unfortunately, when I put together a very simple example with twisted and the gtk "Hello World" sample, everything shut down correctly. It must be something my application is doing. Until I can figure it out further, though...
What might be causing this? Like what could an app do that causes gtk to not quit? The app worked fine on Gtk 2.12, with Python 2.5 and Twisted 8.1, if that helps at all.

A:

As from this question it seems to come from importing the win32ui module. But I think the underlying problem is deeper..
EDIT: Seems to be a problem with my particular install of Windows 7 and whatever else is here.


Q:

how to handle messages after splitting (even if there will be errors) in Spring Integration?

I have an application powered by Spring Integration.
in a nutshell the scheme is:
                                             |-> activator
gateWay -> splitter -> transformer -> router |-> ...
                                             |-> activator

For example, service get some json array, split it to json objects, then transforms them to some java object. While transforming it can throw some validation errors.
Spring Integration Reference says:

A Splitter is another type of Message Endpoint whose responsibility is
  to accept a Message from its input channel, split that Message into
  multiple Messages, and then send each of those to its output channel.

So I expect, that if I send an json array with one invalid object, which throw validation error, all other messages will be handled normally, and only one invalid object will be pushed to error channel. But it is not.
When the first validation exception thrown, all other messages are not handled.
for example:
["correct", "correct", "invalid"] --> 2 messages will be handled, it's ok.
["invalid", "correct", "correct"] --> 0 messages will be handled.
So how to handle messages after splitting, even if there will be errors?
Thanks

A:

Well, that's really not splitter component responsibility to handle downstream errors. It is a mix of responsibility and won't fit to the EIP model.
The same happens when you have a pure Java loop. Right, you can use there try...catch inside the loop, but that doesn't look pretty from the design perspective. So, you decide to move processing logic to the separate method and use that try...catch there. You have just divided a responsibility.
The same we can do, actually, we the splitter and its downstream subscriber for output item. it can be achieved with the ExpressionEvaluatingRequestHandlerAdvice and its onFailureExpression, failureChannel and trapException = true options.
This advice you should use for your transformer definition.
See more information in the Reference Manual. Also there is some clues in the Sample application.


Q:

How to solve $x^{-2} + x^{-3} = \dfrac{x^3 + x^2}{4x^6}$?

For online school I was given the equation $$x^{-2} + x^{-3} = \frac{x^3 + x^2}{4x^6}.$$ The problem lies in the addition of the bases, as I do not know how to solve that. Could you help me?

A:

We have that
$$x^{-2} + x^{-3} = \dfrac{x^3 + x^2}{4x^6}$$
$$x^4+x^3=\frac{1}{4}(x^3+x^2)$$
$$x^4+\frac34 x^3-\frac14 x^2=0$$
$$x^2(4x^2+3x-1)=0$$
However, since $x=0$ is not a solution (it is in the denominator of the original equation), we can divide out by $x$ to get
$$4x^2+3x-1=0$$
This is a simple quadratic equation, can you take it from here?


Q:

why if I insert 1,2,2 as input the result will be 0 instead of one

cin >> a >> b >> n;
int ans=0;
c=max(a,b);
d=min(a,b);
while(n>c)
    if(d+c>n) {
    ans++;
    break;
}
cout << ans;
}

why if I insert 1,2,2 as input the result will be 0 instead of one

A:

If you had a debugger that you could step through the code with, the mistake would have been easy to find.
When you get to the while loop, a = 1, b = 2, n = 2, c = 2, d = 1 and ans = 0.
Since the condition n > c is false (because !(2 > 2)) the body does not get executed and you get what you started with.


Q:

Python/Pandas -- convert day and hour columns into index of hour

I have a Data Frame that looks like this:
df
         Date    Hr    CO2_resp
0      5/1/02   600    0.000889
1      5/2/02   600    0.000984
2      5/4/02   900    0.000912

How would I go about creating a column Ind that represents a number index of hours elapsed since midnight 5/1/02? Such that the column would read
df
         Date    Hr   Ind      CO2_resp
0      5/1/02   600     6      0.000889
1      5/2/02   600    30      0.000984
2      5/4/02   800    80      0.000912

Thanks.

A:

You can use to_datetime with to_timedelta. Then convert timedelta to hours by np.timedelta64(1, 'h') and last if type of output is always int, cast by astype:
#convert column Date to datetime
df['Date'] = pd.to_datetime(df.Date)

df['Ind'] = ((df.Date
              - pd.to_datetime('2002-05-01')
              + pd.to_timedelta(df.Hr / 100, unit='h')) / np.timedelta64(1, 'h')).astype(int)
print (df)
        Date   Hr  CO2_resp  ind
0 2002-05-01  600  0.000889    6
1 2002-05-02  600  0.000984   30
2 2002-05-04  900  0.000912   81

If not dividing by 100 column Hr, output is different:
df['Ind'] = ((df.Date
              - pd.to_datetime('2002-05-01')
              + pd.to_timedelta(df.Hr,unit='h')) / np.timedelta64(1, 'h')).astype(int)
print (df)
        Date   Hr  CO2_resp  Ind
0 2002-05-01  600  0.000889  600
1 2002-05-02  600  0.000984  624
2 2002-05-04  900  0.000912  972