text:
Q: Save Game Using JSON in Unity I create a simple Save Game system in Unity using Unity's JSON Serialization. My Save Game is pretty simple, I am only saving the position of my character and loading it.
The save game works fine, in-game. When I launch the game and click 'Save' the game is saved and the JSON file is updated with my players position. When I click 'Load' the game loads fine and my player is moved to the previously saved position.
However my issue is that whenever I shut down the game and relaunch it, the 'Load' function just resets my character to the position at which I spawn it at. It does not load the character at my previously saved position in the last game.
Now for my code. I have an Actor class which hold my actor's data:
using UnityEngine;
using System.Collections;
using System;

public class Actor : MonoBehaviour
{

    public ActorData data = new ActorData(); // to store our data

    public void StoreData() // for storing our data
    {
        data.pos = transform.position;
    }

    public void LoadData() // for loadinjg our data
    {
        transform.position = data.pos;
    }

    public void ApplyData()
    {
        SaveData.AddActorData(data);
    }

    void OnEnable() // to enable the save/load to avoid hanging
    {
        SaveData.OnLoaded += LoadData;
        SaveData.OnBeforeSave += StoreData;
        SaveData.OnBeforeSave += ApplyData;
    }

    void OnDisable() // to disable the save/load to avoid hanging
    {
        SaveData.OnLoaded -= LoadData;
        SaveData.OnBeforeSave -= StoreData;
        SaveData.OnBeforeSave -= ApplyData;
    }
}

[Serializable] // for storing in JSON
public class ActorData // our players attributes in JSON
{
    public Vector3 pos;
}

I also have an ActorContainer to hold the data for different players:
using System.Collections.Generic;
using System;

[Serializable]
public class ActorContainer
{

    // To store our different actors data
    public List<ActorData> actors = new List<ActorData>();
}

I have a SaveData class which performs my Serialization:
    using UnityEngine;
using System.Collections;
using System.IO;

public class SaveData
{

    // every actos will be sorted in this actor container when loading the game
    public static ActorContainer actorContainer = new ActorContainer(); // static so that we dont have to recreacte savedata everytime

    public delegate void SerializeAction();
    public static event SerializeAction OnLoaded; // happens after loading
    public static event SerializeAction OnBeforeSave; // right before saving

    public static void Load(string path) // where the load is
    {
        actorContainer = LoadActors(path);

        OnLoaded();

        ClearActorList(); // so that there's no duplicates
    }

    public static void Save(string path, ActorContainer actors)
    {
        OnBeforeSave(); // to throw of the data that was in OnBeforeSave

        SaveActors(path, actors); // store all of our actors as json in the file

        ClearActorList(); // clear the list so that the next time we save theres no duplicates
    }

    public static void AddActorData(ActorData data)
    {
        actorContainer.actors.Add(data);
    }

    public static void ClearActorList() // to avoid duplicate data
    {
        actorContainer.actors.Clear(); // access actors and clear it
    }

    private static ActorContainer LoadActors(string path) // path to the JSON
    {
        string json = File.ReadAllText(path); // loading all the text out of the file into a string, assuming the text is all JSON

        return JsonUtility.FromJson<ActorContainer>(json); // parse the JSON into an ActorContainer type and return in the LoadActors
    }

    private static void SaveActors(string path, ActorContainer actors) // where to save and the actors to save
    {
        string json = JsonUtility.ToJson(actors);

        StreamWriter sw = File.CreateText(path); // if file doesnt exist, make the file in the specified path
        sw.Close();

        File.WriteAllText(path, json); // fill the file with the data(json)
    }
}

Lastly I have a GameController class which acts as a communicator with Unity:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.IO;

public class GameController : MonoBehaviour
{ // to tell unity what it has to do, a communicator to be used with unity

    // trigger buttons
    public Button saveButton;
    public Button loadButton;

    private static string dataPath = string.Empty;

    void Awake()
    {
        dataPath = System.IO.Path.Combine(Application.persistentDataPath, "actors.json"); // persistentDataPath unity save game path, actors.json name of the file containing actors
    }

    // for button
    public void Save()
    {
        SaveData.Save(dataPath, SaveData.actorContainer);
    }

    // for button
    public void Load()
    {
        SaveData.Load(dataPath);
    }
}

My JSON file actors.json contains the following:

{"actors":[{"pos":{"x":419.6240539550781,"y":5.0189208984375,"z":0.0}}]}

Any suggestions are welcome.

A: So the problem is simply, you never assign the loaded Value from the JSON to data.pos in Actor.cs. Instead you load it from the public field ActorData data, which hasn't changed.
If i can see this right you have to change in Actor.cs following:
using System.Linq;

// ..

public void LoadData()
{
    // guessing you will implementing an identifier for the separate actors later..
    var currentActor = SaveData.actorContainer.First();
    transform.position = currentActor.pos;

    // also set the loaded data to the field
    data = currentActor;
}

// ..


text:
Q: Error : Linked AMP version is invalid In Blogger I created a blogger template that supports accelerator pages (AMP) , but when Inspect the link on google search console I get an error:

Error : Linked AMP version is invalid

In my template I created two models:
The first does not support accelerated pages:
The second appears when I add ?view=amp at the end of the link exemple:

https://www.example.com/2020/01/post.html?view=amp

Please note that I added the meta to the template
<link href="https://www.example.com/2020/01/post.html?view=amp" rel="amphtml">

redpajama_set_name: RedPajamaStackExchange


text:
Q: To create Filestream enabled DB in Microsoft SQL Server 2012 The following query is my first query on File Stream concept.
EXEC sp_configure filestream_access_level, 2
RECONFIGURE
go
CREATE DATABASE Archive
ON
PRIMARY ( NAME = Arch1,
    FILENAME = 'c:\data\archdat1.mdf'),
FILEGROUP FileStreamGroup1 CONTAINS FILESTREAM( NAME = Arch3,
    FILENAME = 'c:\data\filestream1')
LOG ON  ( NAME = Archlog1,
    FILENAME = 'c:\data\archlog1.ldf')
GO

First of all I go-through the following links for self learning the File Stream.
Configure Filestream Link
Create DB Link
SO answer Link
Using these links, yet I got general error as

FILESTREAM feature is disabled.

Let me show the Query, Error and DB's property

What can I do next?
Edit: 1
I did following process with help of Restart SQL Server services. Still, error remains.

To start, stop, pause, resume, or restart an instance of the SQL Server Database Engine
   Start SQL Server Configuration Manager, using the instructions above.
If the User Account Control dialog box appears, click Yes.
In SQL Server Configuration Manager, in the left pane, click SQL Server Services.
In the results pane, right-click SQL Server (MSSQLServer) or a named instance, and then click Start, Stop, Pause, Resume, or Restart.
Click OK to close SQL Server Configuration Manager.

We can see the Data Engine in Quotes. whereas, the link contains SQL Server services. Am I did correctly?
Thanks,
TamilPugal.

A: Thanks to Dan Guzman.
I got solution for my problem. That is on Enable and Configure Filestream. Under this topic.

Enabling FILESTREAM

But I have no idea about this query:
EXEC sp_configure filestream_access_level, 2

Thanks,
TamilPugal


text:
Q: FlatList, Invariant Violation: numColumns does not support horizontal In my project it is showing the above error.
ProductContainer.js:
import React, { useState, useEffect } from 'react'

import { View, Text, StyleSheet, ActivityIndicator, FlatList } from

'react-native'

import ProductList from './ProductList';

const data = require('../../assets/data/products.json');

const ProductContainer = () => {

    const [products, setProducts ] = useState([]);

    useEffect(() => {

        setProducts(data);

        return () => {

            setProducts([])
        }
    }, [])

    return (

        <View>

            <Text>Product Container</Text>

            <View style={{ marginTop: 100}}>
            <FlatList

                numColumns={2}

                horizontal

                data={products}

                renderItem={({item}) => <ProductList

                key={item.id}

                item={item}/>}

                keyExtractor={item => item.name}

            />

            </View>

        </View>
    )
}

export default ProductContainer;

The error details:
This error is located at:

    in FlatList (created by ProductContainer)

    in RCTView (created by View)

    in View (created by ProductContainer)

    in RCTView (created by View)

    in View (created by ProductContainer)

    in ProductContainer (created by App)

    in RCTView (created by View)

    in View (created by App)

    in App (created by ExpoRoot)

    in ExpoRoot

    in RCTView (created by View)

    in View (created by AppContainer)

    in RCTView (created by View)

    in View (created by AppContainer)

    in AppContainer

If you want I can provide other details also.
Thanks in advance

A: You cannot have an horizontal FlatList with multiple columns. That is what React Native's documentation says:

Multiple columns can only be rendered with horizontal={false} and will zig-zag like a flexWrap layout. Items should all be the same height - masonry layouts are not supported.

You should remove numColumns=2 if you want your FlatList being horizontal or set horizontal to false if you want two columns.
  <FlatList
      numColumns={2}
      horizontal={false}
      data={products}
      renderItem={({item}) => <ProductList
      key={item.id}
      item={item}/>}
      keyExtractor={item => item.name}

  />


text:
Q: how to make specific text in email message in bold using python I am using Windows10 OS, Python 3.7.9 64-bit, I am send automated email in which the employee name alone must be in Bold, I tried the below code, but not getting proper output
e_name = "XXX"
msg = "Dear " + '\033[1m' + e_name + '\033[0m' + "\n\n"

Expected output:
Dear XXX
Actual Output:

In the terminal, it prints the bold text, but while receiving mail, I am getting like this. Please help on this
Also, I want to some items in the list with bullet points which are not manually printed using print statement, the values are in the list of in the dataframe, so I will be using for loop for iteration.
How to print those with bullets (. dot) preceeding the each items.. This also will be the part of the email message.

below is my code, inside for loop, where each item should be displayed with bullets and in bold text in the email.
message = row['employee_id'][i] + "  --  " + row['employee_name'][i] + "\n\n"

also tried simple_colors package,below is the code, even for this method, in the terminal, I am getting correct output, but in the email getting the same Actual Output shown above
from simple_colors import *
message = black(row['employee_id'][i] + "  --  " + row['employee_name'][i] + "\n\n", 'bold')

