Q:

Magento 1.6 - Cannot initialize the indexer process

I'm having problems reindexing the data in magento 1.6 through the admin panel. I just get a message saying
Cannot initialize the indexer process

and the products aren't displaying in the categories on the front end which is obviously a massive problem for the site.
I have tried running the process via shell but it throws the following error:
Category Products index process unknown error:
exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint  violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`strailco_firstclass`.`catalog_category_product_index`, CONSTRAINT `FK_CAT_CTGR_PRD_IDX_CTGR_ID_CAT_CTGR_ENTT_ENTT_ID` FOREIGN KEY (`category_id`) REFERENCES `catalog_category_entity` (`entity)' in /home/strailco/1stclassholidays.com/html/lib/Zend/Db/Statement/Pdo.php:228
Stack trace:
#0 /home/strailco/1stclassholidays.com/html/lib/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array)
#1 /home/strailco/1stclassholidays.com/html/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#2 /home/strailco/1stclassholidays.com/html/lib/Zend/Db/Statement.php(300): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#3 /home/strailco/1stclassholidays.com/html/lib/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)
#4 /home/strailco/1stclassholidays.com/html/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('INSERT INTO `ca...', Array)
#5 /home/strailco/1stclassholidays.com/html/lib/Varien/Db/Adapter/Pdo/Mysql.php(389): Zend_Db_Adapter_Pdo_Abstract->query('INSERT INTO `ca...', Array)
#6 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Resource/Abstract.php(176): Varien_Db_Adapter_Pdo_Mysql->query('INSERT INTO `ca...')
#7 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Resource/Helper/Mysql4.php(48): Mage_Index_Model_Resource_Abstract->insertFromSelect(Object(Varien_Db_Select), 'catalog_categor...', Array, false)
#8 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Resource/Abstract.php(147): Mage_Index_Model_Resource_Helper_Mysql4->insertData(Object(Mage_Catalog_Model_Resource_Category_Indexer_Product), Object(Varien_Db_Select), 'catalog_categor...', Array, false)
#9 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Resource/Abstract.php(111): Mage_Index_Model_Resource_Abstract->insertFromTable('catalog_categor...', 'catalog_categor...', false)
#10 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Catalog/Model/Resource/Category/Indexer/Product.php(929): Mage_Index_Model_Resource_Abstract->syncData()
#11 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Indexer/Abstract.php(132): Mage_Catalog_Model_Resource_Category_Indexer_Product->reindexAll()
#12 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Process.php(166): Mage_Index_Model_Indexer_Abstract->reindexAll()
#13 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Process.php(194): Mage_Index_Model_Process->reindexAll()
#14 /home/strailco/1stclassholidays.com/html/shell/indexer.php(158): Mage_Index_Model_Process->reindexEverything()
#15 /home/strailco/1stclassholidays.com/html/shell/indexer.php(198): Mage_Shell_Compiler->run()
#16 {main}

Next exception 'Zend_Db_Statement_Exception' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`strailco_firstclass`.`catalog_category_product_index`, CONSTRAINT `FK_CAT_CTGR_PRD_IDX_CTGR_ID_CAT_CTGR_ENTT_ENTT_ID` FOREIGN KEY (`category_id`) REFERENCES `catalog_category_entity` (`entity)' in /home/strailco/1stclassholidays.com/html/lib/Zend/Db/Statement/Pdo.php:234
Stack trace:
#0 /home/strailco/1stclassholidays.com/html/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#1 /home/strailco/1stclassholidays.com/html/lib/Zend/Db/Statement.php(300): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#2 /home/strailco/1stclassholidays.com/html/lib/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)
#3 /home/strailco/1stclassholidays.com/html/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('INSERT INTO `ca...', Array)
#4 /home/strailco/1stclassholidays.com/html/lib/Varien/Db/Adapter/Pdo/Mysql.php(389): Zend_Db_Adapter_Pdo_Abstract->query('INSERT INTO `ca...', Array)
#5 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Resource/Abstract.php(176): Varien_Db_Adapter_Pdo_Mysql->query('INSERT INTO `ca...')
#6 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Resource/Helper/Mysql4.php(48): Mage_Index_Model_Resource_Abstract->insertFromSelect(Object(Varien_Db_Select), 'catalog_categor...', Array, false)
#7 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Resource/Abstract.php(147): Mage_Index_Model_Resource_Helper_Mysql4->insertData(Object(Mage_Catalog_Model_Resource_Category_Indexer_Product), Object(Varien_Db_Select), 'catalog_categor...', Array, false)
#8 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Resource/Abstract.php(111): Mage_Index_Model_Resource_Abstract->insertFromTable('catalog_categor...', 'catalog_categor...', false)
#9 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Catalog/Model/Resource/Category/Indexer/Product.php(929): Mage_Index_Model_Resource_Abstract->syncData()
#10 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Indexer/Abstract.php(132): Mage_Catalog_Model_Resource_Category_Indexer_Product->reindexAll()
#11 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Process.php(166): Mage_Index_Model_Indexer_Abstract->reindexAll()
#12 /home/strailco/1stclassholidays.com/html/app/code/core/Mage/Index/Model/Process.php(194): Mage_Index_Model_Process->reindexAll()
#13 /home/strailco/1stclassholidays.com/html/shell/indexer.php(158): Mage_Index_Model_Process->reindexEverything()
#14 /home/strailco/1stclassholidays.com/html/shell/indexer.php(198): Mage_Shell_Compiler->run()
#15 {main}

I have tried deleting the lock files with no success.
Does anyone have ant idea what the problem might be as I'm stuck and need it resolving asap
Many Thanks in advance

A:

Follow this chain of information and you may find an answer.


Q:

lubuntu won't display on both monitors at the same time

I can get Lubuntu 13.10 to display my desktop on either screen, but it refuses to display on both  at the same time. Changing the resolution of a screen generally toggles which screen is displayed; using arandr does not solve the issue. My graphics card is a Radeon HD6380G; I've had ubuntu 12.04 working on this before so I'm absolutely stumped
edit:
I actually got this to work using the proprietary drivers, which is the opposite of what most guides say:
sudo apt-get install figlrx
sudo aticonfig --initial
sudo reboot now

monitors work fine now

A:

I actually got this to work using the proprietary drivers
sudo apt-get install figlrx
sudo aticonfig --initial
sudo reboot now

monitors work fine now


Q:

What does single dash mean in curl command?

curl commands like:
Continue downloading a document:
    curl -C - -o file ftp://ftp.server.com/path/file

Continue uploading a document(*1):
    curl -C - -T file ftp://ftp.server.com/path/file

I mean "-" between "-C" and "-o/-T".

A:

That is part of the -C option. From the curl man page:

Use "-C -" to tell curl to automatically find out where/how to resume the transfer. It then uses the given output/input files to figure that  out.


Q:

Menu Items are not getting displayed

I implemented WL.OptionsMenu in android environment as specified in Worklight APIs(android/js/mainApp.js). If menu option is clicked, I've given a callback function . Its working fine if the callback resides in the same file. But the implementation of that callback is resided in android/native/common/js/mainApp.js file. Hence, its not showing the menuOptions in android mobile. How to solve this problem?

A:

Edit your question with the contents of mainApp.js
There is no such path, in Worklight, as android/native/common/js/mainApp.js.
Perhaps you mean android/native/assets/www/default/common/js/mainApp.js, but then again, it is  exactly the same as android/js/mainApp.js.
The only difference is that android/native/assets/www/default/common/js/mainApp.js is created after you build your application.
There is no reason why it should not work.
Again, edit your question with the contents of mainApp.js and the steps you have taken from creating the project, to running it in your device/emulator.


Q:

Creating java parser for json string

I'm trying to translate a java method that uses Xpath to parse XML to one that uses JsonPath instead and I'm having trouble translating what the Xpath parser is doing so i can replicate it using JsonPath.
Here is the code that currently parses "String body".
public static String parseXMLBody(String body, String searchToken) {
    String xPathExpression;
    try {
            // we use xPath to parse the XML formatted response body
        xPathExpression = String.format("//*[1]/*[local-name()='%s']", searchToken);
        XPath xPath = XPathFactory.newInstance().newXPath();
        return (xPath.evaluate(xPathExpression, new InputSource(new StringReader(body))));
    } catch (Exception e) {
            throw new RuntimeException(e); // simple exception handling, please review it
    }
}

Can anyone help translate this into a method that uses JsonPath or something similar?
Thanks

A:

I can explain the XPath for you
//*[1] selects the first element node in the document. This would be the document element and here can be only one so it is a little strange. /* returns the same node.
//*[1]/* or /*/* return all element child nodes of the document element.
[local-name()='tagname'] filters nodes by their local name (the tag name without the namespace prefix).
The full expression //*[1]/*[local-name()='tagname'] fetches all direct child nodes of the document element with the provided tagname, ignoring namespaces. It could be simplified to /*/*[local-name()='tagname'].
Without knowing the Json, here is no chance to say how the JsonPath should look like. I would not expect the Json to have a root element, but I expect the items to be different because in Json you can not have multiple siblings with the same key (You can have multiple siblings with the same node name in XML).


Q:

Suppose $S$ is bounded star shaped subset of $ \mathbb R^n$ where $n \ge 2$ then $ \partial S$ is path connected

Def: A set $S$ in the Euclidean space $ \mathbb R^n $ is called a star shaped domain if there exists $x_o$ in $S$ such that for all $x$ in $S$ the line segment from $x_0$ to $x$ is in $S$.
Some days ago in a comment in the answer to one of my questions @Hagen Von Eitzen commented that

Suppose $S$ is bounded  star shaped subset of $ \mathbb R^n$ where $n \ge 2$ then $ \partial S$ is Path connected.

I am unable to prove this result. Please help!

A:

Here's another example. Let $(r,\phi)$ be the polar coordinates in $\mathbb R^2$. Define $S$ as the closure of $$\left\{(r,\phi)\mid r\leq2+\sin\frac{30}{\phi(2\pi-\phi)}\right\},$$ where we only allow $r\geq 0$ and $\phi\in(0,2\pi)$. See here for a picture.
This is star shaped pretty much by definition (since for each $\phi$ it contains all the points of at most a certain distance from the origin) and its boundary is a variant of the Warsaw circle and is not path connected.

A:

It seems that this is not true.
For example, consider the following subset in $\mathbb R^2$.
For each $n\in \mathbb N$ consider the points $p_n = (\frac 1n, 1)$ and $p_{n+1}=(\frac{1}{n+1}, 1)$. Then consider the closed polygon $U_n$ formed by the vertices
$$O=(0,0), p_{n+1}, q_n = \left(\frac{2n+1}{4n(n+1)}, \frac 12\right), p_n$$
Note that this is a star convex set, with the center $(0, 0)$. (The third point is chosen this way: Let $D$ be the midpoint of $p_n, p_{n+1}$. Then the line $OD$ will hit $y=\frac{1}{2}$ at one point, which is $q_n $).
Now let
$$U_1 = \overline{\bigcup_n U_n} = \bigcup_n U_n \cup \{(0,y): 0\le y\le 1\},$$  and let
$$U = \{(x, y): (|x|, |y|)\in U_1\}\cup\{(x, y): |y|\le |x|\le 1\}$$
Then $U$ is a closed star convex set with center $(0,0)$, but the boundary is not path connected (only connected). The reason is that the boundary contains the segment $\{(0, y): \frac 12\le |y|\le 1\}$ and the boundary on both sides converges to these two segments as in the case of topological sine curve.


Q:

Solve the System of Equations in Real $x$,$y$ and $z$

Solve for $x$,$y$ and $z$ $\in $ $\mathbb{R}$ if
$$\begin{align} x^2+x-1=y \\
                   y^2+y-1=z\\
z^2+z-1=x \end{align}$$
My Try:
if  $x=y=z$ then the two triplets $(1,1,1)$ and $(-1,-1,-1)$ are the Solutions.
if $x \ne y \ne z$ Then we have
$$\begin{align} x(x+1)=y+1 \\
                   y(y+1)=z+1\\
z(z+1)=x+1 \end{align}$$
Multiplying all we get  $$xyz=1 \tag{1}$$ and adding all we get
$$x^2+y^2+z^2=3 \tag{2}$$
Now from Original Equations
$$\begin{align} x^2=y+1-x\\
                y^2=z+1-y\\
                z^2=x+1-z \end{align}$$ Multiplying all and Using $(1)$ we get
$$(y+1-x)(z+1-y)(x+1-z)=1 $$    $\implies$
$$xy+yz+zx-3=(x-y)(y-z)(z-x) \tag{3}$$ I am unable to proceed further..

A:

using the RMS GM inequality
$$\sqrt{\frac{x^2+y^2+z^2}{3}}\geq\sqrt[3]{xyz}$$
with equality if and only if $x=y=z$, plugging in your values for $xyz$ and$x^2+y^2+z^2$ we get that
$$\sqrt{\frac{3}{3}}\geq\sqrt[3]{1}$$
$$1=1$$
thus the only possible solutons are those you already stated.


Q:

How do I extract this json Array inside of an Array with Volley?

json ImageI'm trying to extract a list (Array) of data out of a Json Object but i don't I don't know to. it's the value of "ingredients" i'm trying to extract. I have trying to extract it as a string but it comes out un-formatted. I have also provide a image of the raw jsonenter code here. if I try to extract it as 'cake.optJSONArray' I get a java.lang.ClassCastException: org.json.JSONArray cannot be cast to java.util.List
I have added more code to help the question make sense (fingers crossed I didn't make it more confusing).
   try {

                for (int i = 0; i < response.length(); i++) {
                    JSONObject cake = response.getJSONObject(i);

                    String cakeId = cake.optString("id");
                    String cakeName = cake.optString("name");

                    List<Ingredients> ingredients = (List<Ingredients>) cake.optJSONArray("ingredients");

                    mCakeList.add(new CakesItem(cakeId,ingredients, cakeName));
                }

public class CakesItem {
private String mId;
private List<Ingredients> mIngredients;
private String mName;

public CakesItem(String cakeId, Lists <Ingrediets> ingredients String cakeName) {
    mId = cakeId;
    mIngredients = ingredients;
    mName = cakeName;

}

public class Ingredients implements Parcelable {
private double quantity;
private String measure, ingredient;

public Ingredients() {
}

A:

I'm not sure what JSON library you are using, but if you import org.json.JSONArray, then if your cake is a org.json.JSONObject that you got out of the JSONObject response returned from Volley, you would use this syntax:
JSONObject cake = response.getJSONObject(i);
JSONArray ingredients = cake.getJSONArray("ingredients");

Then, it is up to you to get the values out of the JSONArray ingredients into your List. It would look something like this:
for (int i = 0; i < response.length(); i++) {
    JSONObject cake = response.getJSONObject(i);

    String cakeId = cake.optString("id");
    String cakeName = cake.optString("name");

    JSONArray JSONingredients = cake.optJSONArray("ingredients");

    List<Ingredients> ingredients = new List<Ingredients>();

    for (int j = 0; j < JSONingredients.length(); j++) {
        JSONObject item = JSONingredients.getObject(j);

        String measure = item.getString(“measure”);
        String ingredient = item.getString(“ingredient”);
        Double quantity = item.getDouble(“quantity”);

        Ingredients item2 = new Ingredients(measure, ingredient, quantity);
        ingredients.add(item2);
      }

      mCakeList.add(new CakesItem(cakeId,ingredients, cakeName));
    }


Q:

Creating a web service in PHP

I would like to create a web service in PHP which can be consumed by different consumers (Web page, Android device, iOS device).
I come from a Microsoft background so am confortable in how I would do it in C# etc.  Ideally I would like to be able to provide a REST service which can send JSON.
Can you let me know how I can achieve this in PHP?
Thanks
Tariq

A:

I developed a class that is the PHP native SoapServer class' REST equivalent.
You just include the RestServer.php file and then use it as follows.
class Hello
{
  public static function sayHello($name)
  {
    return "Hello, " . $name;
  }
}

$rest = new RestServer(Hello);
$rest->handle();

Then you can make calls from another language like this:
http://myserver.com/path/to/api?method=sayHello&name=World

(Note that it doesn't matter what order the params are provided in the query string. Also, the param key names as well as the method name are case-insensitive.)
Get it here.


Q:

wishing a happy week

As a non-native English speaker, I have a question:
Can I write (and say) "Happy week everyone" to wish a good/happy week? Is there any more common English expression in everyday conversations?

A:

As a native English speaker, I have seen "have a good week" used commonly in both spoken and informal written communication.  I have not seen the expression "...happy week" used by native English speakers.

A:

There is nothing wrong saying "Happy week everyone", happy being an adjective and the week being a noun. But it will sound weird and out of the ordinary! something that the people are not used to hearing.
Being Native English speaker I would recommend saying "Have a good week(end) (ahead)" or just say "have a good one."
So, if you don't want to sound weird, don't use "happy week".


Q:

Display content by taxonomy term, including sub-terms

I'm looking at Drupal for the first time in a long time, with a view to using it in a project we're starting. This seems like a very simple question, but I'm struggling to find the answer.
If we have a taxonomy of website sections and associated sub-sections, like this:
News
    - Europe
    - America
    - etc
Products
    - Widgets
    - Doodahs
    - etc

If we have a menu linking to News it's easy to display content associated explicitly with that term, I'm not seeing how to include content associated with its sub-terms though. Is the conventional way of achieving this through...views?
Thanks,
Toby
Update: It looks like in previous versions of Drupal you could perhaps specify a term depth in your URLs. I guess this is what I'm after, but in Drupal 7

A:

From what I can see, Views is the way to do it, using a 'Filter criteria' of 'Content: Has taxonomy terms (with depth)'. If there's a simpler way do let me know.


Q:

Not getting error message in ajax() method jquery

Assume:
1).my login form have two field enrollment,password with one button called login(submit)
2). My backend script login.php is fine no error there
here is my code for sending data via login form and comparing it to backend,now the problem is when i provide right password and enrollment which are needed for login,the event successfully completed but when i provide the wrong credentials its not showing an error message as displayed in ajax() error:function().although the message is displayed for a while when i double click the login button and then page automatically gets refreshed.can anyone help me out to getting error message when wrong password is provided for enrollment
$(function(){
/*$('#err').hide();*/
$('.err').hide();
/*$('.error').hide();*/
$('#eno').blur(function(){
    var eno = $('input#eno').val();
    if(eno == ""){
        $('#err_eno').show();
        $('input#eno').focus();
        return false;
    }else{
        $('#err_eno').hide();
    }
});

$('#pw').blur(function(){
    var pw = $('input#pw').val();
    if(pw == ""){
        $('#err_pw').show();
        $('input#pw').focus();
        return false;
    }else{
        $('#err_pw').hide();
    }
});

$('#submit_btn').click(function(){

    var dataString = $('#log').serialize();
//alert (dataString);return false;
$.ajax({
            type:"POST",
            url:"script/login.php",
            data:dataString,
            success:function(){
                    window.location='profile.php';
            },
            error:function(){
                $('#err').html("
Provide right combination
");
            }
        });
return false;
});

});

A:

Well your Success function is always executed, Try with the following implementation:
$.ajax({
            type:"POST",
            url:"script/login.php",
            data:dataString,
            success:function(x){
            if (x == 1)
            {
        window.location='profile.php';
            }
            else
            {
        //Handle Error Here
                $('#err').html("
Provide right combination
");

            }
          }
        });

login.php
<?php

//execute code

//if success
 print "1";
//else
print "";
?>


Q:

How do I disambiguate associated types?

My current code looks like this:
pub trait A {}
pub trait HasA {
    type A: A;
    fn gimme_a() -> Self::A;
}

pub trait RichA: A {}
pub trait RichHasA: HasA {
    type A: RichA;
    fn gimme_a() -> Self::A;
    // ... more things go here ...
}

pub fn main() {}

My goal is to be able to use RichHasA as a HasA. The above code fails to compile with:
error[E0221]: ambiguous associated type `A` in bounds of `Self`
  --> src/main.rs:10:21
   |
3  |     type A: A;
   |     ---------- ambiguous `A` from `HasA`
...
9  |     type A: RichA;
   |     -------------- ambiguous `A` from `RichHasA`
10 |     fn gimme_a() -> Self::A;
   |                     ^^^^^^^ ambiguous associated type `A`

which makes sense. How can I  disambiguate associated types?

A:

You can use what is called Fully Qualified Syntax (FQS):
fn gimme_a() -> <Self as HasA>::A;
fn gimme_a() -> <Self as RichHasA>::A;

See also:

How to call a method when a trait and struct use the same method name?


Q:

C++ strings and set/get functions

Very new to C++. Could use some help with this assignment on classes.
The assignment requirement is:

Create a class called CourseList that includes one instance variables—
  nameOfCollege (type String). Provide a displayMessage member function
  to welcome the user to the CourseList program. Provide a set function that
  sets the name of the college, and a get function that retrieves the name of
  the college. The set function should have one string parameter for the
  name of the college. Use the function main() to demonstrate class Course’s
  capabilities.

To demonstrate our understanding of classes, we are to create classes, with objects, with functions. The end result is a console app to view fake classes offered at a fake college.
Currently, my get function is not returning the string with my fake college name. This is what I'm trying to resolve currently. I think my issue is with how I've written my functions or how my objects have been constructed.
Here is my code:
// DJ Homework
// welcome function [done]
// set function w/ college name in parameter [maybe done?]
// get function [not done]
// return string [not done]
// display class list  [not done]

#include <iostream>
#include <string> // program uses C++ standard string class
using namespace std;

// CourseList class definition
class CourseList
{
private:
    // string here
    string nameOfCollege;

public:
    void setCollegeName(string nameOfCollege);
    string getCollegeName();

    void CourseList::mysetCollegeName(string nameOfCollege)
    {
        nameOfCollege = "Smart Peoples University";
    }

    string CourseList::mygetCollegeName()
    {
        return string();
    }

    // function that displays a welcome message to the CourseList user
    void displayMessage(string nameOfCollege) const
    {
        cout << "Welcome to the CourseList Program\n\n\n" << "To see the classes offered at " << nameOfCollege << ",type something, then press 'Enter'.";
    } // end function displayMessage
}; // end class GradeBook

// function main begins program execution
int main()
{
    string CollegeName; // string of characters to store the college         name
    CourseList myWelcome; // create a CourseList object named myWelcome

    myWelcome.displayMessage(CollegeName);
} // end main

So that's my homework and attempt at accomplishing said tasks. Any help with my assignment, or with C++ in general, would be greatly appreciated.

A:

There are a number of issues in this code.

You have two pairs of get and set functions with different names; keep one only
Since you are defining your functions in the same class, you do not need CourseList:: before a function name
Your get function is returning an empty string, which is of no use; return nameOfCollege; will make more sense here
Inside your main() function, you are not initializing CollegeName so displayMessage() won't display any College Name


Q:

3-space viewer?

Is there a software package that would allow visulaizing/rendering some example structures in 3-space?  Specifically, I'm thinking of something that would provide a 3-D rendering of, say, 3-vectors (as an arrow), then vector addition (showing the arrows stacked up in addition), point lattices under a basis, convex sets, etc.  I imagine a black background with scaled back grid lines in three space, and objects rendered as 3-D objects of different colors.  You'd be able to navigate three space to spin, zoom, etc. and develop an intuitive feel for the objects in that space.  The UI would be math-savy--enter a matrix and click the "eigen-vector" or "span" radio button to add those to the plot; enter a parametric equation to define a convex set and have it show up;  Enter vector definitions and expressions and see the vectors plotted, along with results, in varying colors.
Basically, I'm trying to extend the capability to look at the 2-space examples we get in handouts to 3-space and allow building an intuitive concept of these structures in the highest dimensional space we can easily visualize.  This would be mostly a learning tool, but can be useful for some problem analysis (like looking at certain linear programming, for example).
The closest tools I can find are either 2-d graphers or generic 3-d rendering packages (that don't understand abstract mathematical objects).  Does anyone know of something in the middle?
(I now see this overlaps with this question, which is tightly focused on matrix operations.)

A:

GeoGebra (which came up in an ad for this question) actually seems to have some useful ability in this area.  Particularly, this example shows some 3-D vector ops:
http://www.geogebratube.org/student/m29087
While it seems to require some amount of scripting for the model, it's at least something.  It seems to have built-in semantics for points, lines, circles, triangles in 3-d geometry.  A more specific tool with better semantics (of vector spaces, other mathematical structures, etc.) would still be more useful.


Q:

how do i fetch articles from lightning knowledge on Salesforce using Native iOS Mobile SDK

In our native iOS app, I included the ServiceSDK using Cocoapods.
Referring to https://developer.salesforce.com/docs/atlas.en-us.noversion.service_sdk_ios.meta/service_sdk_ios/servicesdk_ios_dev_guide.htm
Now, I want to fetch articles from Salesforce. So, I want to use the KnowledgeManager class. But as a prequisite, I need to establish the SCSServiceConfiguration object. This requires a CommunityURL.
We do not use communities in our org.
So, I use the current user's login credentials as directed here: https://developer.salesforce.com/docs/atlas.en-us.noversion.service_sdk_ios.meta/service_sdk_ios/knowledge_authenticated_user.htm
Next step, I try to fetch the data categories as directed here: https://developer.salesforce.com/docs/atlas.en-us.noversion.service_sdk_ios.meta/service_sdk_ios/ios_cache_offline.htm
I have 2 errors in XCode:
[general] Community URL appears to be configured incorrectly.
    Please refer to the Service SDK Developer's Guide for more information on configuring your organization.
    https://developer.salesforce.com/docs/atlas.en-us.noversion.service_sdk_ios.meta/service_sdk_ios/error_community.htm

load failed with error Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL, NSErrorFailingURLStringKey=//test.salesforce.com/services/data/v44.0/support/dataCategoryGroups?sObjectName=KnowledgeArticleVersion&topCategoriesOnly=false, NSErrorFailingURLKey=//test.salesforce.com/services/data/v44.0/support/dataCategoryGroups?sObjectName=KnowledgeArticleVersion&topCategoriesOnly=false, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <E6B620D0-AC3F-4FDF-996D-317D17AB2DEE>.<2>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <E6B620D0-AC3F-4FDF-996D-317D17AB2DEE>.<2>, NSUnderlyingError=0x600000047a80 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}} [-1002]

Why would Salesforce make it mandatory to have Communities in order for us to access Knowledge from Mobile SDK?
Am i missing something? Is there a cleaner way to include and use the ServiceSDK?
**UPDATE: ** I was able to get the data categories as an authenticated user. Below is the code that worked:
In AppDelegate, didFinishLaunching API:
AuthHelper.loginIfRequired({
                    let identity: UserAccountIdentity = UserAccountManager.shared.currentUserAccountIdentity!
                    let account: UserAccount = UserAccountManager.shared.userAccount(for: identity)!
                    // Create auth settings object from SFUserAccount
                    self.scsAuthSettings = SCSAuthenticationSettings(mobileSDK: account)

                    //Set the Authentication Settings to the ServiceCloud object.
                    ServiceCloud.shared().setAuthenticationSettings(self.scsAuthSettings, forServiceType: SCServiceType.knowledge, completion: nil)
                })

However, I am still not able to fetch articles.
The code I have for fetching the articles is as below:
let km = KnowledgeManager.default
        let query = MutableArticleQuery()
        query.categories = categories
        query.queryMethod = .at
        query.pageSize = 2
        km.fetchArticles(with: query) { (articles, error) in
            if error != nil {
                print(error?.localizedDescription ?? "")
            }
            completion(articles)
        }

There is no error. But the articles always has 0 records.

A:

Communities need not be turned on for accessing knowledge articles as an authenticated user. It seems so because SCSServiceConfiguration object is necessary to complete the setup and to be able to access the content. The initializer for SCSServiceConfiguration requires 3 arguments, a communityURL, a dataCategoryGroup and a rootLevelCategory.
The dataCategoryGroup and rootLevelCategory are what determines the source for artciles. So if we do not have an SCSServiceConfiguration, the APIs dont know where to look for.
The challenge was, when we dont use communities in our org, what the communityURL should be.
The answer is apiURL of the user account.
Please see the response from the mobileSDK dev team here:
https://github.com/forcedotcom/ServiceSDK-iOS/issues/103.
For reference, please see the code i have used for authenticating using the logged in user's account and then creating the SCSServiceConfiguration:
AuthHelper.loginIfRequired({
                    let identity: UserAccountIdentity = UserAccountManager.shared.currentUserAccountIdentity!
                    let account: UserAccount = UserAccountManager.shared.userAccount(for: identity)!
                    // Create auth settings object from SFUserAccount
                    self.scsAuthSettings = SCSAuthenticationSettings(mobileSDK: account)

                    if let url = account.apiUrl {
                        let config = SCSServiceConfiguration(community: url, dataCategoryGroup: "Training_Content", rootDataCategory: "All")
                        ServiceCloud.shared().serviceConfiguration = config
                    }

                    //Set the Authentication Settings to the ServiceCloud object.
                    ServiceCloud.shared().setAuthenticationSettings(self.scsAuthSettings, forServiceType: SCServiceType.knowledge, completion: nil)
                })

Hope it helps!!


Q:

How do I get an RT3290 wireless card to work?

After updating to 16.04 my Wifi card does not work anymore. And I have no idea what to do.
lspci
04:00.0 Network controller: Ralink corp. RT3290 Wireless 802.11n 1T/1R PCIe

sudo lshw -C network
  *-network DISABLED
       description: Wireless interface
       product: RT3290 Wireless 802.11n 1T/1R PCIe
       vendor: Ralink corp.
       physical id: 0
       bus info: pci@0000:04:00.0
       logical name: wlo1
       version: 00
       serial: 70:18:8b:81:85:09
       width: 32 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=rt2800pci driverversion=4.4.0-21-generic firmware=0.37 latency=0 link=no multicast=yes wireless=IEEE 802.11bgn
       resources: irq:19 memory:d0610000-d061ffff
  *-network
       description: Ethernet interface
       product: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:05:00.0
       logical name: enp5s0
       version: 0c
       serial: a4:5d:36:c9:2b:c8
       size: 1Gbit/s
       capacity: 1Gbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix vpd bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=full firmware=rtl8168g-2_0.0.1 02/06/13 ip=192.168.100.6 latency=0 link=yes multicast=yes port=MII speed=1Gbit/s
       resources: irq:32 ioport:2000(size=256) memory:d0500000-d0500fff memory:d0400000-d0403fff

lsmod
Module                  Size  Used by
hp_wmi                 16384  0
sparse_keymap          16384  1 hp_wmi
snd_hda_codec_hdmi     53248  1
intel_rapl             20480  0
x86_pkg_temp_thermal    16384  0
intel_powerclamp       16384  0
coretemp               16384  0
kvm_intel             172032  0
arc4                   16384  2
kvm                   536576  1 kvm_intel
snd_hda_codec_idt      57344  1
snd_hda_codec_generic    77824  1 snd_hda_codec_idt
rt2800pci              16384  0
rt2800mmio             20480  1 rt2800pci
irqbypass              16384  1 kvm
rt2800lib              94208  2 rt2800pci,rt2800mmio
crct10dif_pclmul       16384  0
rt2x00pci              16384  1 rt2800pci
crc32_pclmul           16384  0
snd_hda_intel          36864  3
rt2x00mmio             16384  2 rt2800pci,rt2800mmio
snd_hda_codec         135168  4 snd_hda_codec_hdmi,snd_hda_codec_idt,snd_hda_codec_generic,snd_hda_intel
rt2x00lib              57344  5 rt2x00pci,rt2800lib,rt2800pci,rt2800mmio,rt2x00mmio
aesni_intel           167936  0
mac80211              737280  3 rt2x00lib,rt2x00pci,rt2800lib
aes_x86_64             20480  1 aesni_intel
uvcvideo               90112  0
lrw                    16384  1 aesni_intel
gf128mul               16384  1 lrw
snd_hda_core           73728  5 snd_hda_codec_hdmi,snd_hda_codec_idt,snd_hda_codec_generic,snd_hda_codec,snd_hda_intel
glue_helper            16384  1 aesni_intel
snd_hwdep              16384  1 snd_hda_codec
ablk_helper            16384  1 aesni_intel
cryptd                 20480  2 aesni_intel,ablk_helper
snd_pcm               106496  4 snd_hda_codec_hdmi,snd_hda_codec,snd_hda_intel,snd_hda_core
videobuf2_vmalloc      16384  1 uvcvideo
videobuf2_memops       16384  1 videobuf2_vmalloc
input_leds             16384  0
videobuf2_v4l2         28672  1 uvcvideo
videobuf2_core         36864  2 uvcvideo,videobuf2_v4l2
serio_raw              16384  0
snd_seq_midi           16384  0
v4l2_common            16384  1 videobuf2_v4l2
snd_seq_midi_event     16384  1 snd_seq_midi
videodev              176128  4 uvcvideo,v4l2_common,videobuf2_core,videobuf2_v4l2
snd_rawmidi            32768  1 snd_seq_midi
cfg80211              565248  2 mac80211,rt2x00lib
media                  24576  2 uvcvideo,videodev
snd_seq                69632  2 snd_seq_midi_event,snd_seq_midi
joydev                 20480  0
snd_seq_device         16384  3 snd_seq,snd_rawmidi,snd_seq_midi
snd_timer              32768  2 snd_pcm,snd_seq
lpc_ich                24576  0
rtsx_pci_ms            20480  0
eeprom_93cx6           16384  1 rt2800pci
memstick               20480  1 rtsx_pci_ms
crc_ccitt              16384  1 rt2800lib
snd                    81920  17 snd_hwdep,snd_timer,snd_hda_codec_hdmi,snd_hda_codec_idt,snd_pcm,snd_seq,snd_rawmidi,snd_hda_codec_generic,snd_hda_codec,snd_hda_intel,snd_seq_device
soundcore              16384  1 snd
mei_me                 36864  0
mei                    98304  1 mei_me
shpchp                 36864  0
8250_fintek            16384  0
hp_accel               28672  0
lis3lv02d              20480  1 hp_accel
input_polldev          16384  1 lis3lv02d
hp_wireless            16384  0
mac_hid                16384  0
parport_pc             32768  0
ppdev                  20480  0
lp                     20480  0
parport                49152  3 lp,ppdev,parport_pc
autofs4                40960  2
hid_generic            16384  0
usbhid                 49152  0
hid                   118784  3 hid_generic,usbhid
psmouse               126976  0
amdkfd                122880  1
amd_iommu_v2           20480  1 amdkfd
rtsx_pci_sdmmc         24576  0
radeon               1511424  1
i915                 1208320  4
ttm                    98304  1 radeon
i2c_algo_bit           16384  2 i915,radeon
drm_kms_helper        139264  2 i915,radeon
syscopyarea            16384  1 drm_kms_helper
sysfillrect            16384  1 drm_kms_helper
sysimgblt              16384  1 drm_kms_helper
fb_sys_fops            16384  1 drm_kms_helper
ahci                   36864  2
drm                   360448  9 ttm,i915,drm_kms_helper,radeon
r8169                  81920  0
libahci                32768  1 ahci
rtsx_pci               53248  2 rtsx_pci_ms,rtsx_pci_sdmmc
mii                    16384  1 r8169
wmi                    20480  1 hp_wmi
video                  40960  1 i915
fjes                   28672  0

dmesg
[   21.061887] ieee80211 phy0: rt2x00lib_request_firmware: Info - Loading firmware file 'rt3290.bin'
[   21.063536] ieee80211 phy0: rt2x00lib_request_firmware: Info - Firmware detected - version: 0.37
[   22.678723] ieee80211 phy0: rt2800_wait_wpdma_ready: Error - WPDMA TX/RX busy [0x00000068]
[   24.278717] ieee80211 phy0: rt2800_wait_wpdma_ready: Error - WPDMA TX/RX busy [0x00000068]
[   24.278728] ieee80211 phy0: rt2800pci_set_device_state: Error - Device failed to enter state 4 (-5)
[   51.499485] ieee80211 phy0: rt2800_wait_wpdma_ready: Error - WPDMA TX/RX busy [0x00000068]
[   53.099518] ieee80211 phy0: rt2800_wait_wpdma_ready: Error - WPDMA TX/RX busy [0x00000068]
[   53.099529] ieee80211 phy0: rt2800pci_set_device_state: Error - Device failed to enter state 4 (-5)

A:

I encountered the same problem on upgrading from 15.10 to 16.04. I managed to resolve the issue in my case by following the advice of others, specifically:

How to install wifi driver Ralink RT3290 and following second answer, steps 1 to 8 about halfway down the post
I do have to enable my wireless card by opening a terminal window and issuing these two commands:
sudo ifconfig eno1 up  and
sudo service network-manager restart

eno1 is the logical name for my wireless card (found in output of sudo lshw -C network command).
You can automate the two commands in step 2. by adding them to /etc/rc.local (see How can I make "rc.local" run on startup? can I make “rc.local” run on startup?])

A:

I had the the same problem with my RT3090 wireless card after upgrading my laptop from 14.04 to 16.04.
After some messing around, I discovered that the Wifi would only work after resuming from suspend.
I finally seem to have fixed the problem by adding the following to the file /etc/rc.local:
sudo ifconfig wlan0 up
sudo service network-manager restart

If your device is not "wlan0" you can substitute as required.


Q:

How do I go from a summation form to integral form of an expression?

How is the following inequality valid?
$$\sum\limits_{j = 1}^{N/2} \sum\limits_{n = j}^{\infty} \frac{1}{n^2} < \sum_{j = 1}^{N/2} \int_{j - 1/2}^{\infty} \frac{dx}{x^2}$$.
I came across this inequality in one of the references I'm using, and the author states the above is true because $1/x^2$ is a strictly convex function on $(0, \infty)$.

A:

Note that since $\dfrac{1}{x^2}$ is a decreasing function, $\int_{j-1}^j\frac{\mathrm{d}x}{x^2}>\frac{1}{j^2}$. Therefore,
$$
\int_{j-1}^\infty\frac{\mathrm{d}x}{x^2}>\sum_{n=j}^\infty\frac{1}{n^2}\tag{1}
$$
However to get the inequality cited in the question, we need to evaluate a bit more carefully:
$$
\begin{align}
\int_{j-1/2}^{j+1/2}\frac{\mathrm{d}x}{x^2}
&=\frac{1}{j-1/2}-\frac{1}{j+1/2}\\
&=\frac{1}{j^2-1/4}\\
&>\frac{1}{j^2}\tag{2}
\end{align}
$$
Summing $(2)$ yields
$$
\int_{j-1/2}^\infty\frac{\mathrm{d}x}{x^2}>\sum_{n=j}^\infty\frac{1}{n^2}\tag{3}
$$
Using the strict convexity of $\mathbf{\dfrac{1}{x^2}}$
We can prove $(3)$ using strict convexity. Since $x$ is not constant on the support of uniform measure ($\mathrm{d}x$) on $[j{-}\frac12,j{+}\frac12]$, Jensen's inequality yields
$$
\int_{j-1/2}^{j+1/2}\frac{\mathrm{d}x}{x^2}>\frac{1}{\left(\int_{j-1/2}^{j+1/2}x\,\mathrm{d}x\right)^2}=\frac{1}{j^2}
$$


Q:

Apache POI poi-ooxml:4.0.0 throws org.apache.poi.ooxml.POIXMLException

Context:
Trying to open XLSX file using Apache POI's poi & poi-ooxml 4.0.0 version jar's
Issue:
The program throws an error as shown below. I find this error when I use version 4.0.0, as I was able to open excel file using version 3.17 or earlier.
Hope the issue faced is clear & await inputs on how to fix this issue.
Note: Found some related queries but they relate to earlier versions of POI - Link1 Link2
Code:
public static void main(String[] args) {
        try {
            // Open Excel XLSX file
            FileInputStream fis = new FileInputStream(excelFile);
            ZipSecureFile.setMinInflateRatio(0);
            XSSFWorkbook workBook = new XSSFWorkbook(fis);
            System.out.println(workBook);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Gradle:
compile 'org.apache.poi:poi:4.0.0'
compile 'org.apache.poi:poi-ooxml:4.0.0'
//    Tried adding the below jar's as well but dint help
//    compile 'org.apache.commons:commons-collections4:4.2'
//    compile 'org.apache.poi:poi-ooxml-schemas:4.0.0'
//    compile 'org.apache.xmlbeans:xmlbeans:3.0.1'

Error:
org.apache.poi.ooxml.POIXMLException: org/apache/poi/POIXMLTypeLoader
    at org.apache.poi.ooxml.POIXMLFactory.createDocumentPart(POIXMLFactory.java:66)
    at org.apache.poi.ooxml.POIXMLDocumentPart.read(POIXMLDocumentPart.java:648)
    at org.apache.poi.ooxml.POIXMLDocument.load(POIXMLDocument.java:180)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:286)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:307)
    at main.Test.main(Test.java:32)
Caused by: java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:56)
    at org.apache.poi.ooxml.POIXMLFactory.createDocumentPart(POIXMLFactory.java:63)
    ... 5 more
Caused by: java.lang.NoClassDefFoundError: org/apache/poi/POIXMLTypeLoader
    at org.openxmlformats.schemas.drawingml.x2006.main.ThemeDocument$Factory.parse(Unknown Source)
    at org.apache.poi.xssf.model.ThemesTable.<init>(ThemesTable.java:86)
    ... 11 more
Caused by: java.lang.ClassNotFoundException: org.apache.poi.POIXMLTypeLoader
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 13 more

A:

i had the same issue trying to use poi 4.0.1.
Adding compile "org.apache.poi:ooxml-schemas:1.4" fixed the issue for me
all my dependencies:
compile "org.apache.poi:ooxml-schemas:1.4"
compile "org.apache.poi:poi:4.0.1"
compile "org.apache.poi:poi-ooxml:4.0.1"


Q:

Custom classloader loading a jar gives me an Illegal UTF8 string in constant pool in class file

I need to use custom ClassLoader to load 3rd party drivers. The plan is, that the drivers are simply shared jar archives but with a .dar suffix (driver archive). These archives are then simply added to the classpath while the jvm is ignoring this file extension and handling the dar files like resources (which means ignoring the class files inside).
Now my problem is, that my classloader gives me an Illegal UTF8 string in constant pool in class file exception. How could I get around that?
public class DriversClassLoader extends ClassLoader {

    public DriversClassLoader() {
        super(ClassLoader.getSystemClassLoader());
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        if( name.startsWith("java.")) {
            return super.loadClass(name, resolve);
        } else {
            // see if we have already loaded the class.
            Class<?> c = findLoadedClass(name);
            if (c != null) return c;

            try {
                URL driversUrl = super.getResource("drivers.dar").toURI().toURL();
                System.out.println(driversUrl);
                JarInputStream jis = new JarInputStream(driversUrl.openConnection().getInputStream());

                ZipEntry entry;
                while ((entry = jis.getNextEntry()) != null) {
                    if (entry.getName().matches(name)) {
                        System.out.println("loading: " + entry);
                        byte[] cBytes = new byte[(int) entry.getSize()];
                        jis.read(cBytes, 0, cBytes.length);

                        // this is where I get the exception
                        c = defineClass(name, cBytes, 0, cBytes.length);
                        if (resolve) resolveClass(c);
                        return c;
                    }
                }
            } catch (Exception e) {
                throw new ClassNotFoundException("loading of class " + name + " failed", e);
            }

            // else delegate to parent
            return super.loadClass(name, resolve);

            /*
            URL res = getResource(name);
            if (res == null) throw new ClassNotFoundException("Class " + name + "not found in:");

            try {
                byte[] cBytes = IOUtils.toByteArray(new InputStreamReader(res.openStream()));
                c = defineClass(name, cBytes, 0, cBytes.length);
                if (resolve) resolveClass(c);
                return c;
            } catch (Exception e) {
                throw new ClassNotFoundException("loading of class " + name + " failed", e);
            }

            // delegate to parent
            return super.loadClass(name, resolve);*/
        }
    }

    @Override
    public URL getResource(String name) {
        try {
            URL driversUrl = super.getResource("drivers.dar").toURI().toURL();
            System.out.println(driversUrl);
            JarInputStream jis = new JarInputStream(driversUrl.openConnection().getInputStream());

            ZipEntry entry;
            while ((entry = jis.getNextEntry()) != null) {

                if (entry.getName().matches(name)) {
                    System.out.println(entry);
                    return new URL("jar:" + driversUrl + "!/" + entry);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // delegate to parent
        return super.getResource(name);
    }

    @Override
    public Enumeration<URL> getResources(String name) throws IOException {
        //super.get
        return super.getResources(name);
    }
}

Then I simply to
Class<?> aClass = Class.forName("a.class", false, new DriverClassLoader());
System.out.println("aclass = " + aClass);

EDIT 1:
But the file contains valid classes:
java -cp ../rangeCache/src/main/resources/drivers.dar pkg.test.Test

Outputs Hello from dar jar
While this does not:
java -cp target/libs/range-cache-302-SNAPSHOT.jar:drivers/ com.data.cache.range.drivers.DriversClassLoader
jar:file:/home/rangeCache/target/libs/range-cache-302-SNAPSHOT.jar!/drivers.dar
loading: com/data/cache/range/drivers/DatastaxCassandraDriver.class
Exception in thread "main" java.lang.ClassFormatError: Illegal UTF8 string in constant pool in class file com/data/cache/range/drivers/DatastaxCassandraDriver/class
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
    at com.mindbusters.data.cache.range.drivers.DriversClassLoader.loadClass(DriversClassLoader.java:40)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.data.cache.range.drivers.DriversClassLoader.main(DriversClassLoader.java:105)

A:

Your code to read the bytes from the ZipEntry is broken.
You first should not rely on ZipEntry.getSize() since -1 may be returned if not known (see Javadocs).
Then InputStream.read(byte[], int , int) may read less bytes than requested.
You should read the bytes in a loop until -1 is returned or use IOUtils.toByteArray like you already did one time.


Q:

How to use query result as REPLACE parameters

i'm trying to:
1- Find a string inside a lot of content
2- Replace that specific part of the string with a new one using REPLACE function like this:
REPLACE(column_name, query#1, query#2)

Is this possible?
I already have located the exact part of the content that i want to replace
SELECT `post_title`, SUBSTRING(`post_content`, LOCATE('[flv:',`post_content`), LOCATE(']',`post_content`) - LOCATE('[flv:',`post_content`) + 1) AS amazonlinks FROM wp_posts_duplicatedfortestonly WHERE `post_content` LIKE '%[flv:%'

and have the new string ready in another table column: Png_Link
Finally i'm trying to merge all this using the REPLACE function but it's giving me a lot of errors:
UPDATE wp_posts_duplicatedfortestonly
SET
    post_content = REPLACE(post_content,
                           (SELECT SUBSTRING(`post_content`, LOCATE('[flv:',`post_content`), LOCATE(']',`post_content`) - LOCATE('[flv:',`post_content`) + 1) FROM (SELECT post_content FROM wp_posts_duplicatedfortestonly) AS something WHERE `post_content` LIKE '%[flv:%'),
                           (SELECT `Png_Link`  FROM `VideoPlayerUdpateLinksReady` WHERE `Mp4_Link` != ''));

Something like this (only difference is i'm using 2 tables): https://www.db-fiddle.com/f/91EW2kJDc8aWJYYvw86vG9/0
Also tried with variables without any luck:
SET @tblname := "wp_posts_duplicatedfortestonly";
SET @colname := "post_content";
SELECT @lookfor := SUBSTRING(`post_content`, LOCATE('[flv:',`post_content`), LOCATE(']',`post_content`) - LOCATE('[flv:',`post_content`) + 1) FROM @tblname WHERE `post_content` LIKE '%[flv:%';
SELECT @replacewith := `Png_Link` FROM `VideoPlayerUdpateLinksReady` WHERE `Mp4_Link` != '';

SET @qry = CONCAT('UPDATE ',@tblname, ' SET ', @colname, ' = REPLACE(' ,@colname, ',', @lookfor, ',',@replacewith,')');
PREPARE QUERY FROM @qry;
EXECUTE QUERY;

What am i'm doing wrong? Is it possible to use SELECT expressions as REPLACE function parameters or what other workaround do i have?

A:

Managed to solve it on my own rookie way:
1- Since i couldn't make the REPLACE function to accept a query as parameter i just inserted the query result in a new table column:
INSERT INTO VideoPlayerUdpate_FLV_links (`ID`,`PostTitle`,`AmazonLinks`) SELECT `ID`, `post_title`, SUBSTRING(`post_content`, LOCATE('[flv:',`post_content`), LOCATE(']',`post_content`) - LOCATE('[flv:',`post_content`) + 1) AS amazonlinks FROM wp_posts WHERE `post_content` LIKE '%[flv:%'

Remember I had another table VideoPlayerUdpateLinksReady with all my new string that i wanted to replace. I had to manually construct and validate all errors in this column VideoPlayerUdpateLinksReady.Png_Link so it would be ready to replace.
2- So final Step was only to use these 2 tables as parameters in the REPLACE function:
UPDATE `wp_posts_duplicatedfortestonly`  JOIN `VideoPlayerUdpate_FLV_links` ON wp_posts_duplicatedfortestonly.ID = VideoPlayerUdpate_FLV_links.ID  JOIN `VideoPlayerUdpateLinksReady` ON wp_posts_duplicatedfortestonly.ID = VideoPlayerUdpateLinksReady.ID SET `post_content` = REPLACE(`post_content`,VideoPlayerUdpate_FLV_links.AmazonLinks, VideoPlayerUdpateLinksReady.Png_Link)

And i got all my content replaced without any further issues.


Q:

Animating a missile in HTML5/WinJS

I'm writing a game using HTML5/WinJS on Windows 8.  I'm trying to produce the effect of a bullet or missile firing at something; however, I can't seem to get the object to go through another image in the background without trailing a border.  My working theory is that the border I'm seeing is caused by using clearRect.  Here's my code:
var moveBullet = function(missile) {

    if (missile.Image == undefined || missile.Image == null) {
        var image = new Image();
        image.src = "/images/missileImg.png";
        image.onload = function () {
            canvasContext.clearRect(missile.PointX - (image.width / 2), missile.PointY, image.width, image.height);
            missile.PointY += BULLET_SPEED;
            canvasContext.drawImage(image, missile.PointX - (image.width / 2), missile.PointY);
        };
    } else {
        canvasContext.clearRect(missile.PointX - (missile.Image.width / 2), missile.PointY, missile.Image.width, missile.Image.height);
        missile.PointY += BULLET_SPEED;
        canvasContext.drawImage(missile.Image, missile.PointX - (missile.Image.width / 2), missile.PointY);
    }
}

Is there a way to achieve this effect without using clearRect, or a more efficient way of restoring the background as it moves past?

A:

Make your clearRect area a few pixels larger than the missile image. Drawing on a canvas in general has some built-in anti-aliasing. This means that if you draw a line with one color, then draw the same line with the background color, you'll not remove the original line. Something similar might be happening here, in which case a few extra pixels should help.
That said, there's a caveat to be aware of here.
First, I assume the background is separate element from the canvas? It looks like it as you're not redrawing that part on the canvas itself.
The reason I ask is that making repeated calls to clearRect on the same canvas will eventually show performance problems. What happens is that every call to clearRect accumulates into a complex region within the canvas--essentially its transparency mask. So every time the canvas has to be rendered, which happens any time you change it, it has to process that transparent area. Gradually, as you leave more and more small clearRect trails across the canvas, this region will become more and more complex and performance will drop.
I did this experiment with the Blizzard demo on the IE Test Drive site once, where I wondered why the demo was clearing the entire canvas with every animation frame. So I tried just clearing the trail behind each snowflake (and made each one a little bigger as I suggest above, because I had trails). Seemed like the right thing to do, but the performance plummeted by several orders of magnitude. Asking around within the IE team, they confirmed the region behavior I describe.
So the best thing to do, actually, is to do a clearRect on the entire canvas with every frame, then redraw the missile and any other bits that you're animating. This may seem counter intuitive, but ends up working best and avoids all these glitches with pixel trails.


Q:

How to catch exceptions in the Mule foreach scope but keep the process going?

I am new to Mule ESB. I have created a simple flow that loops through a list of orders and calls the Magento API to update the order statuses one by one. My problem is that if there are any exception occurs in the foreach scope, the whole process tops. I tried to use the Exception Strategy to capture the exception and it did capture the exception. But how to resume the process? I didn't find much info with google search. Maybe I was doing something wrong with the flow. How do we normally handle this in Mule?
Here is my flow in xml.
    <flow name="Update_Magento_Order_Status_AU" doc:name="Update_Magento_Order_Status_AU" initialState="started">
    <poll doc:name="Poll">
        <fixed-frequency-scheduler frequency="10" timeUnit="MINUTES"/>
        <jdbc-ee:outbound-endpoint exchange-pattern="request-response" queryKey="GET_ORDERS_BY_STATUS_QUERY" queryTimeout="-1" connector-ref="DSEDatabase" doc:name="Get Orders By Status"/>
    </poll>
    <flow-ref name="ProcessOrderStastusUpdate" doc:name="Process Order Status Update"/>
</flow>
<flow name="ProcessOrderStastusUpdate" doc:name="ProcessOrderStastusUpdate">
    <foreach collection="#[payload]" doc:name="For Each">
        <component doc:name="Set Magento Order Status for Update">
            <singleton-object class="com.dse.esb.component.OrderStatusMapperComp">
                <property key="as400OrderStatuses" value="${as400.orderstatuses}"/>
                <property key="magentoOrderStatuses" value="${magento.orderStatuses}"/>
            </singleton-object>
        </component>
        <logger message="About to update Magento Order Status" level="INFO" doc:name="Logger"/>
        <magento:add-order-comment config-ref="Magento" comment="Updated by Mule ESB with AS400 order status: #[payload.TRNSTS]" orderId="#[payload.EPGORDNBR]" status="#[flowVars['magentoOrderStatus']]" doc:name="Update Magento Order Status"/>
    </foreach>
    <choice-exception-strategy doc:name="Choice Exception Strategy">
        <catch-exception-strategy doc:name="default">
            <logger message="Handle default exception" level="INFO" category="==============>>>>>>>>>>>>" doc:name="Logger"/>
        </catch-exception-strategy>
    </choice-exception-strategy>
</flow>

A:

Use a private flow for the content of the for-each with its own exception strategy. THe exception will be handled in the private flow and the parent flow should be able to continue. Something like:
<flow name="ProcessOrderStastusUpdate">
   <foreach collection="#[payload]" doc:name="For Each">
      <flow-ref name="privateFlow" />
   </foreach>
</flow>

<flow name="privateFlow">
   <component doc:name="Set Magento Order Status for Update">
      <singleton-object class="com.dse.esb.component.OrderStatusMapperComp">
             <property key="as400OrderStatuses" value="${as400.orderstatuses}"/>
             <property key="magentoOrderStatuses" value="${magento.orderStatuses}"/>
      </singleton-object>
   </component>
   <logger message="About to update Magento Order Status" level="INFO" doc:name="Logger"/>
   <magento:add-order-comment config-ref="Magento" comment="Updated by Mule ESB with AS400 order status: #[payload.TRNSTS]" orderId="#[payload.EPGORDNBR]" status="#[flowVars['magentoOrderStatus']]" doc:name="Update Magento Order Status"/>

    <choice-exception-strategy doc:name="Choice Exception Strategy">
        <catch-exception-strategy doc:name="default">
            <logger message="Handle default exception" level="INFO" category="==============>>>>>>>>>>>>" doc:name="Logger"/>
        </catch-exception-strategy>
    </choice-exception-strategy>
</flow>


Q:

PIL install with jpeg

I install  PIL1.2 with python2.7 on linux mint 64.
I have run python setup.py build_ext -i. And I got following infomations.
running build_ext
--------------------------------------------------------------------
PIL 1.2a0 SETUP SUMMARY
--------------------------------------------------------------------
version       1.2a0
platform      Python 2.7.3 (default, Apr 10 2013, 05:13:16)
              [GCC 4.7.2] on linux2
--------------------------------------------------------------------
*** TKINTER support not available (Tcl/Tk 8.5 libraries needed)
--- JPEG support available
*** WEBP support not available
--- ZLIB (PNG/ZIP) support available
--- FREETYPE2 support available
--- LITTLECMS support available
--------------------------------------------------------------------
To add a missing option, make sure you have the required
library, and set the corresponding ROOT variable in the
setup.py script.

To check the build, run the selftest.py script.

*But when i ran python selftest.py. I got jpg error *
'--------------------------------------------------------------------
PIL 1.2a0 TEST SUMMARY
--------------------------------------------------------------------
Python modules loaded from ./PIL
Binary modules loaded from ./PIL
--------------------------------------------------------------------
--- PIL CORE support ok
*** TKINTER support not installed
*** JPEG support not installed
*** WEBP support not installed
*** ZLIB (PNG/ZIP) support not installed
--- FREETYPE2 support ok
--- LITTLECMS support ok
--------------------------------------------------------------------
Running selftest:
**********************************************************************
File "./selftest.py", line 50, in selftest.testimage
Failed example:
    try:
     _info(Image.open(os.path.join(ROOT, "Images/lena.jpg")))
    except IOError:
     pass
Expected:
    ('JPEG', 'RGB', (128, 128))
Got nothing
**********************************************************************
1 items had failures:
   1 of  58 in selftest.testimage
***Test Failed*** 1 failures.
*** 1 tests of 58 failed.

Why can't it pass the test
By the way PIL1.7.1 can work on my computer. But I I can't convert YcbCr to numpy.array. And They said version1.2 had fixed this bug

A:

I have solved this issue by
aptitude search  python_pip
pip uninstall PIL
pip install pillow


Q:

Gerar uma profissão aleatória para os Jogadores Online

Eu estou a criar um pequeno jogo (Android) para jogar eu mais uns amigos meus. O jogo chama-se "Polícias e Ladrões". Pelo menos é necessário ter 4 jogadores em que um deles será o POLÍCIA, outro será o CRIMINOSO, outro será a DAMA e os restantes serão CIVÍS (Pessoas Normais).
Eu atualmente tou a usar o Socket.IO para fazer a ligação entre os jogadores e a comunicação. Mas na altura de dar uma profissão para cada jogador, deparei-me com um problema. Esta é a parte do código em que ele cria e envia para o jogador a sua profissão:
    var PoliceAlready,CriminalAlready,DamaAlready = false;
    for(var SI in clients) {
        var socket = clients[SI];
        var profissaoT;

        if(!PoliceAlready){
                profissaoT="POLÍCIA";
                PoliceAlready = true;
        }else if(!CriminalAlready){
                profissaoT="CRIMINOSO";
                CriminalAlready = true;
        }else if(!DamaAlready){
                profissaoT="DAMA";
                DamaAlready = true;
        }else{
                profissaoT="CIVÍL";
        }
        socket.emit('profissao', profissaoT);
 }

Mas obrigatoriamente terá que ter um Polícia, Criminoso e Dama e estes não se podem repetir. Apartir do código acima ele irá fazer isso mesmo, porém a função for() vai executando os dados do array "clientes" por ordem, o que faz com que sempre tenha a mesma profissão e o objetivo é sempre que voltar a executar esta função de dar a profissão, sempre seja aleatoriamente!
var clients = {'/#53h2bn324buh234', '/#h32h324h5234uh2', '/#3pm3b4ij234'};

Agradeço desde já quem se disponibilizar a ajudar-me, ou pelo menos tentar.

A:

O ideal seria explicar a forma que proponho desenhando, mas tentarei ilustrando. Para garantir que cada jogador terá um papel válido e que tenha somente 1 Policial,  1 Dama e 1 Criminoso vamos imaginar 5 crianças brincando.
Elas pegam uma caixa e colocam 5 papeis escritos as profissões disponíveis, tal que depois que elas terminam a caixa terá 1 Policial, 1 Criminoso, 1 Dama e 2 Cívis. Elas chacoalham a caixa para embaralhar e então cada uma tira um papel. No final, cada criança saberá a sua profissão e não haverá o risco de não ter saído nenhum policial ou ter dois policiais.
O que fiz nesse código é isso. Existe um array chamado papeis, onde possuem números associados a profissões, que são:
1 = Policial
2 = Criminoso
3 = Dama
4 = Cívil
Caso tenha mais de 4 jogadores, o array é preenchido de cívis, por isso o push(4). Então para cada cliente é removido uma profissão aleatóriamente da "caixa".

// deixar os papéis fixos
var papeis = [1, 2, 3, 4];

// Clientes em formato de array de objetos, para que cada cliente possua uma profissao
var clients = [{
  'id': '/#53h2bn324buh234',
  'profissao': null
}, {
  'id': '/#h32h324h5234uh2',
  'profissao': null
}, {
  'id': '/#3pm3b4ij234',
  'profissao': null
}, {
  'id': '/#3pm3b4ij222',
  'profissao': null
}];

// Se houver mais de 4 jogadores os demais serão civis
if (clients.length > 4) {
  for (var i = 0; i < clients.length - 4; i++) {
    papeis.push(4);
  }
}

// elegendo o papel para cada jogador
clients.forEach(function(cliente) {
  var aux = Math.floor(Math.random() * papeis.length);
  // splice remove o papel do array de papeis. Isso para
  // para que tenha somente 1 Policia, Dama e Criminoso.
  var papel = papeis.splice(aux, 1);
  cliente.profissao = obterProfissao(papel[0]);

  adicionarTela(cliente);
});

function adicionarTela(cliente) {
  var div = document.getElementById("papeis");
  var span = document.createElement("span");
  span.innerHTML = " O jogador: " + cliente.id + " é: " + cliente.profissao + "
"
  div.appendChild(span);
}

function obterProfissao(escolha) {
  //var socket = clients[SI];
  var profissaoT;

  if (escolha == 1) {
    profissaoT = "POLÍCIA";
    PoliceAlready = true;
  } else if (escolha == 2) {
    profissaoT = "CRIMINOSO";
    CriminalAlready = true;
  } else if (escolha == 3) {
    profissaoT = "DAMA";
    DamaAlready = true;
  } else {
    profissaoT = "CIVÍL";
  }
  return profissaoT;
  //socket.emit('profissao', profissaoT);
}

PS: Eu adorava esse jogo!


Q:

Finding the object key with the value inside the array?

I know Some people might find this very easy. But It seems to be very difficult to start. If i have array i could have easily done with filter.
Lets say i have this object
    const mapData = {family: ["gender", "ethnics"], house: ["wardNumber","livingType"]}

Now if I have atribute = "gender" How can i find the key  family.
if I have atribute = "livingType" Then i need  House;
Any Javascript pro here?
Thanks in advance

A:

You could get the keys and find with includes.
Methods:

Object.keys for getting own keys from an object,
Array#find for finding an item with a callback,
Array#includes, this checks if an item exists in an array.

const
    mapData = { family: ["gender", "ethnics"], house: ["wardNumber", "livingType"] },
    attribute = "gender",
    key = Object
        .keys(mapData)
        .find(k => mapData[k].includes(attribute));

console.log(key);


Q:

Storing the value of variable using TRadioGroup

I want to change the value of T according to a particular selection but it's not changing. Please have a look. The variable T has been declared along with Form1:TForm1 before 'implementation'. Basically, T should get assigned a linear or non linear equation depending upon the the selection of the respected radio buttons. I put a TEdit in the form so as to get an idea whether it is working or not. The last part is just a way to check by taking an example of Integer values.
Also, if I am not able to give a clear idea then just suggest me how to store a value of the concerned value using the Radiobuttons of the RadioGroup.
procedure TForm1.RadioGroup1Click(Sender: TObject);
begin

 if RadioGroup1.Items[RadioGroup1.ItemIndex] = 'Linear Tension' then
    T:= 5;
  if RadioGroup1.Items[RadioGroup1.ItemIndex] = 'Non-Linear tension' then
    T:= 10;
end;

procedure TForm1.Edit1Change(Sender: TObject);

var
code: Integer;
value: Real;
begin
  Val(Edit1.Text,value,code);
  Edit1.Text := formatfloat('#.0', T);

end;

end.

A:

It's really not a good idea to use a textual comparison for RadioGroup items. It's much better to simply use the ItemIndex directly:
procedure TForm1.RadioGroup1Click(Sender: TObject);
begin
  case RadioGroup1.ItemIndex of
    0: T := 5;
    1: T := 10;
  else
    raise Exception.Create('No item selected - should not get here');
  end;
  ShowMessage(FloatToStr(T));
end;

A:

Do not compare the captions because you will have magic values in your code.
Declare a ValueObject containing the Value and the Name
type
  TTensionValue = record
  private
    FValue : Integer;
    FName : string;
  public
    constructor Create( AValue : Integer; const AName : string );
    class function EMPTY : TTensionValue;
    property Value : Integer read FValue;
    property Name : string;
  end;

  TTensionValues = TList<TTensionValue>;

class function TTensionValue.EMPTY : TTensionValue;
begin
  Result.FValue := 0;
  Result.FName := '';
end;

constructor TTensionValue.Create( AValue : Integer; const AName : string );
begin
  // Validation of AValue and AName
  if AName = '' then
    raise Exception.Create( 'AName' );
  if AValue < 0 then
    raise Exception.Create( 'AValue' );

  FValue := AValue;
  FName := AName;
end;

Prepare a List with valid entries
type
  TForm1 = class( TForm )
  ...
    procedure RadioGroup1Click( Sender: TObject );
  private
    FTensions : TTensionValues;
    procedure PopulateTensions( AStrings : TStrings );
  public
    procedure AfterConstruction; override;
    procedure BeforeDestruction; override;
  end;

procedure TForm1.AfterConstruction;
begin
  inherited;
  FTensions := TTensionValues.Create;

  FTensions.Add( TTensionValue.Create( 5, 'Linear Tension' ) );
  FTensions.Add( TTensionValue.Create( 10, 'Non-Linear tension' ) );
end;

procedure TForm1.BeforeDestruction;
begin
  FTenstions.Free;
  inherited;
end;

Populate that list to the RadioGroup
procedure TForm1.PopulateTensions( AStrings : TStrings );
var
  LValue : TTensionValue;
begin
  AStrings.BeginUpdate;
  try
    AStrings.Clear;
    for LValue in FTensions.Count - 1 do
      AStrings.Add( LValue.Name );
  finally
    AStrings.EndUpdate;
  end;
end;

procedure TForm1.FormShow( Sender.TObject );
begin
  PopulateTensions( RadioGroup1.Items );
end;

Now you only ask the TensionList for the value
procedure TForm1.RadioGroup1Click( Sender: TObject );
begin
  T := FTensions[RadioGroup1.ItemIndex].Value;
end;

The selected value now only rely on the chosen ItemIndex and not on the caption text.


Q:

JSF 2.0 ViewHandler.restoreView(), ViewHandler.createView(): Client or/and Server Viewstate?

In JSF 2.0 specification in the restore/create View phase (section "2.2 Standard Request Processing Lifecycle Phases") it is said:

If the request is a postback, call setProcessingEvents(false) on the
  current FacesContext. Then call ViewHandler.restoreView(), passing the
  FacesContext instance for the current request and the view identifier,
  and returning a UIViewRoot for the restored view. If the return from
  ViewHandler.restoreView() is null, throw a ViewExpiredException with
  an appropriate error message. ...

when it is been  talked about ViewHandler.restoreView() which state is being refered here ? the server component state or the client component state here ?
more generally, how does one differentiate between the client and the server state? how JSF 2.0 manage to keep both synchronized with each other, if there is interaction of any sort?
Where Wikipedia acknowledges several types of state saving, including client and Server State saving and restoring, it does not elaborate more on them.

A:

when it is been talked about ViewHandler.restoreView() which state is being refered here ? the server component state or the client component state here ?

It's the JSF component tree, so I think that whatever you've definied the "server component state" term in your mind applies the most here, as your "client component state" term refers most probably the HTML DOM tree (which is by JSF generated during render response phase and sent from server to client).

more generally, how does one differentiate between the client and the server state? how JSF 2.0 manage to keep both synchronized with each other, if there is interaction of any sort?

Yes, the HTTP request (there's basically no other way to let the HTTP client interact with the HTTP server...). Note particularly the javax.faces.ViewState request parameter.


Q:

Insert hashbytes Incorrect syntax near 'MD5'

I'm using SQL Server 2014.  As part of a larger task, I need to detect updates etc from a table so am implementing Hashbytes. The Hasbytes field is defined as varbinary(MAX).
This is my SQL:
INSERT INTO tbl_People
  SELECT
    id,
    Name,
    Add1,
    Add2,
    Add3,
    HashValue as Hashbytes('MD5',CONCAT('|',Name, Add1, Add2, Add3))
from tbl_PeopleSource

However, I just keep receiving the error:

Incorrect syntax near 'MD5'.

Where am I going wrong?

A:

Missing a comma just before the HashValue alias, to separate Add3 from the next column. Also the alias is inverted, should be <expression> as AliasName.
Add3, -- Here comma
Hashbytes('MD5',CONCAT('|',Name, Add1, Add2, Add3)) as HashValue -- Inverted alias

Also it's good practice to list the inserted table's column so the order doesn't get wrongly interpreted:
INSERT INTO tbl_People (
    ID,
    Name,
    Col1,
    Col2,
    Col3,
    HashValue)
SELECT
    ...

There are multiple ways to use column aliases on SQL Server.


Q:

Compact framework custom control with collection not saving

I am creating a menu control for the compact framework. The control has a collection of items. I can add items using the visual studio designer, however, they are never added to the designer file and therefore next time I open the designer or build the solution the menu no longer has any items.
Here is the code for the Item:
public class Item
{
    public int ImageIndex { get; set; }

    private string _text = "";
    public string Text
    {
        get { return _text ?? ""; }
        set { _text = value ?? ""; }
    }

    public string Name { get; set; }
}

Here is the relevant code for the Menu:
public class ItemMenu : Control
{
    public ItemMenu()
    {
        Columns = 4;
        RowHeight = 64;
        ColumnWidth = 64;
        _items.ListChanged += new ListChangedEventHandler(_items_ListChanged);
    }

    private BindingList<Item> _items = new BindingList<Item>();
    public BindingList<Item> Items
    {
        get { return _items; }
    }

    public ImageList NormalImages { get; set; }
    public ImageList SelectedImages { get; set; }

    public int Columns { get; set; }
    public int RowHeight { get; set; }
    public int ColumnWidth { get; set; }
    public int Rows
    {
        get { return (int)Math.Ceiling((double)Items.Count / (double)Columns); }
    }

    private void _items_ListChanged(object sender, ListChangedEventArgs e)
    {
        Refresh();
    }
}

Does anyone know how I can get the collection of items to save to the designer file when I edit it in the visual studio designer?

A:

I'll try to answer this the best I can while I'm away for the holidays, but you need to specify a few design time attributes for your control. There is a DesignTimeAttributes file that you can add to your Controls assembly. It is an XML file, I believe with the XMTA extension. In the XML file for each class you can specify different design time attributes, as well as link a design time editor to the control etc.
The attribute you need to experiment with is the DesignerSerializationVisibility Attribute. I believe you can set this to Content so that it will correctly serialize your collection.
If you need more direction, I can update my answer when I get back to where I have an example.


Q:

How to ensure that formatoptions *never* contains `r` or `o`?

In vim, the filetype occasionally is set to a value that auto-populates formatoptions with r and o, two features that I do not like.  What setting can I add to guarantee that under no circumstances will those characters appear in formatoptions?

A:

You could define an auto-command in ~/.vimrc to remove r and o format options from every file type:
autocmd CmdLineLeave,BufEnter * set fo-=r fo-=o

A:

Modifying @sergio's answer slightly,
you could use
autocmd Filetype * set fo-=r fo-=o

in your vimrc.
This removes 'r' and 'o' from 'formatoptions' whenever the filetype is set.
(Note that filetype detection has to be on, which can be set by :filetype on.)


Q:

Contrib Module JavaScript interfering with Node

If one has a contrib module that works fine in most cases, but on a specific page (say /comment/comment) you wish it NOT to appear, but the options in Config don't give you that ability...what's the best practice for disabling functionality (in this case javascript) coming from the contrib module?
I'm using the sharebar module but it's all messed up in my comment/comment page. I tried hiding it with CSS (visibility:hidden) but can't target it no matter what I try. I even hid the html of the page itself and it still shows up! (although nothing else does)...which leads me to believe it's javascript...so how can I disable that for a particular page?

A:

That seems to be a common issue with the sharebar module.  The 7.x-2.x-dev version moves the sharebar into a block so that you can place it anywhere with either the block ui or the context ui.
The 7.x-2.x version is still in dev so you may need to do a little testing before enabling it on production, however, the module maintainer is suggesting that people upgrade to this version anyway.


Q:

Asked for a passphrase for a passphrase-less private key when SSH'ing on a virtual machine

I'm having some issues SSH'ing to a server when logged into a particular VM.
From my local PC, I can log in to the server just fine using the command ssh -i .ssh/[my private key] username@domain.
If I then SSH into another unrelated server which also has the same private key and run the above command it will also log in just fine in to the server.
But, when I SSH into a particular OpenStack VM (again has the same private key) on the unrelated server and then SSH in to the server from there I start getting prompted for a passphrase. But a passphrase hasn't been set for the key so inevitably I get a "Permission denied (publickey)." error.
To double check, I removed the private key from the VM and scp'd the private key from my PC into it again and tried the same command I still get prompted for a passphrase.
In other words:

PC - SSH - Server1 = Works fine
PC - SSH - Server2 - SSH - Server1 =
    Works fine
PC - SSH - Server2 - SSH - Virtual Machine - SSH - Server 1 =
        Asks for a passphrase

What could be the reason behind this? It's definitely the right private key I'm using and it has the appropriate permissions.
Edit - Output of ssh -v -i .ssh/[my private key] username@domain as requested
OpenSSH_7.4p1, OpenSSL 1.0.2k-fips  26 Jan 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 58: Applying options for *
debug1: Connecting to xxx.xxx.xxx.xxx [xxx.xxx.xxx.xxx] port 22.
debug1: Connection established.
debug1: key_load_public: No such file or directory
debug1: identity file /.ssh/[my private key].ppk type -1
debug1: key_load_public: No such file or directory
debug1: identity file /.ssh/[my private key].ppk-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.4
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.4 pat OpenSSH* compat 0x04000000
debug1: Authenticating to xxx.xxx.xxx.xxx:22 as '[my username]'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: curve25519-sha256@libssh.org need=64 dh_need=64
debug1: kex: curve25519-sha256@libssh.org need=64 dh_need=64
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:ZiugTjR5fM0E3evOwHoePFKspDQChA0Ab6L0q88KP/g
debug1: Host 'xxx.xxx.xxx.xxx' is known and matches the ECDSA host key.
debug1: Found key in /home/centos/.ssh/known_hosts:2
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /.ssh/[my private key].ppk
Enter passphrase for key '/.ssh/[my private key].ppk':
Enter passphrase for key '/.ssh/[my private key].ppk':
Enter passphrase for key '/.ssh/[my private key].ppk':
debug1: No more authentication methods to try.
Permission denied (publickey).

A:

Enter passphrase for key '/.ssh/[my private key].ppk':

"ppk" is the extension used by the PuTTY key generation tool. I presume the key file was generated using the putty tool. Unfortunately, the OpenSSH ssh utility doesn't read the PuTTY key file format. sshis asking for a passphrase because it will do that any time it can't parse a key file.
You can use the putty key tool to export the key in OpenSSH format. You should end up with two files, my-private-key and my-private-key.pub. The .pub file contains the public key portion which is installed on the remote system. The other file contains the private key which you use with the ssh command.
Alternately, you could use the OpenSSH ssh-keygen utility to generate a new key.


Q:

Problem Importing Web Service

I have created a web service in a virtual directory using VS 2008.  I have tested the service by going to the .asmx page and everything is working fine.  So I selected the "Add web reference" option under the solution and typed in the .asmx URL.  It found the web service  successfully and added the reference to the project.  However, when I try to import the service namespace using the same name as the directory under the "App_WebReferences" folder, it doesn't recognize the name and gives me an error if I try to import it.  Have I missed any steps in the process?

A:

Update: Try generating the proxy manually using the wsdl tool and adding the proxy class as an existing item to client web application project as mentioned in the link.
Something strange happening with proxy generation in your case from VS. Maybe an access issue.
If it happened fine, you should be able to find the VS generated proxy class under one of the sub-folders of
%windir%\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\ (for Asp.Net 2.0). Search for file names starting with App_WebReferences*.cs in the temporary folder.

When you added the web service, what is the name of the web reference you gave? Use the same web reference name in your import statement.
In this link, web reference name is com.deepfitness so you can import com.deepfitness namespace in your asp.net app.


Q:

How to optimise write to file in Rust?

I am new to rust. In past few days I learnt a lot from this community. With your help, I have made a code which reads 5000 files, do some transformation and write 700 files. However, I am still having issues with performance and I am trying to optimise. I could see that Writing to file was taking some time, so wanted to get an opinion on how to optimise it
//file_holder is hashmap
//file is a custom struct with 3 hashmap<String, f32>
file_holder.par_iter().for_each(|(name,file)| {
        serde_json::to_writer(&fs::File::create(name.to_string() +".json").expect("Failed writing"), &file).expect("Failed writing");
    });

A:

Thanks to Rodrigo, It worked.
file_holder.par_iter().for_each(|(k,file)| {
        let f = fs::File::create(k.to_string() +".json").expect("Unable to create file");
        let mut bw = BufWriter::new(f);
        serde_json::to_writer(bw, &file).expect("Failed writing :(");
    });


Q:

Appending column to dataframe with boolean response

My dataframe is as follows:
In [16]: df
Out[16]:
   name  dep
0  jai  sales
1  bobby  design
2  ram  dev
3 shyam dev design

My intention is to remake the dataframe as follows
In [16]: new_df
Out[16]:
   name  dev design sales
0  jai 0 1 0
1  bobby  0 1 0
2  ram  1 1 0

I tried the following
new_df["dev"] = df[df["dep"].str.contains('dev')]
new_df["design"] = df[df["dep"].str.contains('design')]

But this gives me the whole dataframe. How do I get a boolean result?
Note: pd.get_dummies does not give me such a result

A:

Use pd.get_dummies as:
df[['female','male']] = pd.get_dummies(df.gender)
del df['gender']

print(df)
    name  female  male
0    jai       0     1
1  bobby       1     0
2    ram       0     1

print(pd.get_dummies(df.gender))
   female  male
0       0     1
1       1     0
2       0     1

EDIT : If you have multiple strings in a value then use:
df = df.join(df.dep.str.get_dummies(sep=' '))
del df['dep']

print(df)
   design  dev  sales
0       0    0      1
1       1    0      0
2       0    1      0
3       1    1      0

print(df.dep.str.get_dummies(sep=' '))
   design  dev  sales
0       0    0      1
1       1    0      0
2       0    1      0
3       1    1      0


Q:

Implementing clipboard functionality on X (*nix) given the XWindow*?

I'm using the Allegro5 API to create my window and manage it. It allows me access to the XWindow which it creates with XCreateWindow
I have access to d->window but that's about it. From this, is there a way I could interact with the XEvents sent to this window? I want to implement clipboard functionality. I'm just not sure how I can deal with XSelection events.

A:

You need to create the xevent loop, and to handle specific xevents. Here is a xlib hello world example, and that is how you can do it.
The example is copied from here :
 #include<X11/Xlib.h>
 #include<stdio.h>
 #include<stdlib.h>

 int main()
 {
    Display *dpy;
    Window rootwin;
    Window win;
    Colormap cmap;
    XEvent e;
    int scr;
    GC gc;

    if(!(dpy=XOpenDisplay(NULL))) {
        fprintf(stderr, "ERROR: could not open display\n");
        exit(1);
    }

    scr = DefaultScreen(dpy);
    rootwin = RootWindow(dpy, scr);
    cmap = DefaultColormap(dpy, scr);

    win=XCreateSimpleWindow(dpy, rootwin, 1, 1, 100, 50, 0,
            BlackPixel(dpy, scr), BlackPixel(dpy, scr));

    XStoreName(dpy, win, "hello");

    gc=XCreateGC(dpy, win, 0, NULL);
    XSetForeground(dpy, gc, WhitePixel(dpy, scr));

    XSelectInput(dpy, win, ExposureMask|ButtonPressMask);

    XMapWindow(dpy, win);

    while(1) {
        XNextEvent(dpy, &e);
        if(e.type==Expose && e.xexpose.count<1)
            XDrawString(dpy, win, gc, 10, 10, "Hello World!", 12);
        else if(e.type==ButtonPress) break;
    }

    XCloseDisplay(dpy);
 }

To build, create a Makefile :
all: hello

hello: hello.o
    cc -o hello -Wall -L/usr/X11R6/lib -lX11 hello.o

hello.o: hello.c
    cc -o hello.o -Wall -I/usr/X11R6/include -c hello.c


Q:

Retrieve the Id of recently inserted record

I currently have this SQL insert code in code behind
Dim con As New SqlConnection
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("MyConnection").ConnectionString
con = New SqlConnection(conString)

con.Open()

Dim cmd As New SqlCommand("INSERT INTO AdditionalDaysRequest(Status, AdditionalDays, Justification,RequestDaySubmitted) VALUES (@Status,@AdditionalDays,@Justification,@RequestDaySubmitted)", con)

cmd.Parameters.AddWithValue("@Status", "Pending Request")
cmd.Parameters.AddWithValue("@AdditionalDays", TB_Days.Text)
cmd.Parameters.AddWithValue("@Justification", TB_Justification.Text)
cmd.Parameters.AddWithValue("@RequestDaySubmitted", Date.Now)

cmd.ExecuteNonQuery()
con.Close()

The Id in this table is automatically generated and incremented
What I would like to have now is the Id of this record inserted to add it to another table

A:

Change your query text to add a second statement:
 ...;SELECT SCOPE_IDENTITY();

The SELECT SCOPE_IDENTITY() statement Returns the last identity value inserted into an identity column in the same scope as from the MSDN  article above.
In addition, you can use the ability of the Sql engine to understand and process two or more command statements passed as a single string if you separe the statements with a semicolon.
In this way you have the great benefit to execute a single trip to the database.
 Dim cmd As New SqlCommand("INSERT INTO AdditionalDaysRequest(Status, " & _
     "AdditionalDays, Justification,RequestDaySubmitted) VALUES " & _
     "(@Status,@AdditionalDays,@Justification,@RequestDaySubmitted);" & _
     "SELECT SCOPE_IDENTITY()", con)

 cmd.Parameters.AddWithValue("@Status", "Pending Request")
 cmd.Parameters.AddWithValue("@AdditionalDays", TB_Days.Text)
 cmd.Parameters.AddWithValue("@Justification", TB_Justification.Text)
 cmd.Parameters.AddWithValue("@RequestDaySubmitted", Date.Now)
 Dim result = cmd.ExecuteScalar()
 con.Close()
 if result IsNot Nothing Then

       Dim lastInsertId = Convert.ToInt32(result)

 End If

Notice that the two statements are now executed using ExecuteScalar instead of ExecuteNonQuery because we want to catch the result of the last command.


Q:

How fill a plot to a given y0 value

I'm using Plotly in R and I want to create a plot like this:

But when trying with fill = "tozeroy" the plot looks like this:

Ignoring the value of y0
So, I want to fill the area from the lines to y0 value, instead to absolute zero.
A code example:
library(plotly)
library(magrittr)

x <- seq.Date(as.Date("2017/01/01"), as.Date("2017/12/31"), by = 1)
y1 <- rnorm(365, 100, 10)
y2 <- rnorm(365, 100, 10)

dat <- data.frame(x, y1, y2)

plot_ly(dat, x = ~x, y = ~y1, mode = "lines", type = "scatter", fill = "tozeroy", y0 = 80, name = "y1") %>%
add_trace(dat, x = ~x, y = ~y2, fill = 'tozeroy', y0 = 80, name = "y2")%>%
layout(xaxis = list(title = ""), yaxis = list(title = ""))

produces:

Ignoring the y0 = 80 parameter.

A:

If I understood correctly you want the range to begin in y0.
To that end, you have to change the yaxis' range in the layout.
This should suffice:
library(plotly)
library(magrittr)
set.seed(19)

x <- seq.Date(as.Date("2017/01/01"), as.Date("2017/12/31"), by = 1)
y1 <- rnorm(365, 100, 10)
y2 <- rnorm(365, 100, 10)

y0 <- 80
ymax <- max(y1,y2)

dat <- data.frame(x, y1, y2)

plot_ly(dat, x = ~x, y = ~y1, mode = "lines", type = "scatter", fill = "tozeroy", y0 = 80, name = "y1") %>%
  add_trace(dat, x = ~x, y = ~y2, fill = 'tozeroy',  name = "y2")%>%
  layout(xaxis = list(title = ""), yaxis = list(range = c(y0, ymax),title = ""))

The range options in plotly are explained here


Q:

preg_match pattern next line two first words

I have this preg_match pattern `/admin[^:]*:\s*(.* )/i for this subject(as sample)
txt stuff
Administrative Contact:
Brown, John support@xxxxxxx.com
txt stuff

to pull out "Brown, John support@xxxxxxx.com" but I need something to search and print "Brown, John" (name) only and not the whole line (everything as name but not email).
This is a piece of large text and the only static string is "Administrative Contact:".
Thanks

A:

http://ideone.com/u0UgL
$str = 'txt stuff
Administrative Contact:
Brown, John support@xxxxxxx.com
txt stuff';

preg_match('~admin[^:]*:\s*(.*)\s+\S+@~i', $str, $matches);
var_dump($matches[1]); // string(11) "Brown, John"


Q:

Running regression for each line of data.table

I have a big dataset with K>1million observations with 2xN cols. N cols are X-s and other N cols are Y-s. N is relatively small, N<<K.
I want to run a regression for each observation of the form Y_i = beta * X_i, where i=1,...N. Hence, I need to run K regressions and get K betas: beta_1,...,beta_K. I need to do this in more or less efficient way.
Here is the most primitive code I can do.
set.seed(10)
# Data looks like this
K = 15 # number of observations, in reality K is much larger say K = 100,000
# here implicitly N = 5, but it can vary, so if you can suggest a code that uses N as parameter it will be helpful.
data =
  tibble(X1 = rnorm(K,0,1),
       X2 = rnorm(K,0,1),
       X3 = rnorm(K,0,1),
       X4 = rnorm(K,0,1),
       X5 = rnorm(K,0,1),
       Y1 = rnorm(K,0,1),
       Y2 = rnorm(K,0,1),
       Y3 = rnorm(K,0,1),
       Y4 = rnorm(K,0,1),
       Y5 = rnorm(K,0,1)) %>%
  as.data.table()
# Let's introduce some missed variables
data[3,5] = NA
data[5,2] = NA
data[7,4] = NA
data[7,5] = NA
# A dumb loop code will be
beta = 1:K
for(i in 1:K){
  reg_data = tibble(x = data[i,1:5] %>% t(),
         y = data[i,6:10] %>% t() )
  colnames(reg_data) = c("x","y")
  beta[i] = lm(y ~ x + 0, reg_data)$coefficients
}
data$beta = beta
data

Data:
             X1          X2          X3          X4         X5          Y1          Y2          Y3          Y4          Y5        beta
 1:  0.01874617  0.08934727 -1.85374045 -0.02881534 -1.2375945  1.17270628 -0.41635467  0.56317466 -0.48136561 -0.98306919  0.03442037
 2: -0.18425254 -0.95494386 -0.07794607  0.23252515 -0.4561763 -1.47982702 -0.19148234  0.66098669  0.20288178  0.49533171  0.18549600
 3: -1.37133055 -0.19515038  0.96856634 -0.30120868         NA -0.43038782  0.06954478 -1.65805086 -0.03173974  0.72581750 -0.34597018
 4: -0.59916772  0.92552126  0.18492596 -0.67761458  0.3401156 -1.05163864  1.15534832  1.02816798 -1.19558030  0.66729873  1.60396614
 5:  0.29454513          NA -1.37994358  0.65522764  1.0663764  1.52258634  0.59495735  1.12795361  0.62368124  0.95478644  0.08960632
 6:  0.38979430 -0.59631064 -1.43551436 -0.40063755  1.2161258  0.59282805 -1.41964511 -1.28015460 -0.91480448 -1.67533218  0.29574377
 7: -1.20807618 -2.18528684  0.36208723          NA         NA -0.22266151 -1.60667725  1.12886823  0.24875801 -1.20518539  0.65799077
 8: -0.36367602 -0.67486594 -1.75908675  1.36795395 -0.4812086  0.71289428  0.89292590 -0.46413453 -1.06262279 -1.96325249 -0.09581759
 9: -1.62667268 -2.11906119 -0.32454401  2.13776710  0.5627448  0.71660083  0.14816796 -0.31576021 -0.36398225  1.47075231 -0.10946286
10: -0.25647839 -1.26519802 -0.65156299  0.50581926 -1.2463197  0.44024186  1.22702839  0.92429315 -1.20699485  0.37247234 -0.85696018
11:  1.10177950 -0.37366156  1.08655140  0.78634238  0.3809222  0.15883062 -0.76180434  0.07714472  1.42921278  1.06587933  0.62874846
12:  0.75578151 -0.68755543 -0.76254488 -0.90221194 -1.4304273  0.65976414  0.41937541  1.03992361  0.63343589  0.53064987 -0.42653775
13: -0.23823356 -0.87215883 -0.82866254  0.53289699 -1.0484455  2.22051966 -1.03994336  0.74188621 -1.99681562  0.10198345 -0.48758134
14:  0.98744470 -0.10176101  0.83447390 -0.64589425 -0.2185036 -1.18394507  0.71157397  1.25554486 -0.68183217  1.33778247 -0.02128415
15:  0.74139013 -0.25378053 -0.96765199  0.29098749 -1.4899362 -0.07395583 -0.63321301  0.95091897 -0.46005548  0.08723477 -0.27967233

.
What is an efficient data.table-way to do this?

A:

Here is an option to convert it into a long format and then just calculate the coefficients in the linear regression using the equations found here
DT <- melt(data[, rn := .I], id.vars="rn", measure.vars=patterns(c("X", "Y")),
    na.rm=TRUE, value.name=c("X","Y"))[order(rn)]

DT[, {
        sumx <- sum(X)
        sumy <- sum(Y)
        sumxsq <- sum(X^2)
        sumxy <- sum(X*Y)
        b <- (sumxy - sumx * sumy / .N) / (sumxsq - sumx^2 / .N)
        .(`(Intercept)`=sumy / .N - b * sumx / .N, X=b)
    },
    rn]

#for comparison
#DT[, as.list(lm(Y ~ X, .SD)$coefficients), rn]

output:
    rn (Intercept)           X
 1:  1 -0.01297769  0.02656658
 2:  2 -0.01363072  0.16932027
 3:  3 -0.63389115 -0.53933759
 4:  4  0.06518737  1.59775760
 5:  5  1.07353565 -0.10238037
 6:  6 -0.92042107  0.11494024
 7:  7  0.83134259  1.05384614
 8:  8 -0.47319334 -0.25212270
 9:  9  0.31078353 -0.07436378
10: 10 -0.26208273 -1.05275512
11: 11  0.04097118  0.59169896
12: 12  0.67359486  0.02802331
13: 13 -0.40133349 -0.82876842
14: 14  0.31281032 -0.14598437
15: 15 -0.14023767 -0.34075091


Q:

I get "ER_BAD_FIELD_ERROR" using mysql alias

I want to create columns on the fly in the database.
But when I use SQL alias, I get back Error: ER_BAD_FIELD_ERROR: Unknown column 'product_sales' in 'field list.
The column product_sales is not recognized.
Here is my code:
let query = `SELECT dept_id, dept_name, over_head_costs, product_sales) AS product_sales, product_sales - over_head_costs AS profit FROM departments`;

connection.query(query, (err, res) => {
  if (err) throw err;
  console.log(res);

I expect the output to include all the column names including those which were created on the fly.

A:

You have a wrong  closing ) after product_sales try remove it
You are using product_sales - over_head_costs but juts before this columns you reassign the product_sales  using an alias (with the same name)  so you can't use alias in select clause  .. the you should remove the (unuseful ) aliasing for product_sales AS product_sales
let query = `SELECT dept_id, dept_name, over_head_costs
      , product_sales
      , product_sales - over_head_costs AS profit FROM departments`;