A: You can't make bold text unless your application is able to use Markdown or similar. However, to emphasise anyway, you could simply add an asterisk or two, i.e. **xxx**
You can, however, include a bullet as text. The Unicode is U+2022 or you can copy this: • (see also https://unicode-table.com/en/2022/ or the white bullet https://unicode-table.com/en/25E6/).


text:
Q: How do I configure Spacy pipeline to lemmatize a spellchecker component's results? I'm currently trying to add a spellchecker step into one of Spacy's built-in pipelines, specifically 'en_core_web_sm'
I found a pretty neat component called Contextual Spell Check that I've inserted into the pipeline. The problem is that the lemmatize step isn't lemmatizing the spell-checked word, but rather the original text, EVEN after I've reordered the pipeline to ['tok2vec', 'parser', 'contextual spellchecker', 'tagger', 'attribute_ruler', 'lemmatizer', 'ner'].
For example:
doc_a = nlp("Income wes $9.4 milion compared to the prior year of $2.7 milion.")
doc_b = nlp("Income was $9.4 milion compared to the prior year of $2.7 milion.")

Will return the correctly spell-checked results of:
print(doc_a._.outcome_spellCheck)
# Income was $9.4 million compared to the prior year of $2.7 million.

print(doc_b._.outcome_spellCheck)
# Income was $9.4 million compared to the prior year of $2.7 million.

However, examining the underlying results:
# doc_a with misspelled 'was'. Note lemma is still the original typo 'wes'
print(doc_a.to_json()['tokens'])
# {'id': 1, 'start': 7, 'end': 10, 'tag': 'MD', 'pos': 'AUX', 'morph': 'VerbType=Mod', 'lemma': 'wes', 'dep': 'ROOT', 'head': 1}

# doc_b with correctly spelled 'was'. Correctly lemmatized to 'be'
print(doc_b.to_json()['tokens'])
# {'id': 1, 'start': 7, 'end': 10, 'tag': 'VBD', 'pos': 'AUX', 'morph': 'Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin', 'lemma': 'be', 'dep': 'ROOT', 'head': 1}

How do I ensure lemmatize happens on the spell-checked term?

A: spaCy is designed to make sure that the original text is never modified. Unfortunately that is not what you want in your case, but there is not really a way to work around it.
In this case I would recommend you have a spellcheck-only pipeline, and use the spellchecker output to generate a new string that you feed to your lemmatizing pipeline.
Something like this...
spellchecker = ... minimal nlp with the spellchecker...
nlp = ... normal non-spellcheck pipeline ...

doc = nlp(spellchecker(text)._.outcome_spellCheck)

There are other things you could do like load the lemmatizer and create a component to feed spellchecker results to it directly, or maybe use an attribute ruler to map from spellchecker output to your tokens, but the separate pipelines is probably easier to set up as it has minimal dependencies between parts.


text:
Q: How to monitor InnoDB Disk I/O using Server Status Variables? This question is extension of my previous question "How to monitor InnoDB Disk I/O Required for MySQL? "
As mention in my previous question i want to count total number of disk i/o per query, but while testing i got confused with some result ,
i am using below example ::
mysql> explain user;    ------->[user table from Website database]
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| username | varchar(50) | YES  | UNI | NULL    |                |
| id       | int(11)     | NO   | PRI | NULL    | auto_increment |
| password | varchar(50) | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

I have created a index on username.
My analysis is
before running any query system variable status was

'Created_tmp_disk_tables', '1'
'Created_tmp_files', '12'
'Created_tmp_tables', '8'
'Key_reads', '0'
'Key_writes', '0'
'Innodb_buffer_pool_reads', '425'
'Innodb_log_writes', '26'

when i tried

insert into user (`username`,`password`) values ("xyz1","xyz1");

'Created_tmp_disk_tables', '1'
'Created_tmp_files', '12'
'Created_tmp_tables', '8'
'Key_reads', '0'
'Key_writes', '0'
'Innodb_buffer_pool_reads', '425'
'Innodb_log_writes', '27' -------> (shows one write operation in Innodb_log )

when i tried

Select * from user where username ="xyz1";

'Created_tmp_disk_tables', '1'
'Created_tmp_files', '12'
'Created_tmp_tables', '8'
'Key_reads', '0'
'Key_writes', '0'
'Innodb_buffer_pool_reads', '425'
'Innodb_log_writes', '27'

and when i tried

UPDATE user SET `username`="xyz1", `password`="hello"
WHERE `username`="devlad1";

'Created_tmp_disk_tables', '1'
'Created_tmp_files', '12'
'Created_tmp_tables', '8'
'Key_reads', '0'
'Key_writes', '0'
'Innodb_buffer_pool_reads', '425'
'Innodb_log_writes', '29'------>[shows two write operation to log]

My first question are

1). I am calculating disk i/o correctly or i am missing something here?
2). I have create index on 'username' so while doing insert or update index >    count should be modify but varible "Key_writes" keep showing me '0' ,what >    does it means? is index is caching some where ?

thanks in advance!!!!

A: *

*Innodb_log_writes monitor only writes to the innodb transaction log. InnoDB also writes to the double write buffer, data (aka primary key) and secondary indexes on the tablespace, change buffer, undo space, ... Some of these can be buffered on memory, at least for some amount of time.
Additionally, MySQL may write to the mysql binary, general or slow log, or use certain temporary structures for pending transactions, binlog, tables for intermediate results, etc. if they do not fit in memory. Also, bear into mind that if a query involves a temporary table, it can show I/O activity in other engines, as it may create such tables in MyISAM format.
Depending on the configuration and change, a write to InnoDB may cause 0 writes to the transaction log (for example, if it has not yet been synced, or no page was modified) or several (at least one per page modified). Even if you only update 1 record, it may case the modification of several pages (e.g. because a blob is involved, or an index have to be updated). You can check the size of the writes to the transaction log by monitoring the InnoDB Log Sequence Number. Under a strict "flush log at transaction commit", the writes to the log are the only thing that is done to disk, all other changes are tried to be buffered on memory and are written at any future time.
While somehow inaccurate, InnoDB has a section in File I/O in its SHOW ENGINE INNODB STATUS command, for a more global view. As @Ela says, innotop is a good summary tool for monitoring InnoDB operations, including the former command.

*Yes, index changes can be buffered, as any writes. Not only the index pages, but index updates are usually heavily buffered through the change buffer and merged later (more than normal updates, as they involve reading data that may not be on cache). Check the INSERT BUFFER AND ADAPTIVE HASH INDEX section on the previous INNODB STATUS command.
In a nutshell, InnoDB is a complex "set of buffers and asynchronous reads and writes", and there is never a guarantee that we can stop all I/O operations (some of them only kick when the server is idle). This is a good introduction material to InnoDB architecture and operations: https://www.percona.com/live/london-2013/sessions/innodb-architecture-and-performance-optimization

A: You should look at this. Mark Leith is a senior MySQL dev. manager. It's a way (MySQL are trying to get better...) that you can track some metrics - not per query like you want, but data access by table. Install the sys schema in your 5.6 instance and see what happens.
Oh - yes - you were asking about InnodDB in 5.6 - you will have to enable innodb_file_per_table (on by default by 5.7).
On a test system, at least that's a start.
You can start by looking at
select file, total_read, total_written from x$io_global_by_file_by_bytes limit 10;
which doesn't give you data by query, but at least it will start to give you an idea of where to look.
This should start to give you and idea of your i/o per table, if not by query - which (and I'm open to correction here) is not possible with MySQl at the moment.
[EDIT in repsonse to OP's comments]
I'm afraid that I'm having a bit of difficulty in following your exact question. From the docco here and here, you have the defintions of the variables you're asking about. The first is the number of write operations and the second is the number of bytes. How you're going to relate the two, I just don't know. I imagine that it's not simple - what with caching, checkpointing and buffering. I'm guessing that the relationship between the two is some sort of complex function of the application performing the database access - no. of commits &c.
On a brighter note, I did come across something which may help you and make your life a bit easier. If you look here, Mark Leith (mentioned above) talks about how the ps_helper tool is now being implemented in MySQL-Workbench as the sys schema. He also has dba_helper (more experimental AIUI) which is also useful - I think you need dba_helper alongside the sys schema (installed it recently but have forgotten the exact details).
The key point is that all of this (or most of it anyway) is now available within MySQL Workbench in the Peformance->Performance reports section. You could take a look at that and see if that goes any further to answering your issues.
You have said that you are looking for data i/o per query - why are you trying to do this? In any case, if you have your InnoDB tables as separate files (innodb_file_per_table=ON), then you can have a very good idea of what your system is doing - even if you can't get an exact data per query report.
If I were you, I would install Mark Leith's sys schema and dba_helper scripts and then investigate the performance reports and if you have any questions, come back here. I hasten to add that I'm not an expert in this area - I just happen to have looked at it a little.


text:
Q: Check at compile time class constructor signature Is there a way to check at compile time if some class has constructor with certain arguments ?
?
For example:
class foo {
    foo(std::string &s) {
    }
};

I want to check at compile time that constructor with std::string& always defined. Maybe boost provides such functionality ?

A: The common way to check if a specific function exists is to take its address and assign it to a dummy variable. This is a lot more precise than the tests mentioned so far, because this verifies the exact function signature. And the question was specifically about string& in the signature, so non-const and thus presumably modifying the string.
However, in this case you cannot use the take-the-address-and-assign-it trick: constructors don't have addresses. So, how do you check the signature then? Simply: Befriend it in a dummy class.
template<typename T>
class checkSignature_StringRef {
    friend T::T(string&);
};

This too is a very specific check: it will not even match similar constructors like foo::foo(std::string &s, int dummy = 0).

A: I came up with a similar problem wanting to forward constructors to base class when the arguments are compatible, and to do something else when not.
Here is a generalized traits working on MSVC 2013 (requires C++11 stuff):
namespace detail {
    template<class type,class...Args>
    class constructible_from
    {
        template<class C>
        static C arg();

        template <typename U>
        static boost::mpl::true_ constructible_test(U *, decltype( U(arg<Args>()...) ) * = 0 );
        static boost::mpl::false_ constructible_test(...);

    public:

        typedef decltype( constructible_test(static_cast<type*>(nullptr)) ) result;

    };
}   // namespace detail

template<class type>
struct constructible
{
    template<class...Args>
    struct from :
        detail::constructible_from<type,Args...>::result {};
};

Here is a traits usage example, I leave the enable_if application as an exercise :D :
struct b{};
struct c{};
struct d : c{};

struct a
{
    a() {}
    a(a &) {}
    a(b,c) {}
    a(c) {}
};

static_assert(
    constructible<a>::from<>::value,
    "a()"
);
static_assert(
    constructible<a>::from<a&>::value,
    "a(a&)"
);
static_assert(
    ! constructible<a>::from<const a&>::value,
    "a(const a&)"
);
static_assert(
    constructible<a>::from<b,c>::value,
    "a(b,c)"
);
static_assert(
    ! constructible<a>::from<b>::value,
    "a(b)"
);
static_assert(
    constructible<a>::from<c>::value,
    "a(c)"
);
static_assert(
    constructible<a>::from<d>::value,
    "a(d)"
);

A: If you really need it, you can add this function:
static void _dummy() { std::string s; foo f(s); }

Without your constructor, the compilation will fail. Note: your constructor is private. If it's on purpose, then _dummy should be inside the class. Otherwise, you can have it outside the class.
Also, you can templatize or even make it a macro, if this happens a lot in your code.
But to tell the truth, it still looks like a hack. Are you sure you need it?

A: If you're trying to check if foo is constructible from a string, you can use boost::is_convertible.
For example:
BOOST_STATIC_ASSERT((boost::is_convertible<std::string, foo>::value));

A: Using Concept check in boost 1.39:
#include <boost/concept_check.hpp>

class foo_c
{
public:
    foo_c(std::string& s)
    {}
};

template<typename T>
class algo_c
{
BOOST_CONCEPT_ASSERT((boost::Convertible<std::string,T>));
public:
    algo_c()
    {}
};

Removing or changing the constructor of foo_c result in the following compile time error:

error C2440: 'initializing' : cannot
  convert from 'std::string' to 'foo_c'

EDIT:
That can be made to work with explicit constructor with a homemade concept check:
template <typename T>
struct HasTheRightConstructor
{
    BOOST_CONCEPT_USAGE(HasTheRightConstructor)
    {
        std::string v;
        T j(v);
    }
};

A: What you are asking for sounds a lot like a unit test.  I would download something like cppunit and integrate it into your compilation.
Any unit tests you write will be built/executed at compile time.  See Unit Testing for more information.

A: If you need this kind of checks, you'll probably need some other compile time checking
I suggest to take a look to boost concept checking library (documentation is here). You can find some documentation, classes and macros that can help you.


text:
Q: Reversing Order of Select List in Javascript & HTML // Generate and append Base array from DB based on ID selected
function BasePopulation(id) {

    // Use previous query
    var array = dropdownRequest.responseJSON[id];

    // Create Base dropdown
    $("#inputGroup")
        .append(
            '
' +
                '<select id="BaseSelect" name="BaseSelect" class="selectpicker" data-size="10" data-width="auto" data-container="body" title="Base">' +
                    '<option>Base</option>' +
                    '' +
                '</select>' +
            '
'
        );

    // Populate Base dropdown

    $.each(array, function(index, base) {
        // Reformat JD Base
        var base_value = BaseToValue(base);

        $("#BaseSelect")
            .append($("<option class='removable'></option>")
            .attr("value", base_value)
            .text(base));
    });

    $("#BaseSelect").selectpicker("refresh");

}

I'm trying to reverse the order of the dropdown list in HTML/Javascript, but I can't find a reverse function. Is there a function to do this, or do I have to do this manually?

A: There are two possible ways for you to populate the dropdown reversly.
1: with jQuery .prepend() method instead of .append()
$.each(array, function(index, base) {
    // Reformat JD Base
    var base_value = BaseToValue(base);

    $("#BaseSelect")
        .prepend($("<option class='removable'></option>")  // Using prepend
        .attr("value", base_value)
        .text(base));
});

2: with the JS .reverse() method applied on the array
array.reverse()

$.each(array, function(index, base) {
  ...

Read the documentation for more details ;)

A: If you reverse this var array = dropdownRequest.responseJSON[id];
array with the .reverse function?


text:
Q: handlebars layouts and partials in a sails.js application I'm developing a web application with sails.js v0.10 and I'm using handlebars templates, I want to use layouts and partials. I figured out that sails.js uses express3-handlebars to provide handlebars layouts and partials. But I can't use both at the same time.
My config/views.js file is:
    ...
    engine: 'handlebars',
    layout: 'layouts/main.handlebars'
    ...

This works perfectly, the layout is loaded. The problem is when I'm try to use partials, I get an error saying that the partial was not found.
    //UserController.js
    ...
    index: function(req, res) {
        res.view({partials: {userlist: 'partials/userlist'}});
    ...

This only works when I change the value of the config/views.js layout property to false. But when I do that I can't use layouts anymore.
is it a bug in sails.js? or, am I doing something wrong?

A: This is not a bug. It is actually by design.
In Express 3, built-in support for layouts/partials was deprecated. Instead, developers are expected to rely on the view engines themselves to implement this features. (See https://github.com/balderdashy/sails/issues/494 for more info on that.)
Since adopting Express 3, Sails has chosen to support the legacy layouts feature for convenience, backwards compatibility with Express 2.x and Sails 0.8.x apps, and in particular, familiarity for new community members coming from other MVC frameworks. As a result, layouts have only been tested with the default view engine (ejs).
If layouts aren't your thing, or (for now) if you're using a server-side view engine other than ejs, (e.g. Jade, handlebars, haml, dust) you'll want to set layout:false in sails.config.views, then rely on your view engine's custom layout/partial support.


text:
Q: Replace each value in Series with its relative ranking I have a sorted Series, is there a simple way to change it from
A    0.064467
B    0.042283
C    0.037581
D    0.017410
dtype: float64

to
A    1
B    2
C    3
D    4

A: You can just do rank
df.rank(ascending=False)


text:
Q: std::string copy constructor seg fault this happens when constructing a structure, my code:
http://wklej.org/hash/c42680a7f9d/txt/ at this line: http://wklej.org/hash/5fefcecc371/txt/ backtrace: http://wklej.org/id/451070/txt/
any help is apperciated
Sorry, i fail to copy the code here so i post it at any other site ;(

A: Use a debugger and get a stack trace.
The problem is almost certainly passing a bad C string into the std::string constructor. Perhaps the pointer is invalid or the C string does not terminate and the constructor reads off into protected memory.
But without more information I can't tell what the bug is. The debugger should point it out immediately.
Also, your Socket holds a pointer but only defines a constructor and destructor. You also need a copy constructor and an assignment operator. If those two operations aren't supposed to happen then define them as private with no implementation.
Also, I see from your backtrace that this is an old version of GCC. It's possible that this version does not have the fixes that make std::string safe to use in multi-threaded programs. I don't know when it was fixed but some older versions of the libstdc++ library didn't lock the reference counts on the string and could crash when different threads would free the string memory while also writing to it.

A: I've placed your code here in order to be able to edit it:
#ifdef _WIN32
    #define _WIN32_WINNT 0x0501
#endif

#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <sstream>
#include <string>

#ifdef assert
    #undef assert
#endif

#define assert(x)\
    if (!x) { \
        std::clog << "[Error - __FUNCTION__] Asseration to: " << #x << " failed. line: " << __LINE__ << ", file: " << __FILE__ << "." << std::endl;\
        std::exit(100);\
    }

template<typename _Tp>
inline std::string toString(_Tp __p)
{
    std::stringstream ss;
    ss << __p;
    std::string ret;
    ss >> ret;
    return ret;
}

struct Proxy;

typedef std::vector<Proxy*> ProxyVec;

struct Proxy
{
    std::string name;
    uint32_t port;
};

ProxyVec loadProxies(const std::string& fileName)
{
    std::FILE *f = fopen(fileName.c_str(), "r");
    if (!f) {
        std::clog << "[Error - loadProxies] Cannot open: " << fileName << "." << std::endl;
        delete f;
        f = NULL;
        return ProxyVec();
    }

    char buffer[1024];
    ProxyVec ret;
    int32_t __n = 0;
    while (fgets(buffer, sizeof(buffer), f)) {
        ++__n;
        std::string str(buffer);
        if (str.find("\n") != std::string::npos)
            str = str.substr(0, str.length()-1);

        if (str.find("\r") != std::string::npos)
            str = str.substr(0, str.length()-1);

        size_t sep = str.rfind(":");
        if (sep == std::string::npos) {
            std::clog << "[Error - loadProxies] Cannot load proxy #" << __n << "." << std::endl;
            continue;
        }

        std::string hostname = str.substr(0, sep);
        uint32_t port = static_cast<uint32_t>(std::atoi(str.substr(sep+1, str.length()-sep).c_str()));
        std::clog << "Loading proxy: " << hostname << ":" << port << "." << std::endl;
        Proxy proxy;
        proxy.name = hostname;
        proxy.port = port;
        ret.push_back(&proxy);
    }
    std::clog << "Loaded: " << __n << " proxies." << std::endl;
    return ret;
}

class Socket
{
    public:
        Socket(boost::asio::io_service& service, const std::string& host,
            const std::string& port, const std::string& targetHost, const std::string& targetPort);
        ~Socket();

        void write(const std::string& message);
        std::string receivedData() const;
        bool connected() const;
        void receive();
        void handle();

    private:
        struct SocketData
        {
            SocketData(boost::asio::io_service& service, const std::string& _host, const std::string& _port,
                const std::string& _targetHost, const std::string& _targetPort):
                socket(service),
                write(service),
                read(service),
                resolver(service),
                buffers(),
                host(_host),
                port(_port),
                targetHost(_targetHost),
                targetPort(_targetPort),
                connected(false)
            {
            }
            boost::asio::ip::tcp::socket socket;
            boost::asio::io_service::strand write, read;
            boost::asio::ip::tcp::resolver resolver;
            boost::array<char, 1024> buffers;
            std::string host, port;
            std::string targetHost, targetPort;
            bool connected;
        };
            // FIXME: Use shared_ptr instead.
        SocketData* d;

    protected:
        //handle resolve func
        void handle_resolve(const boost::system::error_code&,
            boost::asio::ip::tcp::resolver::iterator);

        //handle connection func
        void handle_connect(const boost::system::error_code&,
            boost::asio::ip::tcp::resolver::iterator);

        //handle write func
        void handle_write(const boost::system::error_code&, size_t);

        //handle read func
        void handle_read(const boost::system::error_code&, size_t);

    private:
        void connectionThread();
};

Socket::Socket(boost::asio::io_service& service, const std::string& host, const std::string& port,
    const std::string& targetHost, const std::string& targetPort)
    : d(new SocketData(service, host, port, targetHost, targetPort))
{
    boost::thread thread(boost::bind(&Socket::connectionThread, this));
    // FIXME: This function is blocking. The constructur will never exit.
    //        Use thread_group.join_all() as last line in main() instead.
    thread.join();
}

Socket::~Socket()
{
    d->socket.close();
    delete d;
    d = NULL;
}

void Socket::connectionThread()
{
    if (!d)
        return;

    if (d->connected)
        return;

    boost::asio::ip::tcp::resolver::query query(d->host, d->port);
    d->resolver.async_resolve(query,
        boost::bind(&Socket::handle_resolve, this,
            boost::asio::placeholders::error,
                boost::asio::placeholders::iterator));
}

void Socket::handle_resolve(const boost::system::error_code& e,
    boost::asio::ip::tcp::resolver::iterator ep_iter)
{
    if (!e) {
        boost::asio::ip::tcp::endpoint iter = *ep_iter;
        d->socket.async_connect(iter,
            boost::bind(&Socket::handle_connect, this,
                boost::asio::placeholders::error, ++ep_iter));
    } else {
        std::clog << "[Error - Socket::handle_resolve] " << e.message() << "." << std::endl;
    }
}

void Socket::handle_connect(const boost::system::error_code& e,
    boost::asio::ip::tcp::resolver::iterator ep_iter)
{
    if (!e) {
        std::cout << "[Notice - Socket::handle_connect] Connected to host." << std::endl;
        d->connected = true;
        write("CONNECT " + d->targetHost + ":" + d->targetPort + " HTTP/1.1\r\n\r\n");
        receive();
    } else if (ep_iter != boost::asio::ip::tcp::resolver::iterator()) {
        d->socket.close();
        boost::asio::ip::tcp::endpoint ep = *ep_iter;
        d->socket.async_connect(ep,
            boost::bind(&Socket::handle_connect, this,
                boost::asio::placeholders::error, ++ep_iter));
    } else {
        std::clog << "[Error - Server::handle_connect] " << e.message() << "." << std::endl;
    }
}

void Socket::handle_write(const boost::system::error_code& e,
    size_t bytes)
{
    assert(!e || bytes < 0);
}

void Socket::handle_read(const boost::system::error_code& e,
    size_t bytes)
{
    assert(!e || bytes < 0);
    std::cout << receivedData() << std::endl;
    receive();
}

void Socket::write(const std::string& message)
{
    boost::asio::async_write(d->socket, boost::asio::buffer(message),
        d->write.wrap(
            boost::bind(&Socket::handle_write, this,
                boost::asio::placeholders::error,
                    boost::asio::placeholders::bytes_transferred)));
}

std::string Socket::receivedData() const
{
    return std::string(d->buffers.data());
}

void Socket::receive()
{
    d->socket.async_read_some(boost::asio::buffer(d->buffers),
        d->read.wrap(
            boost::bind(&Socket::handle_read, this,
                boost::asio::placeholders::error,
                    boost::asio::placeholders::bytes_transferred)));
}

void Socket::handle()
{
    assert(!d->targetHost.empty());
    assert(!d->targetPort.empty());

    std::string str(d->buffers.data());
    std::clog << "Received: " << str << "." << std::endl;
    if (str.substr(0, 4) == "PING")
        write("PO" + str.substr(2) + "\r\n");
    else if (str.find("MODE") != std::string::npos)
        write("JOIN #OTland\r\n");
    else if (str.find("JOIN") != std::string::npos)
        write("PRIVMSG #OTland :Hello\r\n");
}

bool Socket::connected() const
{
    return d->connected;
}

void handler(const std::string& fileName, const std::string& host, const std::string& port, uint32_t threads);

int main(int argc, char **argv)
{
    if (argc < 5) {
        std::clog << "[Error - main] Usage: " << argv[0] << " <proxy_file> <host> <port> <threads>" << std::endl;
        return 1;
    }

    std::string file(argv[1]);
    std::string host(argv[2]);
    std::string port(argv[3]);
    uint32_t threads = static_cast<uint32_t>(std::atoi(argv[4]));
    if (!threads)
        threads = 1;

    for (uint32_t __i = 0; __i < threads; ++__i)
            // FIXME: Use the thread.join() there.
        handler(file, host, port, threads);
}

typedef std::vector<Socket*> SocketVec;

void handler(const std::string& fileName, const std::string& host,
    const std::string& port, uint32_t threads)
{
    assert(!fileName.empty());
    assert(!host.empty());
    assert(!port.empty());

    ProxyVec proxies = loadProxies(fileName);
    assert(proxies.size());

    SocketVec sockets;
    for (ProxyVec::const_iterator it = proxies.begin(); it != proxies.end(); ++it) {
        boost::asio::io_service io;
        Socket socket(io, (*it)->name, toString((*it)->port), host, port);
            // FIXME: socket is a local variable and it's address is invalid outside
            //        this loop -> memory leak -> seg-fault.
        sockets.push_back(&socket);
    }

    for (SocketVec::const_iterator it = sockets.begin(); it != sockets.end(); ++it) {
        if (!(*it)->connected())
            continue;

        (*it)->handle();
    }
    // FIXME: I'm not sure if I understand this architecture. A new thread is
    //        started with this function as handler ? Who waits until this new created
    //        thread is finished ? Where is the join() ?
    (void) new boost::thread(boost::bind(handler, fileName, host, port, threads));
}

A: I don't think this is your only problem, but in this snippet in handler, you're creating your Socket objects on the stack. Each Socket object that you create will be destroyed at the end of the for loop. This means that the objects in the sockets vector are invalid objects. Doing this may also corrupt the memory heap enough to produce the error that you're seeing.
SocketVec sockets;
for (ProxyVec::const_iterator it = proxies.begin(); it != proxies.end(); ++it) {
    boost::asio::io_service io;
    Socket socket(io, (*it)->name, toString((*it)->port), host, port);
    sockets.push_back(&socket);
}

Change this to:
SocketVec sockets;
for (ProxyVec::const_iterator it = proxies.begin(); it != proxies.end(); ++it) {
    boost::asio::io_service io;
    Socket* socket = new Socket(io, (*it)->name, toString((*it)->port), host, port);
    sockets.push_back(socket);
}

A: This answer was originally a comment to Dan's answer, but after looking at your code I felt compelled to give a full answer. You really need to take a closer look at the Boost.Asio examples and understand how they work. Pay special attention to the asynchronous examples, it doesn't look like you've grasped the concepts of object lifetime and how the handlers work. Particularly, you should master single threaded programs before jumping into multiple threads. When you've conquered that, you should use a thread pool invoking io_service::run instead of an io_service per thread. It will ultimately make your program's logic easier to understand.
You also should look into valgrind, there's a slew of errors in your code like this one:
==19853== Invalid read of size 4
==19853==    at 0x10000D0E4: handler(std::string const&, std::string const&, std::string const&, unsigned int) (in ./a.out)
==19853==    by 0x10000D5E6: main (in ./a.out)
==19853==  Address 0x7fff5fbff398 is not stack'd, malloc'd or (recently) free'd


text:
Q: Find area of surface Find area of surface given by
$$
z=x^2-2x+y^2
$$
where
$$
(x-1)^2+y^2 \leq 4
$$
Edit: Initial thought was to use surface-integral, and using the formula
$$
dS = \sqrt{1+(\frac{\partial z}{\partial x})^2 + (\frac{\partial z}{\partial y})^2}dxdy
$$
Doing this, I got:
$$
dS=\sqrt{4x^2-8x+4y^2+5}dxdy
$$
but I'm unsure what to do next. Any help with my problem and/or how to solve would be appreciated, thanks.

A: $$
dS = \sqrt{1+(\frac{\partial z}{\partial x})^2 + (\frac{\partial z}{\partial y})^2}dxdy
$$
Using
$$
\frac{\partial z}{\partial x}=2x-2, \frac{\partial z}{\partial y}=2y,
$$
$$
dS=\sqrt{4x^2-8x+4y^2+5}dxdy
$$
Change variables to polar coordinate system $$(x,y)=(1+rcosθ,rsinθ)$$
$$
dS=\sqrt{4r^2+1}drdθ
$$
Final integral is:
$$
\int_{0}^{2\pi}\int_{0}^{2} \sqrt{4r^2+1}\cdot rdrdθ
$$
which gives the final answer:
$$
\frac{\pi}{6}\cdot(17\sqrt{17}-1)
$$
Thanks to everyone for their help.


text:
Q: Implementing mib2c template for scalar I am trying to get the mib2c template code to work for a simple scalar, but continue to get MY-MIB::mibName = No such object available on this agent at this OID upon a snmpget request no matter what I do.
When generating the mib2c template code I choose the net-snmp -> scalar options. From there I have tried options 1 and 2.
My understanding of the option 2 template is that you shouldn't even have to change any of the code to get it to successfully return a zero value for scalars.
However, the debug messages show that the init_* functions are getting called but the handlers are not getting called at all.
I am wondering if anyone can point me to resources showing a successful implementation example of the mib2c generated code as I am fairly lost at this point.
Thanks!


text:
Q: How can I create a Locale with a specific script code? I'm trying to convert this String az_AZ_#Latn, found here, to a Locale but I'm unable to parse the #Latn part.
If I do new Locale("az_AZ_#Latn") I lose the #Latn part (the Script code).
I've tried as well using the LocaleUtils from commons-lang but I get an error saying that it's an invalid format.

A: That #Latn refers to the script which in this case is Latin.
From java documentation:

script
ISO 15924 alpha-4 script code. You can find a full list of valid script codes in the IANA Language Subtag Registry (search for "Type: script"). The script field is case insensitive, but Locale always canonicalizes to title case (the first letter is upper case and the rest of the letters are lower case).
Well-formed script values have the form [a-zA-Z]{4}
Example: "Latn" (Latin), "Cyrl" (Cyrillic)

If you want to create a Locale using the script you can use its builder.
For instance:
Locale locale = new Locale.Builder()
                    .setLanguage("az")
                    .setRegion("AZ")
                    .setScript("Latn")
                    .build();

A: Locale.Builder is able to handle script information for locales. The documentation of the Builder class also includes this example code:
Locale aLocale = new Locale.Builder().setLanguage("sr")
                                     .setScript("Latn")
                                     .setRegion("RS")
                                     .build();

By using the builder you would have to do the splitting of the string yourself and also removal of any unsupported characters like #.
Using the 3-arg contructor java.util.Locale.Locale(String, String, String) is not correct since you probably don't intend to specify a variant using Latn but a script instead.

A: If the format is consistent (your input looks always the same) you can split by # and by _ and get the parts.
See the following example:
var input = "az_AZ#Latn"
var lns = input.split("#")
var l = lns[0].split("_")
var locale = new Locale.Builder()
                 .setLanguage(l[0])
                 .setRegion(l[1])
                 .setScript(lns[1])
                 .build()

locale.getLanguage() // ==> "az"
locale.getCountry() // ==> "AZ"
locale.getScript() //==> "Latn"

A: As written in the docs:

It is not possible to set a script code on a Locale object in a
release earlier than JDK 7.

But you can use the Locale builder to make it like this:
Locale locale = new Locale.Builder().setLanguage("az").setRegion("AZ").setScript("Latn").build();

You can get the Script it by calling locale.getScript()
Edit:
Here's a method I made for converting a string into a locale (doesn't work for extensions):
public static Locale stringToLocale(String locale){
    if(locale == null || locale.isEmpty()) return null;
    String[] parts = locale.split("_");
    if(parts.length == 1) return new Locale(parts[0]);
    if(parts.length == 2) return new Locale(parts[0],parts[1]);
    if(parts.length == 3)
        if(parts[2].charAt(0) != '#') return new Locale(parts[0],parts[1],parts[2]);
        else return new Locale.Builder().setLanguage(parts[0]).setRegion(parts[1]).setScript(parts[2].substring(1)).build();
    if(parts.length == 4) return new Locale.Builder().setLanguage(parts[0]).setRegion(parts[1]).setVariant(parts[2]).setScript(parts[3].charAt(0)=='#'? parts[3].substring(1):null).build();
    return null;
}
    //works for the toString output expect for extensions. test: for(Locale l:  Locale.getAvailableLocales()) System.out.println(l.equals(stringToLocale(l.toString())));
   // output : true true true...

usage:
Locale l = stringToLocale("az_AZ_#Latn");


text:
Q: Perl hex string to binary string I'm trying to convert a string of hex digits to a binary string.  If my input string is 41424344, then I would want the string to store "ABCD".  How can this be done?

A: You can do it without using regex with help of pack:
print pack 'H*', '41424344';

Output:
ABCD

A: The canonical method is
$input_string =~ s/(..)/chr(hex($1))/ge;

This reads two characters at a time from the input, calling hex (converting a hexidecimal number to a decimal number) and then chr (converting a decimal number to a character) on each input.

A: s/([a-f0-9][a-f0-9])/chr(hex($1))/egi;


text:
Q: How to read rows from Lucene.Net's index files I am using Lunece.net 2.0.5 version.
I want to open and display all the records in the index file in a grid (table) format in an ASP.NET web application, and also provide edit option for each cell in that grid.
But I don't know how to read each row from Index file.
I used code below-
   private List<String> GetIndexTerms(string indexFolder)
        {
            List<String> termlist = new List<string>();
            IndexReader reader = IndexReader.Open(indexFolder, false);
            TermEnum terms = reader.Terms();
            while (terms.Next())
            {
                Term term = terms.Term();
                String termText = term.Text();
                int frequency = reader.DocFreq(term);
                termlist.Add(termText);
            }
            reader.Close();
            return termlist;
        }

but it returns list of each term and here I am unable to aggregate data by each row (record).
Let me know if there is way to read file by each row or I need to update version of Lucene that I am currently using.
Also please provide any links to Lucene.net's better documentation websites.

A: You can read all the records/rows (documents in Lucene terminology) directly from the index without  searching
var reader =  IndexReader.Open(dir);
for (int i = 0; i < reader.MaxDoc(); i++)
{
    if (reader.IsDeleted(i)) continue;

    Document d =  reader.Document(i);
    var fieldValuePairs =  d.GetFields()
                            .Select(f => new {
                                  Name = f.Name(),
                                  Value = f.StringValue() })
                            .ToArray();
}

PS: v2.0.5 is very old. try latest & greatest Lucene.Net


text:
Q: What triggers the trade tab to appear? I restarted with 110 kittens (yay for 40 paragon!) and am really missing my trading. I can't seem to find anywhere on the wiki or even in the code how to make my trade tab appear.
What trigger makes the trade tab show up on my tab bar?

A: The trading tab is unlocked the moment it is useful; specifically, it unlocks once the first race sends an emissary to your village. This leads to the obvious problem that you need the Explore button on that tab to unlock more. Therefore, the game helps you out a bit; on reaching Year 20, a single race is unlocked for trade, for free, which then unlocks the trading tab to discover more.


text:
Q: Amazon SNS: Does it handle Google Cloud Messaging Canonical Ids? I was going through Google Cloud Messaging documentation and I came across this section:
http://developer.android.com/google/gcm/adv.html#canonical

Canonical IDs
If later on you try to send a message using a different registration ID, GCM will process the request as usual, but it will include the canonical registration ID in the registration_id field of the response. Make sure to replace the registration ID stored in your server with this canonical ID, as eventually the ID you're using will stop working.

How do we handle the Canonical Id update while using Amazon SNS Endpoint ANRs?
I checked the Amazon API documentation for
CreatePlatformEndpoint: http://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformEndpoint.html
and
Publish: http://docs.aws.amazon.com/sns/latest/api/API_Publish.html
Please suggest. Thanks!

A: you can not get Canonical IDs via SNS ,but you can get it via Google GCM REST Api youself.
see this:GCM with PHP (Google Cloud Messaging)
result will have Canonical IDs.


text:
Q: Is there any noun in English which changes the first letter in the plural? Plenty of nouns change the second letter to become plural (man->men, goose->geese) but does anything change its first letter.  I've hunted high and low over the internet, and spent ages browsing the questions at Oxford dictionaries but I can't find anything.

A: The only one I could find is cow/kine.
However, kine is mentioned as an archaic plural of cow in most dictionaries including OED but Wikipedia and Wiktionary mentions as regional or dialectal also.
Wordsmith does not count it as archaic and includes a contemporary usage:

Kine is one of the very few words in English (other examples: I/we, me/us) that have no letters in common with its singular form, cow. It is pluralized using the -n marker, as in the words children, brethren, and oxen.
"Cows stood belly deep in a ranch pond, doing their impersonation of the kine in John Constable's paintings."
  Verlyn Klinkenborg; Water and Grasses; The New York Times; Jul 5, 2010.

Interestingly, kine is a double plural also because an extra suffix has been added to Middle English plural form ki (ky) or kie (kye):

The word "cow" came via Anglo-Saxon cū (plural cȳ), from Common Indo-European gʷōus (genitive gʷowés) = "a bovine animal", compare Persian gâv, Sanskrit go-, Welsh buwch. The plural cȳ became ki or kie in Middle English, and an additional plural ending was often added, giving kine, kien, but also kies, kuin and others. This is the origin of the now archaic English plural of "kine". The Scots language singular is coo or cou, and the plural is "kye".
[Wikipedia]

A: I'm not sure whether pronouns count: "I" versus "We".
There are also some prefixes: e.g. "byte" versus "kilobyte"; and "ester" versus "polyester"; and possibly "pole" versus "dipole".

A: The Equatorial Guinean currency, the ekwele, has plural bipkwele.

A: I guess there are some that only describe plurals, so you'd have to use another word if you wanted to express singular: poultry, livestock, folk(s).


text:
Q: Как удалить дублирующие товары, но 1 оставить? delete product
group by name
having count(*) > 1

A: WITH CTE AS (
    SELECT name, ROW_NUMBER() OVER(PARTITION BY name ORDER BY name) rnk
    FROM product
     )
DELETE FROM CTE
WHERE rnk > 1;

A: Первое самое простое что приходит в голову, это записать данные во временную таблицу дистинком, потом удалить и снова вставить. Совсем не оптимально, но если табличка небольшая будет работать быстро.
select distinct name INTO #temp from product

delete product
group by name
having count(*) > 1

insert into product
select * from #temp

drop table #temp


text:
Q: How to dynamic add image/imagebutton in android listview or gridview I have a list of emotion icons(over 100 icons).
And I would like to display in a view that people can click it and toast what he is clicking.

Now, I have some confusing points:
1) What views should I use to include all this icons (GridView or ListView)?
2) How to dynamic add them or add them pro-grammatically? If I declare each one by one, I think it is no good. But any other ideas?
All the images icons is in drawable folder.
Thanks.

A: GridView would be better in this case with a PopupWindow. Take a HashMap and store the name of the smiley as String and its Image as Resource Id.
eg:-
HashMap<String, Integer> map = new  HashMap<String, Integer>();
map.put("smile", R.drawable.smile);
....

Now, Iterate through all the values(images) of HashMap and poplulate your GridView from the HashMap values(images).
And, inside Adapter class you can show images using map.get(key); to ImageView and set the Resource.
UPDATE:
I had just created a small demo for the same you can check it from here.


text:
Q: Nothing happens when trying to upgrade from Linux Mint 12 to 13 I am trying to upgrade from Linux Mint 12 to 13 using apt-get. After running the following commands, nothing seems to happen. I am fairly new to linux, what am I doing wrong?
user@olympus /etc/default $ sudo apt-get dist-upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

user@olympus /etc/default $ sudo apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

A: Clem, the Linux Mint dev, recommends a different method to upgrade. Mint has a few specialized tools that make porting your data and settings to a new installation much easier.
Doing a clean install is generally a good idea. An update may go smoothly but you are also likely to have problems. If you do, the comments here may help.
Having said that, if you still want to use apt, edit (as root, sudo) your /etc/apt/sources.lst to point to the latest release:
deb http://packages.linuxmint.com/ maya main upstream import
deb http://archive.ubuntu.com/ubuntu/ precise main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu/ precise-updates main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu/ precise-security main restricted universe multiverse
deb http://archive.canonical.com/ubuntu/ precise partner
deb http://packages.medibuntu.org/ precise free non-free

Save the file and then run the following commands:
$ sudo apt-get update
$ sudo apt-get dist-upgrade

Finally, reboot your computer.


text:
Q: Handling registration ID changes in Google Cloud Messaging on Android In the docs on Google Cloud Messaging, it states:

The Android application should store this ID for later use (for
  instance, to check on onCreate() if it is already registered). Note
  that Google may periodically refresh the registration ID, so you
  should design your Android application with the understanding that the
  com.google.android.c2dm.intent.REGISTRATION intent may be called
  multiple times. Your Android application needs to be able to respond
  accordingly.

I register my device using the following code:
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String regID = gcm.register(senderID);

The GoogleCloudMessaging class encapsulates the registration process. So how am I suppose to handle com.google.android.c2dm.intent.REGISTRATION since handling that is done internally by the GoogleCloudMessaging class?

A: Reading the new InstanceID API, I found more info on when the token might change:

Your app can request tokens from the Instance ID service as needed
  using the getToken() method, and like InstanceID, your app can also
  store tokens on your own server. All tokens issued to your app belong
  to the app's InstanceID.
Tokens are unique and secure, but your app or the Instance ID service
  may need to refresh tokens in the event of a security issue or when a
  user uninstalls and reinstalls your app during device restoration.
  Your app must implement a listener to respond to token refresh
  requests from the Instance ID service.

More details:

The Instance ID service initiates callbacks periodically (for example,
  every 6 months), requesting that your app refreshes its tokens. It may
  also initiate callbacks when:

*

*There are security issues; for example, SSL or platform issues.

*Device information is no longer valid; for example, backup and    restore.

*The Instance ID service is otherwise affected.

Sources:
https://developers.google.com/instance-id/
https://developers.google.com/instance-id/guides/android-implementation

A: After scrubbing through tonnes of misleading answers across the net, including SO, the only place I found a complete answer was as remarked by Eran's answer and here:
While automatic registration refresh might or might never have happened, google describes a simiple algorithm to handle the canocical_ids by parsing successful response:
If the value of failure and canonical_ids is 0, it's not necessary to parse the remainder of the response. Otherwise, we recommend that you iterate through the results field and do the following for each object in that list:

If message_id is set, check for registration_id:
If registration_id is set, replace the original ID with the new value (canonical ID) in your server database. Note that the original ID is not part of the result, so you need to obtain it from the list of code>registration_ids passed in the request (using the same index).
Otherwise, get the value of error:
If it is Unavailable, you could retry to send it in another request.
If it is NotRegistered, you should remove the registration ID from your server database because the application was uninstalled from the device or it does not have a broadcast receiver configured to receive com.google.android.c2dm.intent.RECEIVE intents.
Otherwise, there is something wrong in the registration ID passed in the request; it is probably a non-recoverable error that will also require removing the registration from the server database. See Interpreting an error response for all possible error values.

From aforementioned link.

A: That's an interesting question.
Google encourage you to switch to the new registration process :

An Android application running on a mobile device registers to receive messages by calling the GoogleCloudMessaging method register(senderID...). This method registers the application for GCM and returns the registration ID. This streamlined approach replaces the previous GCM registration process.

The note that says Google may periodically refresh the registration ID only appears on the page that still shows the old registration process, so it's possible that this note is no longer relevant.
If you want to be safe, you can still use the old registration process. Or you can use the new process, but have in addition the code that handles the com.google.android.c2dm.intent.REGISTRATION intent, in order to make sure you are covered if Google do decide to refresh the registration ID.
That said, I never experienced such a refresh, and even when I did experience a change in the registration ID (usually as a result of sending a notification after un-installing the app and then re-installing it), the old registration ID still worked (resulting in a canonical registration ID sent in the response from Google), so no harm was done.
EDIT (06.06.2013) :
Google changed their Demo App to use the new interface. They refresh the registration ID by setting an expiration date on the value persisted locally by the app. When the app starts, they load their locally stored registration id. If it is "expired" (which in the demo means it was received from GCM over 7 days ago), they call gcm.register(senderID) again.
This doesn't handle the hypothetical scenario in which a registration ID is refreshed by Google for an app that hasn't been launched for a long time. In that case, the app won't be aware of the change, and neither will the 3rd party server.
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    mDisplay = (TextView) findViewById(R.id.display);

    context = getApplicationContext();
    regid = getRegistrationId(context);

    if (regid.length() == 0) {
        registerBackground();
    }
    gcm = GoogleCloudMessaging.getInstance(this);
}

/**
 * Gets the current registration id for application on GCM service.
 *

 * If result is empty, the registration has failed.
 *
 * @return registration id, or empty string if the registration is not
 *         complete.
 */
private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.length() == 0) {
        Log.v(TAG, "Registration not found.");
        return "";
    }
    // check if app was updated; if so, it must clear registration id to
    // avoid a race condition if GCM sends a message
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion || isRegistrationExpired()) {
        Log.v(TAG, "App version changed or registration expired.");
        return "";
    }
    return registrationId;
}

/**
 * Checks if the registration has expired.
 *
 *
To avoid the scenario where the device sends the registration to the
 * server but the server loses it, the app developer may choose to re-register
 * after REGISTRATION_EXPIRY_TIME_MS.
 *
 * @return true if the registration has expired.
 */
private boolean isRegistrationExpired() {
    final SharedPreferences prefs = getGCMPreferences(context);
    // checks if the information is not stale
    long expirationTime =
            prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1);
    return System.currentTimeMillis() > expirationTime;
}

EDIT (08.14.2013) :
Google changed their Demo App again (two days ago). This time they removed the logic that considers the Registration ID to be expired after 7 days. Now they only refresh the Registration ID when a new version of the app it installed.
EDIT (04.24.2014) :
For the sake of completeness, here are the words of Costin Manolache (taken from here), a Google developer involved in the development of GCM, on the matter :

The 'periodical' refresh never happened, and the registration refresh
  is not included in the new GCM library.
The only known cause for registration ID change is the old bug of apps
  getting unregistered automatically if they receive a message while
  getting upgraded. Until this bug is fixed apps still need to call
  register() after upgrade, and so far the registration ID may change in
  this case. Calling unregister() explicitly usually changes the
  registration ID too.
The suggestion/workaround is to generate your own random identifier,
  saved as a shared preference for example. On each app upgrade you can
  upload the identifier and the potentially new registration ID. This
  may also help tracking and debugging the upgrade and registration
  changes on server side.

This explains the current implementation of the official GCM Demo application.
com.google.android.c2dm.intent.REGISTRATION should never be handled when using the GoogleCloudMessaging class to register.


text:
Q: When may we ignore the limits of integration? When we try to evaluate an integral such as, say
$$\int_a^b{f(x)dx}$$
there is often the case that we can analytically find
$$\int{f(x)dx}$$
a little faster (imagine leaving away the evaluation for specific terms for partial integrations, if you lack an example. Partially integrating forces you to evaluate two terms instead of one all of the sudden).
Therefore, I feel tempted to leave away the limits of integration in general and evaluating it at the very end, to save some time.
Unfortunately, I'm not sure if this holds for every scenario. Think of integration by substitution, where the limits might change due to substituting.
And so, I want to ask: When exactly can I just ignore the limits of integration and apply them to an indefinite integral instead?
If you're having trouble to understand the difference, just give
$\int_0^{\pi}{e^x\cdot cos(x)dx}$ a try. Finding $\int{e^x\cdot cos(x)dx}$ is easy, but trying to find $\int_0^{\pi}{e^x\cdot cos(x)dx}$ directly (using partial integration and evaluating all the terms mid-way) is somewhat cumbersome.

A: Alright, I'll try to answer it myself, now that the question has been discussed in the comments. Thanks a lot to Travis and André Nicolas!
In general, we may always ignore the limits of integration. This is easily justifiable by the Fundamental Theorem of Calculus:
$$\int_a^bf(x)\,dx = F(b) - F(a) = \left[ F(x) \right]_a^b = \left[ \int f(x)\,dx \right]_a^b $$
given that $f$ is well-behaved on $[a, b]$.
Note, though, that there are some definite integrals that we can solve exactly without being able to express their anti-derivatives in terms of elementary functions (thanks, Travis).


text:
Q: Latest 4 posts excluding category, append latest post from excluded category I need to build an 'announcement' banner showing the 5 latest posts, of which one MUST be the latest newsletter.
What I want to do: latest 4 posts excluding newsletter category + latest newsletter post as the 5th post.
How is this possible?
I have tried tax_query, but then it only shows the newsletter category, and does not limit that specific category.
I have tried excluding all post IDs from the newsletter category, but then if there are no newsletters in the latest 5 posts, it does not show the latest newsletter at all.
Code:
$category_id = get_cat_ID('Newsletter');
$latest_newsletter = query_posts("cat=$category_id&order_by=date");
$exclude_ids = [];
$count = 0;
while (have_posts()) : the_post();
    $post = get_post();
    if($count > 0) {
        $exclude_ids[] = $post->ID;
    }
    $count++;
endwhile;
wp_reset_query();
query_posts(['posts_per_page' => '4', 'order_by' => 'date', 'post__not_in' => $exclude_ids]); if (have_posts()) : ?>

ANNOUNCEMENT

            <?php while ( have_posts() ) : the_post(); ?>

<a href="<?php the_permalink(); ?>" title="Continue reading"> continue reading...
                    <?php the_title(  ); ?>

            <?php endwhile; ?>

Any ideas?

A: You can create two separate query objects to achieve what you want.
e.g
 //this is just an example not complete code
// write you actual query in the array passed to WP_Query
 $latest_articles = new WP_Query( array('order' => 'DESC', 'posts_per_page ' => 4) );

while ( $latest_articles->have_posts() ) :
    // Loop over the posts and show the content

 $newletter_article = new WP_Query( array('order' => 'DESC', 'posts_per_page'=> 1, 'cat' => 1 ) );

while ( $newletter_article->have_posts() ) :
 //show the newletter article


text:
Q: Declined Not an Answer flag First, I apologize for yet another declined flag post.
However, this question specifically states: "I don't need to be able to go from string to value again." And this answer specifically answers that (how to go from a string to the value).
Seeing how the question has 10 other useful answers, I thought that one that went against the grain didn't need to add more bulk - therefore I flagged it.
I didn't use the "other" option when flagging, however, I left what I believe is a constructive and useful comment explaining why it wasn't an appropriate answer.
And yet, the flag is declined with "flags should not be used to indicate technical inaccuracies, or an altogether wrong answer."
Am I mistakenly taking the flag description (...it does not attempt to answer the question) a little bit too literal?

A: I declined that flag, for pretty much the reasons that everyone has mentioned in the comments above.
"Not an answer" flags should be on answers that we can tell at a glance aren't attempts to answer the question. This includes "me too" responses, complete gibberish, or questions being asked within answers. We've become more strict with these flags, now that they're being used to seed review audit test cases. In general, if we have to read the entire question to understand why something isn't an appropriate answer, "not an answer" isn't a good flag to use here.
Also, remember that what you're asking us to do with this flag is to unilaterally delete content someone has provided. I'm going to lean towards giving the answerer the benefit of the doubt in these cases, particularly if it's in an area that I'm not as familiar with. I did read your comment, but still couldn't see enough there to cause me to delete the answer.
Sorry about the declined flag, but hopefully you can see what I was thinking here.


text:
Q: Add particles on button click in unity I am new to unity 3d, I have to do some enhancement in exiting project.. if user choose correct option then I have to show some particles around the button at runtime.
My code for adding particles is below ..not working:
ParticleSystem ps = GetComponent<ParticleSystem>();
ps.Play ();

I have also added particles component from unity editor..
Thanks in advance
Edit :
as @kardux suggested:
declaration :
[SerializeField] private ParticleSystem ps;

on method :
ps.Play()

Screenshot from inspector:

Error:
I/Unity   (23313): NullReferenceException
I/Unity   (23313):   at UnityEngine.ParticleSystem.<Play>m__0 (UnityEngine.ParticleSystem ps) [0x00001] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3666
I/Unity   (23313):   at UnityEngine.ParticleSystem.IterateParticleSystems (Boolean recurse, UnityEngine.IteratorDelegate func) [0x00003] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3780
I/Unity   (23313):   at UnityEngine.ParticleSystem.Play (Boolean withChildren) [0x00020] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3666
I/Unity   (23313):   at UnityEngine.ParticleSystem.Play () [0x00005] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3661

A: First of all if you're using particles inside Unity UI I highly advise you looking to UIParticleSystem.cs script from Unity UI Extension repository: this is a community gathering of many useful UI tools :)
(simply don't forget to add the UI/Particles/Hidden shader that you can find here)
You can change the sprite you want to use here:

Also keep in mind when using this script that you will have to scale your particles according to your screen (particles are initialized at a size of 1 because that's 1 meter in Unity 3D world: but now you will probably be in canvas space which will be something like 1920x1080px so 1px will be very small). You can find some base settings below:

Now coming to your scrip I suspect you simply have to call Stop() before Play() like this (note I used a burst emission type in my particle system settings):
ParticleSystem ps = GetComponent<ParticleSystem>();
ps.Stop ();
ps.Play ();

P.-S. Please note that if you use UIParticleSystem script you will have to consider your particles system as an UI item (will be rendered on top of other items based on hierarchy order)
Hope this helps,
EDIT:
You have two ways of setting up your GameObjects:

*

*you have all component on the same GameObject (ParticleSystem, UIParticleSystem and YOUR_SCRIPT): this way you can get the ParticleSystem reference by calling GetComponent<ParticleSystem>() inside your script

*you have one particle GameObject (with ParticleSystem and UIParticleSystem) and YOUR_SCRIPT is on another GameObject: you can't call GetComponent<ParticleSystem>() in your script since it will search on the components of this GameObject so you declare a ParticleSystem ps; variable (either public or [SerializeField] private) that you assign through the Inspector by dragging your particle GameObject to it.
Note that implicitly, GetComponent<ParticleSystem>() equals this.gameObject.GetComponent<ParticleSystem>(): that's why it will search components from the current GameObject.
EDIT 2:
Not sure why your script throw this NullReference exception: I just tried with a very short script and it works perfectly...
public class TestScript: MonoBehaviour
{
    [SerializeField]
    private ParticleSystem ps;

    void Start()
    {
        // This one is not even needed
        ps.Stop();
    }

    public void PlayParticles()
    {
        ps.Stop();
        ps.Play();
    }
}

A: Provided you have a particle system on the same gameObject as the script that is calling it, it should be fine.
Are you using a UI button? If so, have a look here..
http://answers.unity3d.com/questions/852397/particle-system-in-46-ui.html
It's old but still relevant.

A: Are you using the New Unity UI System or GUI, Is the UI worldspace?

*

*Create a empty gameobject - attach the particle to that.

*Whenever you want emit particles call Gameobject.SetActive(true);

*Make sure Play on Awake option is checked in the particle system.

Set the position of the particle according to your UI.

A: public GameObject particle;
//include the particle in the gameobject

void Start() {
  particle.SetActive(false);
 }

void button() {
 particle.SetActive(true);
}

//this works.


text:
Q: Find and Paste in different workbook I'm doing a report in my office. Struckup in one point, so need your help or suggestions on that.
I have 3 different worksheet contains the "Emp Name" and their " Emp ID". (note: the order is not same order).
If i enter the working hours in one sheet (ie) in the third column, the same working hours want to replicate in other sheet as well. Kindly advise me the solution.
Please find the below as an example.
In Work Sheet 1:
Name    Emp ID
AAA     123456
BBB     154658
CCC     178954

In Work Sheet 2:
Name    Emp ID
BBB     154658
CCC     178954
AAA     123456

I have the below code, but its copy and pate whole data from Worksheet1 to Worksheet2 which is already existing in a particular folder. I required to copy and pate the third and fouth column to Worksheet2 from Worksheet1, but the name and emp id is not same as per the Worksheet1.
Sub copydata()
    Dim wkbSource As Workbook
    Dim wkbDest As Workbook
    Dim shttocopy As Worksheet
    Dim wbname As String
    ' check if the file is open
    ret = Isworkbookopen("H:\Srikanth\Book2.xlsm")
    If ret = False Then
        ' open file
        Set wkbSource = Workbooks.Open("H:\Srikanth\Book2.xlsm")
    Else
        'Just make it active
        'Workbooks("C:\stack\file1.xlsx").Activate
        Set wkbSource = Workbooks("Book2.xlsm")
    End If
    ' check if the file is open
    ret = Isworkbookopen("H:\Srikanth\Book1.xlsx")
    If ret = False Then
        ' open file
        Set wkbDest = Workbooks.Open("H:\Srikanth\Book1.xlsx")
    Else
        'Just make it active
        'Workbooks("C:\stack\file2.xlsx").Activate
        Set wkbDest = Workbooks("Book1.xlsx")
    End If
    'perform copy
    Set shttocopy = wkbSource.Sheets("filedata")
    shttocopy.Copy wkbDest.Sheets(3)
End Sub
Function Isworkbookopen(filename As String)
    Dim ff As Long, ErrNo As Long
    Dim wkb As Workbook
    Dim nam As String
    wbname = filename
    On Error Resume Next
    ff = FreeFile()
    Open filename For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0
    Select Case ErrNo
        Case 0 : Isworkbookopen = False
        Case 70 : Isworkbookopen = True
        Case Else : Error ErrNo
    End Select
End Function

A: It will be pretty simple if use VLOOKUP to achieve the same rather than writing VBA code.
Advantage of using formula will be:

*

*Easier to edit and understand

*Faster result and it will be light weight.


text:
Q: Using QPython Console with MIT App Inventor I am new to Android development and am using MIT App Inventor 2, as I was completely lost in the official Android development tutorials. Below is the description of the program and the problem.
I am taking an unknown number of inputs from the user (from a listPicker), which are then saved to a global list. I want to run a python code with arguments sourced from this global list. The python code then churns this data along with input from 3 other text files, and returns back a list which I want to display in the app.
I have created both the android app and the python code, but I need to link them somehow. I tried Skulpt, but I am not sure how to get the 3 files to be read into python using that. I also tried Activity Starter, but can't figure out how to get that to fire up the QPython to execute the python script with these files, and give back the output.
Any suggestions to do this, or any other tools which can be used are welcome.


text:
Q: Access nested JSON object value using java {
    "files": {
        "f1.png": {
            "intext": "A",
            "inval": 0,
            "inbinary": false
        },
        "f2.png": {
            "intext": "A",
            "inval": 0,
            "inbinary": true
        }
    }
}

How to access value of inval when the f1.png value is not fixed. i.e. the name of file can be anything, its not known so how can I access value for inval field for various files in this JSON using Java?

A: Please try below code,
import org.json.JSONException;
import org.json.JSONObject;
public static void main(String[] args) {
        String jsonString = "{\"files\": {\"f1.png\": {\"intext\": \"A\",\"inval\": 0,\"inbinary\": false}, \"f2.png\": {\"intext\": \"A\",\"inval\": 0,\"inbinary\": true}}}";
        try {
            JSONObject jsonObject =new JSONObject(jsonString);
            JSONObject jsonChildObject = (JSONObject)jsonObject.get("files");
            Iterator iterator  = jsonChildObject.keys();
            String key = null;
            while(iterator.hasNext()){
                key = (String)iterator.next();
                System.out.println("inval value: "+((JSONObject)jsonChildObject.get(key)).get("inval"));
            }
        }
        catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Hope it solves your issue

A: Using Jackson and JsonNode, you'd do:
private static final ObjectReader READER = new ObjectMapper()
    .getReader;

// blah

// read the node
final JsonNode node = READER.readTree(fromWhatever);

// access the inner "files" member
final JsonNode filesNode = node.get("files");

to access the inner object.
Then to walk the filesNode object you'd do:
final Iterator<Map.Entry<String, JsonNode>> iterator = filesNode.fields();
Map.Entry<String, JsonNode> entry;
while (iterator.hasNext()) {
    entry = iterator.next();
    // the "inval" field is entry.getValue().get("inval")
}

If you can use this project this becomes more simple:
// or .fromFile(), .fromReader(), others
final JsonNode node = JsonLoader.fromString(whatever);

final Map<String, JsonNode> map = JacksonUtils.nodeToMap(node.get("files"));
// walk the map

A: You can use JsonPath library to access child elements.
https://github.com/json-path/JsonPath
It can be as simple as
List<String> names = JsonPath.read(json, "$.files.*);

With some modifications.

A: You can use ObjectMapper.
First create a class Image.
import lombok.Data;

@Data
public class Image {

    private String intext;
    private Integer inval;
    private Boolean inbinary;

}

and convert to Map
final ObjectMapper objectMapper = new ObjectMapper();
final String jsonString =
      "{\"files\": {\"f1.png\": {\"intext\": \"A\",\"inval\": 0,\"inbinary\": false}, \"f2.png\": {\"intext\": \"A\",\"inval\": 0,\"inbinary\": true}}}";
  final Map<String, Map<String, Image>> output =
      objectMapper.readValue(
          jsonString, new TypeReference<Map<String, Map<String, Image>>>() {});

Thanks.

A: for nested array type,
{
"combo":    [
                {"field":"divisions"},
                {"field":"lob"}
]

}
 below code will help.
Iterator<?> keys = jsnObj.keys();

    while(keys.hasNext()) {
        String key = (String) keys.next();
        JSONArray list = (JSONArray) jsnObj.get(key);
        if(list==null || list.length()==0)
            return null;
        List<String> comboList = new ArrayList<String>();
        for(int i=0;i<list.length();i++){
            JSONObject jsonObject =  (JSONObject)list.get(i);
            if(jsonObject==null)
                continue;
            comboList.add((String)jsonObject.get("fields"));
        }
    }


text:
Q: Virtual Document Root For Many Community Sites I think I have a weird/complicated situation but I think I'm overlooking something simple. We are setting up a Yii application that will host other "skins" people set up. It's basically one big community but on many different sites. Everything will be handled by one single common core Yii application.
Our plan is to allow two different URL configurations depending on what the skin owner wants to do:
1) whatever.theirsite.com (which is set up as a CNAME to portal.oursite.com - for advanced users)
2) portal.oursite.com/theircommunity - for those who just want it to work with no other configuration
In the first case, it's easy enough to pick out the SERVER_NAME variable, look up the correct theme in the database, and serve up the correct theme/community. I have actually done this in the past and it works fine. However, I'm a little lost on the second case. I can still do the db lookup to find out what theme to serve from portal.oursite.com/theircommunity, but all the routing gets screwed up because theircommunity is not a controller. It's more like a virtual directory but its dynamic. I feel like I'm missing a simple htaccess or possibly a UrlManager rule.
Valid example urls would be:
http://whatever.theirsite.com/mycontroller/myaction
http://portal.oursite.com/theircommunity/mycontroller/myaction

or for a module:
http://whatever.theirsite.com/mymodule/mycontroller/myaction
http://portal.oursite.com/theircommunity/mymodule/mycontroller/myaction

In all cases, both pairs of requests need to go to the same place. Backend processing ensures that they look different but are handled by the same code.
Any advice?
Edit:
One solution I thought of but haven't tested yet (not sure if it is a good idea or not, or if it would even work) would be to extend the URL manager to add new routing rules depending on which community is being asked for.
ex:

*

*before application runs, do a db lookup to figure out which theme we
are using.

*if the theme uses a virtual root, then copy all existing url manager rules but append theircommunityname/ to the front of them.

A: Interesting question! I may be way off mark here. But would something like this work?
/portal.oursite.com
  /theircommunity1/index.php
  /theircommunity2/index.php

In words: create a user-specific subdirectory of your webroot.
This means that user 1 will have the /theircommunity1/index.php entry script. User 2 will have /theircommunity2/index.php. In the entry scripts your can

*

*Set user specific variables

*include a 'secondary' entry script that may be outside the webroot.

A: Yes, I think your edit/URL manager setup is probably going to be your best option.
For what it's worth, those routing rules are going to look similar to the module routing rules, so you might be able to fake load a module that has the appropriate name using an app behavior. I did something similar for a client last year; it worked, but was complex. I would suggest your start getting comfortable writing unit tests against this system, you'll want them to make sure you don't break things in the future :-)

A: I'm not sure I understood your scenario correctly. You can extend UrlManager and create some variable based on the site lookup. Eg $_GET['site'] = 'theircommunity'; and you can check for this variable later on your application.

A: This actually ended up having a simple solution but it took me a while to find it.  It was simply a matter of extending CHttpRequest and setting the baseUrl property for the request in init().
if (Yii::app()->domainManager->isPortalDomain) {
   // need to set the document root correctly
   Yii::app()->request->baseUrl = '/' . Yii::app()->domainManager->domain->name;
}

When I did that, all routing worked and urls were created correctly.


text:
Q: how to validate $xmlDoc->load($xml); this is my xml file :
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
   <channel>
      <title>Title</title>
      <link>http://www.Mydomain.com</link>
      <description>Description</description>
      <managingEditor>managingEditor</managingEditor>
      <webMaster>webMaster</webMaster>
      <lastBuildDate>Sat, 19 Oct 2013 09:21:40 +0400</lastBuildDate>
      <generator>generator</generator>
      <item>
         <title>title</title>
         <link>link</link>
         <description>ATT&T</description>
         <author>author</author>
         <pubDate>25 Aug 2013 16:52:31 +0400</pubDate>
      </item>
    </channel>
</rss>

and i am reading like this:
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

but i am getting this error:
Warning: DOMDocument::load(): EntityRef: expecting ';' in
file:///C:/xampp/htdocs/readxml/rss.xml, line: 14 in

because of ' & ' ... in description Node
Please Advise

A: You want to alter your XML. To make sure you have no problems with the XML document, you should contain strings containing & of < or > in CDATA.
So your description should look like this
<description><![CDATA[ATT&T]]></description>

More details here
UPDATE:
Since the OP posted he can't modify the XML.
Replace the & symbols with the & entity:
$xml = str_replace('&', '&', $xml);

The line above will replace -all- &'s with the & entity.

A: Replace ATT&T with ATT&T as unescaped ampersands aren't allowed in XML.

A: UPDATE:

libxml_use_internal_errors(true);
$xmlDoc = new DOMDocument();
if($xmlDoc->load($RSSURL->URL))
{

}else{
     echo 'XML file is not valid structure';
}


text:
Q: Animate text color jQuery CSS hover disappears? I have an issue when I make a button and have it change color when hovering over it works fine but when I first animate the color using jQuery then the hovering color doesn't work anymore but the active color when clicking still works, whats up with that?
HTML:
BUTTON

CSS:
.button {
  padding: 10px 20px;
  color:#808080;
  background-color:#808080;
  text-decoration: none;
}
.button:hover {
   color: #fff;
}
.button:active {
   background-color:#3C3C3C;
   color: #000;
}

jQuery:
$('.button').animate({color:'#ccc' },1000);

JSFiddle DEMO

A: Just add !important to your hover as below:
.button:hover {
   color: #fff !important;
}

DEMO

A: Its because, when you're using:
$('.button').animate({color:'#ccc' },1000);

It sets inline CSS to your  as:
BUTTON

and inline CSS has more preference over external or internal CSS so to override it you can do as Guruprasad Rao stated above OR you can do this:
.button[style]:hover {
   color: #FFF !important;
 }

the [style] selector will only work if your element has inline CSS only.


text:
Q: why I cannot Displaying data from view in MySQL database? I've a view to displaying some data from database to my php program, but the data cannot be displayed when I running it?
this is my view from phpmyadmin look like
(select `m`.`id_mutasi` AS `id_mutasi`,`m`.`tgl_mutasi` AS `tgl_mutasi`,`m`.`kode_barang` AS `kode_barang`,`a`.`nm_barang` AS `nm_barang`,`m`.`ruang_lama` AS `ruang_lama`,`m`.`ruang_baru` AS `ruang_baru`,`u`.`nm_unit` AS `unit_lama`,`m`.`unit_baru` AS `unit_baru`,`i`.`user` AS `user_lama`,`m`.`userbaru` AS `user_baru`,`m`.`jumlah` AS `jumlah`,`m`.`user_posting` AS `user_posting` from ((((((`simaset`.`mutasi` `m` join `simaset`.`inventarisasi` `i` on((`m`.`kode_inventarisasi_baru` = `i`.`kode_inventarisasi`))) join `simaset`.`aset` `a` on((`a`.`kode_barang` = `m`.`kode_barang`))) join `simaset`.`ruangan` `r` on((`r`.`kode_ruangan` = `m`.`ruang_lama`))) join `simaset`.`ruangan` `rb` on((`rb`.`kode_ruangan` = `i`.`kode_ruangan`))) join `simaset`.`unit_kerja` `u` on((`u`.`kode_unit` = `m`.`unit_lama`))) join `simaset`.`unit_kerja` `ub` on((`ub`.`kode_unit` = `i`.`kode_unit`))))

and this is my php code

        ID Mutasi
        Tgl Mutasi
        Kode Barang
        Barang
        Dept Lama
        Jabatan Lama
        Dept Baru
        Jabatan Baru

        Jumlah
        User Posting

        Aksi

      <?php do { ?>

              <?php echo $row_rs_data['id_mutasi']; ?>

            <?php echo $row_rs_data['tgl_mutasi']; ?>
            <?php echo $row_rs_data['kode_barang']; ?>
            <?php echo $row_rs_data['nm_barang']; ?>
            <?php echo $row_rs_data['ruanglama']; ?>
            <?php echo $row_rs_data['unitlama']; ?>
            <?php echo $row_rs_data['ruangbaru']; ?>
            <?php echo $row_rs_data['unitbaru']; ?>

            <?php echo $row_rs_data['jumlah']; ?>
            <?php echo $row_rs_data['user_posting']; ?>
            <a href="?mod=pindah_inventaris&act=delete&id_mutasi=<?php echo $row_rs_data['id_mutasi']; ?>" onclick="return confirm('Hapus Data <?php echo $row_rs_data['nm_barang']; ?> ?')">

        <?php
        echo "test";
         } while ($row_rs_data = mysql_fetch_assoc($rs_data)); ?>

A: Replace your
 block. Use while instead of do..while and mysqli instead of mysql mysql has been deprecated.

  <?php while ($row_rs_data = mysql_fetch_assoc($rs_data)){ ?>

          <?php echo $row_rs_data['id_mutasi']; ?>

        <?php echo $row_rs_data['tgl_mutasi']; ?>
        <?php echo $row_rs_data['kode_barang']; ?>
        <?php echo $row_rs_data['nm_barang']; ?>
        <?php echo $row_rs_data['ruanglama']; ?>
        <?php echo $row_rs_data['unitlama']; ?>
        <?php echo $row_rs_data['ruangbaru']; ?>
        <?php echo $row_rs_data['unitbaru']; ?>

        <?php echo $row_rs_data['jumlah']; ?>
        <?php echo $row_rs_data['user_posting']; ?>
        <a href="?mod=pindah_inventaris&act=delete&id_mutasi=<?php echo $row_rs_data['id_mutasi']; ?>" onclick="return confirm('Hapus Data <?php echo $row_rs_data['nm_barang']; ?> ?')">

    <?php
    echo "test";
     } ?>


text:
Q: Can't get Paypal and Rails app to work. Notification Paypal not working I am building a functionality to send three MMS (via Twilio) to the phone number entered by the user in a form after receiving a payment of $1.
Story:
1) User insert phone number and name in form. Then, click on Place order (via paypal)
2) The user go through the process on paypal-side, then is returned to my site and I receive notification of payment from paypal (the problem starts here).
3) Once I receive the completed :payment_status, I send the three MMS to the phone number.
My question:
I spent hours on this and I have no idea how to fix this. I want my send_text_message method to fire as soon as I receive the payment notification from paypal. I tried many things but nothing work and I start to worder if my setup is simply wrong. I need some help please.
I have one controller (Home) and two models (Home and Message).
# Table name: homes
#
#  id                  :integer          not null, primary key
#  phone               :string
#  sender_name         :string
#  created_at          :datetime         not null
#  updated_at          :datetime         not null

# Table name: messages
#
#  id         :integer          not null, primary key
#  body       :string
#  media_url  :string
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

MODEL -> Message
class Message < ActiveRecord::Base
belongs_to :home

end

MODEL -> Home
class Home < ActiveRecord::Base
  require 'twilio-ruby'
  has_many :messages
  validates :phone, presence: true
  validates :sender_name, presence: true
def send_text_message
    twilio_sid = ENV["TWILIO_ACCOUNT_SID"]
    twilio_token = ENV["TWILIO_AUTH_TOKEN"]
    twilio_phone_number = ENV["TWILIO_PHONE_NUMBER"]
    sender_number = twilio_phone_number.sample

    @twilio_client = Twilio::REST::Client.new(twilio_sid, twilio_token)

    random_messages.each do |message|
      twilio_credentials.account.messages.create(
        :from => sender_number,
        :to => self.phone,
        :body => message[:body],
        :media_url => message[:media_url]
        )
    end
  }

serialize :notification_params, Hash

  def paypal_url(return_path)
      values = {
          business: "merchant@sumbio.com",
          cmd: "_xclick",
          upload: 1,
          return: "#{Rails.application.secrets.app_host}#{return_path}",
          invoice: id + 1000,
          amount: '1.89',
          item_name: "Game of Thrones - Funny Prank",
          item_number: '1',
          quantity: '1',
          notify_url: "#{Rails.application.secrets.app_host}/hook"
      }
      "#{Rails.application.secrets.paypal_host}/cgi-bin/webscr?" + values.to_query
  end

private

def random_messages
    Message.order("RANDOM()").limit(3)
end

CONTROLLER: Home
class HomesController < ApplicationController
  protect_from_forgery except: [:hook]
  before_action :set_home, only: [:show, :destroy]

  def show
  end

  def new
    @home = Home.new
  end

  def create
    @home = Home.new(home_params)

    respond_to do |format|
      if @home.save
        format.html { redirect_to @home.paypal_url(home_path(@home)) }
        #@home.send_text_message
        #redirect_to @home, notice: 'Your Attack Has Officially Launched!'
        #format.json { render :show, status: :created, location: @home }
      else
        format.html { render :new }
        format.json { render json: @home.errors, status: :unprocessable_entity }
      end
    end
  end

  def hook
    params.permit! # Permit all Paypal input params
    status = params[:payment_status]
    if status == "Completed"
      @home = Home.find params[:invoice]
      @home.update_attributes notification_params: params, status: status, transaction_id: params[:txn_id], purchased_at: Time.now
      @home.send_text_message
    end
      format.html { render :new }
      format.json { render json: @home.errors, status: :unprocessable_entity }
  end

  private
    def set_home
      @home = Home.find(params[:id])
    end

    def home_params
      params.require(:home).permit(:phone, :sender_name, :plan, :notification_params, :status, :transaction_id ,:purchased_at)
    end
end

------------
Routes
resources :homes
post "/homes/:id" => "homes#show"
post "/hook" => "homes#hook"
root 'homes#new'

EDIT
The payment with paypal works. When the user click on the place order button, it redirect him to paypal and proceed to payment. The issue is that the send_text_message method is undefined and also do not get send. I can also see that the payment was made in the sandbox payment account

A: I think the problem is because the Home record is not found. I said I think because the OP specified that the issue is that the send_text_message is undefined not ActiveRecord::RecordNotFound.
To understand why this might be the bug, it's important to look at the Home#paypal_url method, as the invoice key is being set as id + 1000.
Now, in the HomeController#hook action, @home is being set to Home.find(params[:invoice]) , which for the first record in the db would mean Home.find(1001). I doubt this is the required behaviour.
Changing the invoice key to id should fix this problem.

A: if you tried to make the payment directly on the phone, maybe the current problem from paypal, is the issue.
Look here: PayPal: Client proceed to payment, clicked pay and got back to success page, but was not charged