text:
Q: Shrink Database using query I have deleted tons of records from my database and now i want to shrink the database.
So please give me script which shrinks the database

A: First off you need to determine which database files that you want to shrink.  You can get a rollup of space used on files like so:
use YourDatabase;
go

;with space_used_cte as
(
    select
        name,
        size * 8.0 / 1024 as size_mb,
        fileproperty(name, 'SpaceUsed') * 8.0 / 1024 as space_used_mb
    from sys.database_files
)
select
    name,
    size_mb,
    space_used_mb,
    convert(decimal(5, 2), space_used_mb / size_mb * 100) as space_used_percent
from space_used_cte;

Then when you determine whichever database file you want to shrink, you can issue a DBCC SHINKFILE command.  See BOL documentation for syntax.  But a common file shrink operation would look like the following:
dbcc shrinkfile(YourDatabaseFileName, <target size in MB>);

If you expect this space to be consumed in the future, it makes no point in shrinking the database file to just have it grow again.  Database file shrinking should only be incorporated when you absolutely need the database file space to be reclaimed and don't expect it to be utilized again.

A: This goes without saying : Why you should not shrink your data files ?
If you want to shrink, then after the shrink operation, make sure you do reorg/rebuild of your indexes as well as update stats as required.
Below script will help you to shrink datafile in increments
-- Shrink_DB_File.sql
/*
This script is used to shrink a database file in
increments until it reaches a target free space limit.

Run this script in the database with the file to be shrunk.
1. Set @DBFileName to the name of database file to shrink.
2. Set @TargetFreeMB to the desired file free space in MB after shrink.
3. Set @ShrinkIncrementMB to the increment to shrink file by in MB
4. Run the script

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=80355
*/

declare @DBFileName sysname
declare @TargetFreeMB int
declare @ShrinkIncrementMB int

-- Set Name of Database file to shrink
set @DBFileName = 'nameOfDatabaseFileGoesHere'

-- Set Desired file free space in MB after shrink
set @TargetFreeMB = 1000

-- Set Increment to shrink file by in MB
set @ShrinkIncrementMB = 500

-- Show Size, Space Used, Unused Space, and Name of all database files
select
        [FileSizeMB]    =
                convert(numeric(10,2),round(a.size/128.,2)),
        [UsedSpaceMB]   =
                convert(numeric(10,2),round(fileproperty( a.name,'SpaceUsed')/128.,2)) ,
        [UnusedSpaceMB] =
                convert(numeric(10,2),round((a.size-fileproperty( a.name,'SpaceUsed'))/128.,2)) ,
        [DBFileName]    = a.name
from
        sysfiles a

declare @sql varchar(8000)
declare @SizeMB int
declare @UsedMB int

-- Get current file size in MB
select @SizeMB = size/128. from sysfiles where name = @DBFileName

-- Get current space used in MB
select @UsedMB = fileproperty( @DBFileName,'SpaceUsed')/128.

select [StartFileSize] = @SizeMB, [StartUsedSpace] = @UsedMB, [DBFileName] = @DBFileName

-- Loop until file at desired size
while  @SizeMB > @UsedMB+@TargetFreeMB+@ShrinkIncrementMB
        begin

        set @sql =
        'dbcc shrinkfile ( '+@DBFileName+', '+
        convert(varchar(20),@SizeMB-@ShrinkIncrementMB)+' ) '

        print 'Start ' + @sql
        print 'at '+convert(varchar(30),getdate(),121)

        exec ( @sql )

        print 'Done ' + @sql
        print 'at '+convert(varchar(30),getdate(),121)

        -- Get current file size in MB
        select @SizeMB = size/128. from sysfiles where name = @DBFileName

        -- Get current space used in MB
        select @UsedMB = fileproperty( @DBFileName,'SpaceUsed')/128.

        select [FileSize] = @SizeMB, [UsedSpace] = @UsedMB, [DBFileName] = @DBFileName

        end

select [EndFileSize] = @SizeMB, [EndUsedSpace] = @UsedMB, [DBFileName] = @DBFileName

-- Show Size, Space Used, Unused Space, and Name of all database files
select
        [FileSizeMB]    =
                convert(numeric(10,2),round(a.size/128.,2)),
        [UsedSpaceMB]   =
                convert(numeric(10,2),round(fileproperty( a.name,'SpaceUsed')/128.,2)) ,
        [UnusedSpaceMB] =
                convert(numeric(10,2),round((a.size-fileproperty( a.name,'SpaceUsed'))/128.,2)) ,
        [DBFileName]    = a.name
from
        sysfiles a

A: Are you sure you want to do this?  It can cause performance problems.
http://blog.sqlauthority.com/2011/01/19/sql-server-shrinking-database-is-bad-increases-fragmentation-reduces-performance/
http://www.brentozar.com/archive/2009/08/stop-shrinking-your-database-files-seriously-now/
Since you tagged this SQL Server Express, you might really want to do this.  MSDN tells you how in the links below and suggests you reindex after.
http://msdn.microsoft.com/en-us/library/ms189035.aspx
http://msdn.microsoft.com/en-us/library/ms189493.aspx
http://blog.sqlauthority.com/2007/01/31/sql-server-reindexing-database-tables-and-update-statistics-on-tables/


text:
Q: Two long text fields are "incompatible data types" I am using an Access database which contains linked tables from SQL Server, I am creating a report using a subreport inside it, which I wish to pass a field by linking. The two fields in question are both long text is Access. In SQL Server they are both VARCHAR(MAX) data types.
Screenshot of error:

A: You can't, plain and simple.
Access cannot link fields with data type "Long text" ("Memo" in earlier versions), not with local tables and not with linked SQL Server tables.
See also Cannot join on Memo or OLE Object . (Error 3118) or
Cannot join on Memo, OLE, or Hyperlink Object - Access 2007 - outer joins
IMHO, the need to do this is a sign of faulty table design. There should be an ID field to create the link.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Empathy doesn't obey system/theme/gnome-appearence font settings I actually had this problem since at least 10.04.
Empathy ignores gnome-appearance-properties, and settings in /etc/fonts/fonts.conf
It's not just a matter of font size, but also it renders Unicode incorrectly due to none configurable font settings that also doesn't obey system settings.
Is there a work around for this? because the empathy guys haven't even confirmed these bugs yet.

A: The reason why Empathy doesn't have same fonts as the rest of your desktop UI is because in the "client area", it uses UI settings as specified by the chat theme (Since version 2.27.3, Empathy uses Adium Message Styles which define how fonts and overall UI should look like for your chat conversations, visit this page for more details), so until something's wrong with the chat theme you're using, it shouldn't look ugly.
As far as you've used default chat theme ("Ubuntu" in any case since 9.10), there shouldn't be any trouble what you've mentioned as long as the font the theme uses are still installed in the system. But as you've mentioned that you're facing it since 10.04, I wonder if you're using default settings or have customized the system so dramatically that the problem has surfaced in every version of Ubuntu since 10.04.
As a quick work-around I recommend you to download chat theme for Empathy called Renkoo (It is the theme from which the Ubuntu chat theme is created, so you'll hardly notice any difference). Once you download it, the theme folder has .AdiumMessageStyle extension, keep the folder in your home directory in .local/share/adium/message-styles/ (if directory doesn't exist, create it). Once you put the folder in there, it should show up in Edit->Preferences->Themes[Tab]. Change the theme and see if fonts now look properly (You'll need to reopen the chat window for changes to take effect).


text:
Q: AngularJS not refreshing ng-repeat on page change I'm using AngularJS to bind data to my Laravel app. I'm also using Bootstrap-UI for pagination, and so far, things are working together at first.
When I change to page 2, the ng-repeat won't show the data from page 2. I already checked and the $scope.results is changing with the data from page2, but ng-repeat won't show it. It's blank.
I tried placing $scope.$watch but I always get an error saying that $digest is already in progress.
Here is my HTML code:

         [[ result.id ]]

         [[ result.name ]]

         [[ result.email ]]

         [[ result.cpf ]]

            [[ result.active ]]

My pagination HTML (bootstrap-ui)
<pagination class="pull-right" ng-change="getResults(currentPage)" ng-model="currentPage" num-pages="numPages" total-items="totalItems" items-per-page="entryLimit"></pagination>

And my Angular code:
var app = angular.module('prime', ['ngSanitize','ngResource','angular-loading-bar','ngAnimate','ui.bootstrap'],
 function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
});

app.factory('JsonService', function ($resource,model) {
    return $resource('/api/users/?page=:page',{page: "@page"});
});

app.filter('startFrom', function () {
    return function (input, start) {
        if (input) {
            start = +start;
            return input.slice(start);
        }
        return [];
    };
});

app.controller('ResultsController', function($scope, $http, JsonService, filterFilter) {

    $scope.results = [];
    $scope.search = [];
    $scope.currentPage = 1;
    $scope.entryLimit = 10; // itens por pagina

    $scope.init = function() {
        JsonService.get({}, function (response) {
            $scope.results = response.data;
            $scope.totalItems = response.total;
            $scope.noOfPages = Math.ceil($scope.totalItems / $scope.entryLimit);
        }, function (error) {
            $scope.results = [];
        });
    };

    $scope.resetFilters = function () {
        $scope.search = [];
    };

    // runs $watch on the search field
    $scope.$watch('search', function (newVal, oldVal) {
        $scope.filtered = filterFilter($scope.results, newVal);
        $scope.totalItems = $scope.filtered.length;
        $scope.noOfPages = Math.ceil($scope.totalItems / $scope.entryLimit);
        $scope.currentPage = 1;
    }, true);

    $scope.$watch('currentPage', function(newPage) {
        $scope.init($scope.numberPage);
    });

});

A: Is your example accurate? There are a few confusing parts to it which could be related to your problem:

*

*Your $scope.init() method never passes a page parameter to the .get() method. Because of this, your service is probably returning the same page every time.

*Your $watch('currentPage', ...) call watches currentPage, but passes $scope.numberPage to the $scope.init() method. Even if the problem in #1 didn't exist, I think you meant to use currentPage here instead of numberPage.

*You're performing client-side pagination as well as server-side pagination:

Specifically, this part:
startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit

Your entryLimit is set to 10, right? So let's say you request page 2 and the server returns 10 items (assuming problems #1 and #2 didn't exist). Your filters would evaluate to this:
startFrom:(2-1)*10 | limitTo:10

Which comes out to:
startFrom:10 | limitTo:10

But you only have 10 items because the server already did the pagination! By doing the client-side pagination as well, you end up with an empty list.
So, either get rid of the client-side pagination (the startFrom and limitTo), or get rid of the server-side pagination (load everything once in the beginning).
That's all I can see from your code. If you can post a full example on Plunker or something, we might be able to help more.


text:
Q: Array Filter In swift I want to add on response on another array whose quantity greater than zero. Can it is possible without iterating my array. Is their any function because my array has lot of value. Please help any help would be appreciated.
{
            id = 1;
            img = "http://alatiffy.com/admin/uploads/1478601364.png";
            name = "Executive Lunch Tiffy";
            price = 99;
            quantity = 1;
        },
            {
            id = 2;
            img = "http://alatiffy.com/admin/uploads/1478601409.png";
            name = "Deluxe Lunch Tiffy";
            price = 149;
            quantity = 0;
        },
            {
            id = 4;
            img = "http://alatiffy.com/admin/uploads/1478583806.jpg";
            name = "KADHI PAKODA CHAWAL";
            price = 59;
            quantity = 1;
            status = Y;
        },
            {
            id = 2;
            img = "http://alatiffy.com/admin/uploads/1478583832.jpg";
            name = "DAL MAKHNI CHAWAL";
            price = 59;
            quantity = 0;
            status = Y;
        },
            {
            id = 5;
            img = "http://alatiffy.com/admin/uploads/1478583850.jpg";
            name = "SHAHI PANEER CHAWAL";
            price = 59;
            quantity = 0;

 status = Y;
    },

A:
Swift 3.x

Suppose you kept the above JSON data in an array of dictionary of type [String:AnyObject]
So your dictionary will be
var dict = Dictionary<String,AnyObject>()

And your array will be array of the above type of dictionary
var array = [Dictionary<String,AnyObject>]()

In order to filter the array for quantity greater than 0
let filteredArray = array.filter{$0["quantity"] as! Int > 0}

your filteredArray will contain all the dictionary objects which have quantity of greater than zero.
I would suggest you to make a model class of Food or Lunch item and apply filter on model itself rather than using dictionaries.

A: try this code,
   var filteredResults = arr.filter { $0.quantity > 0 }


text:
Q: How to Match the list of values which are being passed from Input controls with column in the table in Vertica DB SQL Select * from Network
where systemid in $P{objectid}

When I tried this it is not working because the output of the parameter Objectid is in the form of [10.129.148.163 10.130.149.111]. Hence it is throwing SQL statement error.
Then I tried using of Replace function. Ex:
 (REPLACE( replace(replace('[10.129.148.163,10.130.149.111]', '[', '('''),']',''')') , ',', ''','''))

This replace function is giving output as ('10.129.148.163','10.130.149.111')
But when Im using the same in where clause it is not working:
Select * from Network
where systemid in (REPLACE( replace(replace('[10.129.148.163,10.130.149.111]', '[', '('''),']',''')') , ',', ''','''))

The output is giving blank.
Then I tried using JOIN,
Select * from Network N
inner join (select distinct (REPLACE( replace(replace('[10.129.148.163,10.130.149.111]', '[', '('''),']',''')') , ',', ''',''')) as neid )t on 1=1
where (t.neid ilike '%'||N.systemid||'%' and not (t.neid  not ilike '%'||N.systemid||'%' ))

Then it is giving output as below
10.129.148.163
10.129.148.1
10.130.149.111
10.130.149.1

But the expected output is
10.129.148.163
10.130.149.111

I have tried my best but still not working.

A: You cannot use a string of format '[10.129.148.163 10.130.149.111]' as a list of literals in an IN() predicate.
But, in Vertica, you can convert such a string to an array, and then EXPLODE() that array into an in-line table with which you can join.
As your Vertica version seems to be pre- 9.3, I add a script that uses SPLIT_PART() on your argument , after cleaning it of the square brackets using REGEXP_REPLACE() on a single-row table containing your search argument as its only column CROSS JOIN-ed with a series of consecutive integers. See the end of the post.
I'm using VSQL, Vertica's command-line SQL client. That one has a different format to use parameters / variables, the colon, followed by the variable name. So you will have to modify the script to contain $P{objectid} instead of my :objectid
\set objectid '''[10.129.148.163 10.130.149.111]'''
-- create some test data. Zurich and Berne satisfy the where condition.
CREATE LOCAL TEMPORARY TABLE
networks(systemid,dom,city)
ON COMMIT PRESERVE ROWS AS (
          SELECT '10.129.148.163','foo.co.ch','Berne'
UNION ALL SELECT '10.130.149.111','bar.co.ch','Zurich'
UNION ALL SELECT '10.130.149.112','chk.co.ch','Basle'
UNION ALL SELECT '10.130.149.113','tst.co.ch','Lugano'
UNION ALL SELECT '10.130.149.113','kil.co.ch','Geneva'
)
;

WITH
search(pos,objid) AS (
  SELECT
    EXPLODE(
     STRING_TO_ARRAY(
       :objectid  -- put parameter here
       USING PARAMETERS collection_delimiter=' '
      )
    ) OVER(PARTITION BEST)
)
-- ctl select * from search;
-- ctl  pos |     objid
-- ctl -----+----------------
-- ctl    0 | 10.129.148.163
-- ctl    1 | 10.130.149.111
SELECT
  networks.*
FROM networks
JOIN search
 ON systemid=objid;
-- out CREATE TABLE
-- out Time: First fetch (0 rows): 56.730 ms. All rows formatted: 56.886 ms
-- out     systemid    |    dom    |  city
-- out ----------------+-----------+--------
-- out  10.129.148.163 | foo.co.ch | Berne
-- out  10.130.149.111 | bar.co.ch | Zurich

Pre-Vertica-9.3 version:
\set objectid '''[10.129.148.163 10.130.149.111]'''
CREATE LOCAL TEMPORARY TABLE
networks(systemid,dom,city)
ON COMMIT PRESERVE ROWS AS (
          SELECT '10.129.148.163','foo.co.ch','Berne'
UNION ALL SELECT '10.130.149.111','bar.co.ch','Zurich'
UNION ALL SELECT '10.130.149.112','chk.co.ch','Basle'
UNION ALL SELECT '10.130.149.113','tst.co.ch','Lugano'
UNION ALL SELECT '10.130.149.113','kil.co.ch','Geneva'
)
;

WITH
objectid(objectid) AS (
  SELECT :objectid
)
,
i(i) AS ( -- need as many consecutive integers as we have IP addresses -
            SELECT 1
  UNION ALL SELECT 2
  UNION ALL SELECT 3
)
,
search(i,objid) AS (
  SELECT
    i
  , SPLIT_PART(REGEXP_REPLACE(:objectid,'[][]',''),' ',i) AS objid
  FROM objectid CROSS JOIN i
  WHERE objid <> ''
)
-- ctl SELECT * FROM search;
-- ctl  i |     objid
-- ctl ---+----------------
-- ctl  1 | 10.129.148.163
-- ctl  2 | 10.130.149.111
SELECT
  networks.*
FROM networks
JOIN search
 ON systemid=objid;
-- out     systemid    |    dom    |  city
-- out ----------------+-----------+--------
-- out  10.129.148.163 | foo.co.ch | Berne
-- out  10.130.149.111 | bar.co.ch | Zurich


text:
Q: Query Selector Returning null This is driving me crazy. I have a HTML page with a form element as shown below:
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  <script src="formHandler.js"></script>
  <script src="app.js"></script>

</head>

<body>

  <form data-coffee-order="form">
    <input type="submit" />
  </form>

</body>

In my app.js I try to access the form element using the querySelector as shown below:
var FORM_SELECTOR = '[data-coffee-order="form"]'

var form = document.querySelector(FORM_SELECTOR)
console.log(form) // this is null why?

For some reason form is always null. Why is that?

A: Because the JavaScript code is executing before the element actually exists.  Place the code after:
<body>

    <form data-coffee-order="form">
        <input type="submit" />
    </form>

    <script src="app.js"></script>

</body>

(This may also apply to your other JavaScript.  It's not necessary, but even if just for consistency it would make sense.  Unless there's JavaScript code you want to be executed immediately, before the DOM is loaded.)


text:
Q: Faster way to read image in BufferedImage WITHOUT ImageIO I know there is already lot of discussion around this but haven't found the answer. I have no issues with reading image with ImageIO except it takes time.
I have 18-20MB images and it takes 10-20 seconds to read them. Are there any new image libraries which can help reading an image in BufferedImage faster than ImageIO?


text:
Q: Eclipse + Java - SplashWindow I would like develop a basic application with splashWindow.
this should stay for 5 seconds, when user press any key, the time is need reset, and redefine the time() for 5 seconds again.
If user dont press any key, the splashWindow close.
public class SplashWindow extends JWindow implements WindowListener, KeyListener
{
    private Container c;

    SplashWindow()
    {
        frase1.setText("test");
        Font font12 = new Font ("Courier New", Font.BOLD, 18);
        frase1.setFont(font12);
        frase1.setForeground(Color.WHITE);

        frase2.setText("test2");
        frase2.setFont(font12);
        frase2.setForeground(Color.WHITE);
    }

    public void open( int tempo )
    {

        c = getContentPane();
        c.setLayout(null);

        c.setBackground(Color.black);
        Insets in = Toolkit.getDefaultToolkit().getScreenInsets(this.getGraphicsConfiguration());
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        int width = d.width-(in.left + in.top);
        int height = d.height-(in.top + in.bottom);
        this.setSize(width,height);
        this.setLocation(in.left,in.top);

        BorderLayout layout = new BorderLayout();
        c.setLayout(layout);

        c.add(BorderLayout.CENTER, frase1);
        c.add(BorderLayout.PAGE_END, frase2);
        frase1.setHorizontalAlignment(SwingConstants.CENTER);
        frase2.setHorizontalAlignment(SwingConstants.CENTER);

        this.setVisible( true );
        this.addKeyListener(this);

        sleep( tempo );
    }

    /**
     * Aguarda um tempo em milisegundos
     * @param tempo     int que representa o tempo, em milisegundos, que ser�aguardado.
     * @exception InterruptedException
     * @exception Exception
     * @return void
     */
    private void sleep( int tempo )
    {
        try {
            Thread.sleep( tempo );
        }
        catch( InterruptedException ie ) {
            ie.printStackTrace();
            JOptionPane.showMessageDialog( null, " Erro 00 - Falha no sleep do Splash ", " Erro ", JOptionPane.ERROR_MESSAGE );
        }
        catch( Exception e ) {
            e.printStackTrace();
            JOptionPane.showMessageDialog( null, " Erro 00 - Falha no sleep do Splash ", " Erro ", JOptionPane.ERROR_MESSAGE );
        }
    }

    /**
     * Fecha a janela de splash
     * @return void
     */
    public void close()
    {
        dispose();
    }

    /**
     * @param windowevent
     * @return void
     */
    public void windowOpened( WindowEvent windowevent )
    {
        Graphics2D graphics2d = (Graphics2D)getGlassPane().getGraphics();
        graphics2d.setColor( new Color( 51, 102, 153 ) );
        graphics2d.setFont( new Font( "SansSerif", 0, 16 ) );
    }
    /**
     * @param windowevent
     * @return void
     */
    public void windowActivated( WindowEvent windowevent )
    {
    }
    /**
     * @param windowevent
     * @return coid
     */
    public void windowClosed( WindowEvent windowevent )
    {
    }
    /**
     * @param windowevent
     * @return void
     */
    public void windowClosing( WindowEvent windowevent )
    {
    }
    /**
     * @param windowevent
     * @return void
     */
    public void windowDeactivated( WindowEvent windowevent )
    {
    }
    /**
     * @param windowevent
     * @return void
     */
    public void windowDeiconified( WindowEvent windowevent )
    {
    }
    /**
     * @param windowevent
     * @return void
     */
    public void windowIconified( WindowEvent windowevent )
    {
    }

}

A: Use SplashScreen Functionality. Here is a tutorial.


text:
Q: what are the steps in order to run java enterprise application Sorry for this simple questions but i am too much confused with how to run java application. Whenever i ask some each one tells his own tools to proceed and i have learn that thing.
So provided i have simple basic eclipse with no plugin and i have downloaded the sample web application which uses spring , hibernate , mysql ,
The folder structure of app is
.setting
src--main,test
target
.classpath
.project

Now i want to run this using localhost in browser
what thing i need to do. i will tell from my knowledge and u guys can correct it
i don't want to use STS or install any plugin in eclipse.

*

*I imported the project from eclipse
menu and i appeared on left window

*As it uses spring do i have to add
the spring jar files in build path
of spring. or anything else

*Same for hibernate jar files

*Fior simple java app i used to
compile the class which contain the
void main function but i have no
idea which file to compile to run
this app

*I added the mysql connector in build
path to connect with mysql in simple
java app. will same thing work here?

*I knoow we need web server for that.
so if i want to install glass fish
server then how will i connect it to eclispe or that app. will tomcat be
ok than glass fish??? i know tthere
is eclispe ide with embedded glass
fish but i want integrate evrything
myself

*IN browser i which url i need to use
to see that app

I don't know how did maven , appfuse fit in here. Can i run app without maven if yes then what does maven really do , i mean does it compile the java files or what. If i require maven then

*

*Do i need to install it separately i
mean exe file or jar file

*how to link with eclipse

*I have read about building with
maven , what will ahppen after
building i mean what is the result
of building , will i see browser
after building  or after building
there are some steps further. do
maven needs to link with web server
installed

sorry for basics questions but i am confused with all new trminology

A: Building a webapp is complicated.  I will try and address your specific questions.
Utimately you don't need Maven or Appfuse, both can be very helpful.
Maven is a build tool.  Maven and Eclipse do some similar tasks.  Both can compile your code and manage a classpath.  Maven handles a lot of things out of the box that Eclipse can't do by default.  Maven can manage dependencies (i.e. download the spring jars for you) and create complex build processes.
If you are unfamiliar with Maven and creating a build file from scratch then it probably won't be much help.  If you have a pom.xml (Maven build file) from somewhere else then Maven can be a big help.  The result of Maven depends on how your build file is structured.  The result is most often either a .war file (described below as step 5) or that your application is deployed directly to your web server (described below as step 6).
Appfuse is also not mandatory but can be useful.  Appfuse will create a skeleton project for you.  When it does this it will create a pom.xml (Maven build file) to automatically build your project.  Appfuse by itself doesn't do anything other than help get projects started.  Most people don't start building web apps from scratch anymore since getting the directory structure right and creating the build file can be a lot of work and it's easy to make mistakes.  A tool similar to Appfuse is Spring Roo.
Tomcat, Glassfish, Jetty, and JBoss are web servers.  They are also often called Servlet Containers which is just another name for a web server that hosts servlets in a certain fashion.  Any of them will work for your project, they all have different learning curves.  Integrating them into Eclipse may work for you, when I got started I found it was easier (although a little slower) to keep them separate.
In the JDK there is an interface named javax.servlet.Servlet.  This is the interface that the entry class of your web application must implement.  In particular the method service(ServletRequest req, ServletResponse res) is called every time there is a request for a URL.  If you want your web application to respond to HTTP it may be simpler to extend the abstract class HttpServlet (which implements Servlet) instead.  Most libraries (i.e. Spring web framework) have their own implementations of Servlet that are the entry point to the library.
I will now describe the basic process for building a web application.  This is a complicated process and most people eventually automate it with Maven.  I do not suggest trying to manually walk through the process yourself it can be very complicated but you can if you want.  I am going to assume that you are placing all of your built files in a folder named $BUILD

*

*Compile your source code.  The compiled classes need to end up in a folder called $BUILD/WEB-INF/classes

*Place all your jar files (external libraries) in a folder named $BUILD/WEB-INF/lib

*Create a deployment descriptor, this is a file that tells your web server how to deploy your code.  The most important thing in this file is a mapping from URLs to Java classes that implement Servlet.  It should be named web.xml and put in $BUILD/WEB-INF

*jar up the all this code with the root of the jar being at $BUILD.  You could call this code application.jar

*Rename the jar file extension to war.  A war file is simply a jar file that has the required WEB-INF directory inside of it.

*Deploy this war file to your web server (Tomcat/JBoss/Jetty/Glassfish/etc.), the process for doing this is different for each web server

That is the basics of web application deployment.  Your web server will extract the war file and load all of the jars in the lib folder into the classpath.  It will then take any URL requests it receives and send them to the appropriate Servlet implementations declared in your deployment descriptor.
As you can see this is not a simple process.  This is the reason tools like Appfuse and Roo exist.  They try and give you a starting point which does all of this basic stuff for you.  If you are having trouble I would suggest trying again from scratch with Appfuse/Roo.  As you start to get the hang of things I would also suggest learning more about Maven (or Ivy+Ant) to handle dependencies for you.

A: You should download the Java EE edition of Eclipse - it contains the code needed to work with enterprise applications.
You will also need an enterprise server (like JBoss or Glassfish) and the corresponding server adapter, which is a bit much for a beginner.
The easiest way to get started is to download Netbeans with Glassfish and use that instead - at least for now - as everything is configured correctly and it is very fast to get started!   When you are more familiar with the way things work, you can switch back to Eclipse if you want to.


text:
Q: AWS boto function calls from Lambda code I am trying to modify the default aws-lambda scheduled events code, to make a call to SNS. Whenever there is an error, I want to publish to a SNS topic instead of raising the error, and then using cloudwatch.
The boto import is failing. Any ideas why this is failing.
Error message, when I try to test:
Unable to import module 'lambda_function': cannot import name sns

Lambda code:
from __future__ import print_function

from datetime import datetime
from urllib2 import urlopen
from boto3 import sns #I have also tried import boto3
import json

SITE = 'http://my-site.com/'  # URL of the site to check
EXPECTED = 'My Site'  # String expected to be on the page

def validate(res):
    '''Return False to trigger the canary

    Currently this simply checks whether the EXPECTED string is present.
    However, you could modify this to perform any number of arbitrary
    checks on the contents of SITE.
    '''
    return EXPECTED in res

def lambda_handler(event, context):
    print('Checking {} at {}...'.format(SITE, event['time']))
    try:
        if not validate(urlopen(SITE).read()):
            raise Exception('Validation failed')
    except:
        print('Check failed!')
        # pub = boto.sns.connect_to_region('us-east-1').publish(topic='<my topic name'',message='site down!')
        raise
    else:
        print('Check passed!')
        return event['time']
    finally:
        print('Check complete at {}'.format(str(datetime.now())))

A: This is how I import SNS via python:
import boto
sns = boto.connect_sns()

OR
import boto3
client = boto3.client('sns')


text:
Q: how can I run the result of this powershell script... I can't get the last pipe to output the versions of java I'm looking to get the java versions of all the Java on the machine.
 Get-ChildItem 'C:\Program Files*' -Include java.exe -Recurse | % { $_ -version }

i'm able to get the results however am not able to run the commands to get the actual versions back.
C:\Program Files\Java\jre1.8.0_241\bin\java.exe -version
C:\Program Files\Vertiv\DSView 4\j2sdk\bin\java.exe -version
C:\Program Files (x86)\Common Files\Oracle\Java\javapath\java.exe -version
C:\Program Files (x86)\Common Files\Oracle\Java\javapath_target_3553135156\java.exe -version

any other options appreciated.


text:
Q: Finding the Most Similar Match in a Set I have a database of animals, each with many attributes ranging from 0 to 1-- these attributes are things like size, speed, hairiness, etc.  Given an input set of attributes, and weights for each type of attribute, I need to find the "closest" match in the set of animals.  Is there an algorithm that accomplishes this in better than O(n) time?
What I'm specifically trying to do is find suitable textures for "animals" produced by a genetic algorithm in a game, by matching them to animals that already exist.  By "closest," I mean the animal whose weighted sum of attribute differences is minimal.  The database and weights are known at application launch time, so a lot of time can be invested towards preparing the data.
I've found algorithms on string matching and product matching given user preferences, but either I'm not finding what I'm looking for or I'm not understanding how to reapply such concepts to my dilemma.  Perhaps there's something from the world of graph theory to help me out?
Any help would be greatly appreciated!

A: You could treat the items as points in a high-dimensional space, and insert them all into a BSP-tree, such as a k-d tree. To use the attribute-weights, you just need to multiply them by the corresponding coordinate: (w1*x, w2*y, ...)
Preparation: (from wikipedia, python code)
def kdtree(point_list, depth=0):

    if not point_list:
        return None

    # Select axis based on depth so that axis cycles through all valid values
    k = len(point_list[0]) # assumes all points have the same dimension
    axis = depth % k

    # Sort point list and choose median as pivot element
    point_list.sort(key=lambda point: point[axis])
    median = len(point_list) // 2 # choose median

    # Create node and construct subtrees
    node = Node()
    node.location = point_list[median]
    node.left_child = kdtree(point_list[:median], depth + 1)
    node.right_child = kdtree(point_list[median + 1:], depth + 1)
    return node

Search: (from gist, based on the wikipedia algorithm)
# method of the Node-class

def closest_point(self, target, point, best=None):
    if target is None:
        return best

    if best is None:
        best = target

    # consider the current node
    if distance(target, point) < distance(best, point):
        best = target

    # search the near branch
    best = self.child_near(point).closest_point(point, best)

    # search the away branch - maybe
    if self.distance_axis(point) < distance(best, point):
        best = self.child_away(point).closest_point(target, point, best)

    return best

Read more:

*

*High Dimensional Search and the NN Problem (blog article)

*Closest Point Search in High Dimensions by Nene and Nyar.

*Nearest Neighbor Search in Multidimensional Spaces by Tsaparas

A: If you can spend time arranging your data, you can sort your animals by score (in O(nlogn) time but done only once) and then apply a binary search over score to find the closest match in O(logn) time.
If you get your animal list from a SQL database, you can get a sorted list by using the ASC or DESC keywords in your query.

A: You could possibly frame this as a maximum weight matching problem, but the lower bound on the complexity of finding the minimal such matching is going to be much, much worse than O(n).  Think more like O(n^3).
If I had to attempt to solve this, I would consider pairwise matching your attributes of the same type according to weight (i.e., create a weighted edge between your input 'hairy' attribute and every other 'hairy' attribute in the data set, using some factor of the input weight and the inverse of the difference between the query 'hairy' value and the matched 'hairy' value).  At that point you can merge all the edges going to a specific animal, and take the sum of the edge weights as the match score.
For example:
Monkey:
A1: 0.5
B1: 0.25
C1: 1.0

Giraffe:
A2: 0.2
C2: 0.9
D2: 0.1

Input query:
Ai: 0.4 with weight 0.8
Di: 0.2 with weight 0.25

So we create the following graph:
Ai --> A1 with weight 0.8 * 1/abs(0.5-0.4) (i.e., 8.0)
Ai --> A2 with weight 0.8 * 1/abs(0.2-0.4) (i.e., 4.0)

Di --> D2 with weight 0.25 * 1/abs(0.1-0.2) (i.e., 2.5)

Then we collapse all edges with attributes in the same target animal, to get our candidates:
Monkey: 8.0
Giraffe: 4.0 + 2.5

It's not pretty, and it's worse than O(n) (probably by some factor of m, where m is the number of attributes you are trying to match on), but it might be a starting point from which to start to optimise a better solution.

A: How about finding number of linear inversions? So you'd have a linear set of data for 2 animals and you'd want to find out how similar or different they are by kinda sorting them. Complexity is same as that of merge sort. For 'n' animals you'll have nC2 inversions counted.


text:
Q: Different color for different word in QML TextArea without RichText I am trying to make a code editor and want to change color of keywords in TextArea after user types a keyword. I read that textFormat:Text.StyledText could change color without changing the whole text to Html but adding tags to the text is not changing the color. Here I used bold tag for code
Code -
TextArea{
Layout.alignment: Qt.AlignTop
id:ta
selectByMouse: true
selectByKeyboard: true
Layout.fillWidth:true
Layout.fillHeight: true
font.pointSize: 12
textMargin: 16
font.family:"courier new"
persistentSelection: true
textFormat: Text.StyledText

onActiveFocusChanged: {
menu_trig=0
}
onTextChanged: {
    // check text
        console.log(ta.text.slice(0,ta.text.length-3))
        if(ta.text.slice(ta.text.length-3,ta.text.length)=="def")
                {
          ta_text.text=ta.text.substring(0,ta.text.length-3)+"<b>def</b>"}
            }
Keys.onPressed: {
    if(codeChange==0)
    {codeChange=1
        mainWindow.title=title.toString()+" *"}
}
Component.onCompleted: forceActiveFocus()
// color:"orange"}

A: You have to use a QSyntaxHighlighter and because it seems to me you are trying to make it an editor for python I have implemented based on this post.
syntaxhighlighter.h
#ifndef SYNTAXHIGHLIGHTER_H
#define SYNTAXHIGHLIGHTER_H

#include <QRegularExpression>
#include <QSyntaxHighlighter>

class QQuickTextDocument;

class HighlightingRule
{
public:
    HighlightingRule(const QString &patternStr, int n, const QTextCharFormat &matchingFormat);
    QString originalRuleStr;
    QRegularExpression pattern;
    int nth;
    QTextCharFormat format;
};

class PythonSyntaxHighlighter : public QSyntaxHighlighter
{
    Q_OBJECT
public:
    PythonSyntaxHighlighter(QTextDocument *parent);
    const QTextCharFormat getTextCharFormat(const QString &colorName, const QString &style = QString());
    void initializeRules();
    bool matchMultiline(const QString &text, const QRegularExpression &delimiter, const int inState, const QTextCharFormat &style);
protected:
    void highlightBlock(const QString &text);
private:
    QStringList keywords;
    QStringList operators;
    QStringList braces;
    QHash<QString, QTextCharFormat> basicStyles;
    QList<HighlightingRule> rules;
    QRegularExpression triSingleQuote;
    QRegularExpression triDoubleQuote;
};

class SyntaxHighlighterHelper: public QObject
{
    Q_OBJECT
    Q_PROPERTY(QQuickTextDocument *quickdocument READ quickdocument WRITE setQuickdocument NOTIFY quickdocumentChanged)
public:
    SyntaxHighlighterHelper(QObject *parent=nullptr):
        QObject(parent),
        m_quickdocument(nullptr)
    {}
    QQuickTextDocument *quickdocument() const;
    void setQuickdocument(QQuickTextDocument *quickdocument);
signals:
    void quickdocumentChanged();
private:
    QQuickTextDocument *m_quickdocument;
};

#endif // SYNTAXHIGHLIGHTER_H

syntaxhighlighter.cpp
#include "syntaxhighlighter.h"
#include <QQuickTextDocument>

HighlightingRule::HighlightingRule(const QString &patternStr, int n, const QTextCharFormat &matchingFormat)
{
    originalRuleStr = patternStr;
    pattern = QRegularExpression(patternStr);
    nth = n;
    format = matchingFormat;
}

PythonSyntaxHighlighter::PythonSyntaxHighlighter(QTextDocument *parent)
    : QSyntaxHighlighter(parent)
{
    keywords = QStringList() << "and" << "assert" << "break" << "class" << "continue" << "def" <<
                                "del" << "elif" << "else" << "except" << "exec" << "finally" <<
                                "for" << "from" << "global" << "if" << "import" << "in" <<
                                "is" << "lambda" << "not" << "or" << "pass" << "print" <<
                                "raise" << "return" << "try" << "while" << "yield" <<
                                "None" << "True" << "False";

    operators = QStringList() << "=" <<
                                 // Comparison
                                 "==" << "!=" << "<" << "<=" << ">" << ">=" <<
                                 // Arithmetic
                                 "\\+" << "-" << "\\*" << "/" << "//" << "%" << "\\*\\*" <<
                                 // In-place
                                 "\\+=" << "-=" << "\\*=" << "/=" << "%=" <<
                                 // Bitwise
                                 "\\^" << "\\|" << "&" << "~" << ">>" << "<<";

    braces = QStringList() << "{" << "}" << "\\(" << "\\)" << "\\[" << "]";

    basicStyles.insert("keyword", getTextCharFormat("blue"));
    basicStyles.insert("operator", getTextCharFormat("red"));
    basicStyles.insert("brace", getTextCharFormat("darkGray"));
    basicStyles.insert("defclass", getTextCharFormat("black", "bold"));
    basicStyles.insert("brace", getTextCharFormat("darkGray"));
    basicStyles.insert("string", getTextCharFormat("magenta"));
    basicStyles.insert("string2", getTextCharFormat("darkMagenta"));
    basicStyles.insert("comment", getTextCharFormat("darkGreen", "italic"));
    basicStyles.insert("self", getTextCharFormat("black", "italic"));
    basicStyles.insert("numbers", getTextCharFormat("brown"));

    triSingleQuote.setPattern("'''");
    triDoubleQuote.setPattern("\"\"\"");

    initializeRules();
}

void PythonSyntaxHighlighter::initializeRules()
{
    for(const QString & currKeyword: keywords)
    {
        rules.append(HighlightingRule(QString("\\b%1\\b").arg(currKeyword), 0, basicStyles.value("keyword")));
    }
    for(const QString & currOperator: operators)
    {
        rules.append(HighlightingRule(QString("%1").arg(currOperator), 0, basicStyles.value("operator")));
    }
    for(const QString &currBrace: braces)
    {
        rules.append(HighlightingRule(QString("%1").arg(currBrace), 0, basicStyles.value("brace")));
    }
    // 'self'
    rules.append(HighlightingRule("\\bself\\b", 0, basicStyles.value("self")));

    // Double-quoted string, possibly containing escape sequences
    // FF: originally in python : r'"[^"\\]*(\\.[^"\\]*)*"'
    rules.append(HighlightingRule("\"[^\"\\\\]*(\\\\.[^\"\\\\]*)*\"", 0, basicStyles.value("string")));
    // Single-quoted string, possibly containing escape sequences
    // FF: originally in python : r"'[^'\\]*(\\.[^'\\]*)*'"
    rules.append(HighlightingRule("'[^'\\\\]*(\\\\.[^'\\\\]*)*'", 0, basicStyles.value("string")));

    // 'def' followed by an identifier
    // FF: originally: r'\bdef\b\s*(\w+)'
    rules.append(HighlightingRule("\\bdef\\b\\s*(\\w+)", 1, basicStyles.value("defclass")));
    //  'class' followed by an identifier
    // FF: originally: r'\bclass\b\s*(\w+)'
    rules.append(HighlightingRule("\\bclass\\b\\s*(\\w+)", 1, basicStyles.value("defclass")));

    // From '#' until a newline
    // FF: originally: r'#[^\\n]*'
    rules.append(HighlightingRule("#[^\\n]*", 0, basicStyles.value("comment")));

    // Numeric literals
    rules.append(HighlightingRule("\\b[+-]?[0-9]+[lL]?\\b", 0, basicStyles.value("numbers"))); // r'\b[+-]?[0-9]+[lL]?\b'
    rules.append(HighlightingRule("\\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\\b", 0, basicStyles.value("numbers"))); // r'\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b'
    rules.append(HighlightingRule("\\b[+-]?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b", 0, basicStyles.value("numbers"))); // r'\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b'
}

void PythonSyntaxHighlighter::highlightBlock(const QString &text)
{
    for(const HighlightingRule &rule: rules) {
        QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text);
        while (matchIterator.hasNext()) {
            QRegularExpressionMatch match = matchIterator.next();
            setFormat(match.capturedStart(), match.capturedLength(), rule.format);
        }
    }
    setCurrentBlockState(0);
    bool isInMultilne = matchMultiline(text, triSingleQuote, 1, basicStyles.value("string2"));
    if (!isInMultilne)
        isInMultilne = matchMultiline(text, triDoubleQuote, 2, basicStyles.value("string2"));
}

bool PythonSyntaxHighlighter::matchMultiline(const QString &text, const QRegularExpression &delimiter, const int inState, const QTextCharFormat &style)
{
    QRegularExpressionMatch match;
    int startIndex = 0;
    if (previousBlockState() != 1)
        startIndex = text.indexOf(delimiter);
    while (startIndex >= 0) {
        QRegularExpressionMatch match = delimiter.match(text, startIndex);
        int endIndex = match.capturedStart();
        int commentLength = 0;
        if (endIndex == -1) {
            setCurrentBlockState(1);
            commentLength = text.length() - startIndex;
        } else {
            commentLength = endIndex - startIndex
                    + match.capturedLength();
        }
        setFormat(startIndex, commentLength, style);
        startIndex = text.indexOf(delimiter, startIndex + commentLength);
    }

    return currentBlockState() == inState;
}

const QTextCharFormat PythonSyntaxHighlighter::getTextCharFormat(const QString &colorName, const QString &style)
{
    QTextCharFormat charFormat;
    QColor color(colorName);
    charFormat.setForeground(color);
    if (style.contains("bold", Qt::CaseInsensitive))
        charFormat.setFontWeight(QFont::Bold);
    if (style.contains("italic", Qt::CaseInsensitive))
        charFormat.setFontItalic(true);
    return charFormat;
}

QQuickTextDocument *SyntaxHighlighterHelper::quickdocument() const
{
    return m_quickdocument;
}

void SyntaxHighlighterHelper::setQuickdocument(QQuickTextDocument *quickdocument)
{
    m_quickdocument = quickdocument;
    if(m_quickdocument){
        new PythonSyntaxHighlighter(m_quickdocument->textDocument());
    }
}

main.cpp
// ...
qmlRegisterType<SyntaxHighlighterHelper>("Foo", 1, 0, "SyntaxHighlighterHelper");
// ...

main.qml
// ...
import Foo 1.0
// ...
SyntaxHighlighterHelper{
    quickdocument: ta.textDocument
}

TextArea{
    id:ta
    anchors.fill: parent
    selectByMouse: true
    selectByKeyboard: true
    font.pointSize: 12
    textMargin: 16
    font.family:"courier new"
    persistentSelection: true
    textFormat: Text.StyledText
    tabStopDistance: 4*fontMetrics.advanceWidth(" ")
    FontMetrics {
        id: fontMetrics
        font.family: ta.font
    }
}
// ...

The example can be found here.


text:
Q: EC2 Auto Scaling for mortals? Does that exist? I have very simple EC2 setup with Eastic Load Balancer and two web servers under it.
I need to automatically start additional instance when CPU on one of them reaches 100% or some instance fails.
The first thing I looked was Amazon http://aws.amazon.com/autoscaling/ page. I read this page a few times and staring at it and can't believe. It appears that Amazon advertise "Auto Scaling" as feature while they only provide API and some do-it-yourself tools. You actually have to build the Auto Scaling for them! There's no console or some tool that provide AutoScaling. You have to program or pay  programmer to build such tool. They advertise AutoScaling but it does not exist - you have to build it yourself? or I am missing something?
I looked at alternatives:
Rightscale looks like overkill for my simple setup. They operate with whole infrastructure deployments, not single servers. and entry cost is $2500 when my whole monthly budget is under $500.
Scalr. Seems more approachable then Rightscale. But like with Rightscale I couldn't find a way to bring my own server that is already running on EC2.
With Scalr and Rightscale it seems the only way to get in is to build server from scratch in their console and then somehow transfer the data?
I also looked at product called Ylastic. This is weirdest product of all. Registration requires some "Eucalyptus" account. And I read every page on Ylastic website, there's no mention what "Eucalyptus" is. How do you obtain it? is it a program you install on your EC2 instance or some third party service?
I am completely baffled by lack of this simple possibility- to start new EC2 instance when one fails or eats 100% CPU.
It looks like there only tools there are either for Enterprise users who build whole solution farms. Or bunch of do-it-yourself tools that require a programmer.
Is there a middle ground?
Thanks.

A: Not that I've found, because scaling is a rather situation-dependent thing.
I'm facing a similar problem myself (and looking at similar products) and we'll likely end up rolling our own. The big problem is that there is no slider-bar on web-scale where at one side of the slider you have a single server running both web and DB, and at the other end of the slider you have multiple availability zones with web-serving clusters on anycasted IP addresses hiding behind memcachd, and significantly sharded and replicated databases. How you plot the slider from one side to the other depends entirely on your application code.
If growth is at all possible for your app, these scaling issues need to be thought about and your auto-scale system built to accommodate.

A: Autoscaling DOES exists, it just haven't graphic interface and instead have command-line interface. You don't need programmer, you only need someone to spend few hours reading documentation and make a few command line calls.
Take a look at the link below - it have an example of 7 command line calls you need to make it running.
http://docs.amazonwebservices.com/AutoScaling/latest/DeveloperGuide/index.html?US_SetUpASLBApp.html
BTW, your web servers are read-only, right ? They don't have some database to update or so ?
And I'd agree, if it's just a web server, maybe EC2 is an overkill and web hosting provider is the right answer ?

A: Ylastic actually provides GUI for EC2 autoscaling features.
You can signup for Ylastic here: https://dashboard.ylastic.com/signup?plan=basic.

A: Following Joe's questions about Scalr (Disclaimer: I work at Scalr), it is not exactly true to say that you need to restart from scratch when you use Scalr for the first time. You can "import" your servers that are already running on EC2 in Scalr. To do so, you need to use the feature called "Create role from non-Scalr server". You can find more information about it on our wiki.
I don't know if RightScale does such a feature or not, but you can definitely do it with Scalr. I hope this helps.

A: I think Ylastic does a great job for AWS Auto Scaling plus it does a lot more. You can also try EZAutoScaling, it is essentially a GUI for AWS Auto Scaling and that's all it does for a very cheap price.

A: Another GUI for Amazon's Auto Scaling service is Asgard, a free and open source application from Netflix for cloud management and application deployment in AWS, focusing primarily on Auto Scaling Groups.


text:
Q: How do I redirect after success in php I need some help with my php. I am creating an ajax php mailer system, and I'm trying to figure out two things, I want to make it so when the email is successfully sent, to redirect to another page
and, I have another problem, when I send an email, the 'from' part has a name of my web host username, and I want to change it to my email, anyone know how to do that with php, or ajax.
php file
<?php

        // Only process POST reqeusts.
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            // Get the form fields and remove whitespace.
            $name = strip_tags(trim($_POST["name"]));
            $phone = trim($_POST["tel"]);
            $time = trim($_POST["time"]);
            $method = trim($_POST["method"]);
                    $name = str_replace(array("\r","\n"),array(" "," "),$name);
            $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
            $message = trim($_POST["message"]);

            // Check that data was sent to the mailer.
            if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                // Set a 400 (bad request) response code and exit.
                http_response_code(400);
                echo "Oops! There was a problem with your submission. Please complete the form and try again.";
                exit;
            }

            // Set the recipient email address.
            // FIXME: Update this to your desired email address.
            $recipient = "WebInquiry@ThePPCGroup.Com";

            // Set the email subject.
            $subject = "New contact from $name";
            $msg = "Thank you for contacting ThePPCGroup.\nSomeone will contact you shortly. Please let us know the best time to reach you, and if phone or email is better.\nThePPCGroup\n855-539-4742\nWebInquiry@ThePPCGroup.Com\nWWW.ThePPCGroup.Com";
            // Build the email content.
            $email_content = "Name: $name\n";
            $email_content .= "Email: $email\n\n";
            $email_content .= "Phone: $phone\n\n";
            $email_content .= "Prefered Time: $time\n\n";
            $email_content .= "Prefered Method: $method\n\n";
            $email_content .= "Message:\n$message\n";

            // Build the email headers.
            $email_headers = "From: $name <$email>";

            // Send the email.
            if (mail($recipient, $subject, $email_content, $email_headers)) {
                // Set a 200 (okay) response code.
                http_response_code(200);
                mail($email, "Thank You!", $msg, "WebInquiry@ThePPCGroup.Com")
            } else {
                // Set a 500 (internal server error) response code.
                http_response_code(500);
                echo "Oops! Something went wrong and we couldn't send your message.";
            }

        } else {
            // Not a POST request, set a 403 (forbidden) response code.
            http_response_code(403);
            echo "There was a problem with your submission, please try again.";
        }

    ?>

ajax file
function sendEmail() {
    var form = $('#ajax-contact');
    var formMessages = $('#form-messages');
    var formData = $(form).serialize();

    $(form).submit(function(event) {
        event.preventDefault();
    });

    $.ajax({
      type: 'POST',
      url: $(form).attr('action'),
      data: formData
    })

    .done(function(response) {
      $(formMessages).removeClass('error');
      $(formMessages).addClass('success');

      $(formMessages).text(response);
      $('#name').val('');
      $('#email').val('');
      $('#tel').val('');
      $('#time').val('');
      $('#method').val('');
      $('#message').val('');
      window.location = 'http://www.theppcgroup.com/thank-you.html';
    })

    .fail(function(data) {
      $(formMessages).removeClass('success');
      $(formMessages).addClass('error');

      if (data.responseText !== '') {
          $(formMessages).text(data.responseText);
      } else {
          $(formMessages).text('Oops! An error occured and your message could not be sent.');
      }
    });
  }

if ($('#submit').on('click', function() {
  sendEmail();
}));

A: You can return an array to the ajax function like this:
// Send the email.
            if (mail($recipient, $subject, $email_content, $email_headers)) {
                // Set a 200 (okay) response code.
                http_response_code(200);
                mail($email, "Thank You!", $msg, "WebInquiry@ThePPCGroup.Com");
                $response = array('status': true, 'message': "Thank You!");
            } else {
                // Set a 500 (internal server error) response code.
                http_response_code(500);
                $response = array('status': false, 'message': "Oops! Something went wrong and we couldn't send your message.");
            }
        } else {
            // Not a POST request, set a 403 (forbidden) response code.
            http_response_code(403);
            $response = array('status': false, 'message': "There was a problem with your submission, please try again.");
        }
        return json_encode($response);

and in ajax
.done(function(response) {
      $(formMessages).removeClass('error');
      $(formMessages).addClass('success');

      $(formMessages).text(response.message);
      $('#name').val('');
      $('#email').val('');
      $('#tel').val('');
      $('#time').val('');
      $('#method').val('');
      $('#message').val('');
      if (response.status == true){
       window.location = 'http://www.theppcgroup.com/thank-you.html';
      }
    })


text:
Q: MooTools: Element disposal Let's say I have two elements on a page. One is a div, and the other is its child, an achor. Let's say that I've added an event to that anchor via anchor.addEvent('click', ...). If I set the div's .innerHTML = '', does the 'click' event associated with the anchor get removed/disposed of/garbage collected?

A: It depends if you have still reference to "anchor" DOM instance. If so, it will stay in memory until all references are removed.
Test example:
var parent = new Element('div');
var child = new Element('div', {
    events : {
        click : function() {
            alert('child clicked');
        }
    }
});
child.innerHTML = 'child content';
parent.appendChild(child);
document.body.appendChild(parent);
parent.innerHTML = 'parent content';
document.body.appendChild(child);

A: According to the MooTools API: destroy() is a method that:

Empties an Element of all its children, removes and garbages the Element. Useful to clear memory before the pageUnload.

I suspect that what happens to anchors removed when their parent elements are removed using innerHTML = '' is going to depend on the browser.
jQuery offers an empty() method, I am guessing other libraries probably offer methods too. You can see a pretty good discussion of this topic in Removing an element from DOM.

A: *

*IMHO, you should use empty() instead of innerHTML = "".

*The reference will remain like @nemisj said, but it will be "floating" and useless.
I did some tests here: test case, maybe you'll find interesting.


text:
Q: Knockout.js v2.3.0 error "You cannot apply bindings multiple times to the same element" I've just upgraded to Knockout.js 2.3.0 and now I'm getting this error:
You cannot apply bindings multiple times to the same element.

which I wasn't getting in 2.2.1.
I'm getting a partial view from my MVC controller and adding it to the page after clicking on an href. The error happens the second time I click on the link to get the partial view. I'm doing this multiple times.
Is there a way to clear this out and avoid the new error thrown?
Here's my code:
$.get(url + "GetAssignedCompaniesView?layoutId=" + layoutId + "&noCache=" + new Date().getMilliseconds(), function (result) {
    $("#editAssignedPartial").html($(result));
    showEditAssignedArea(true);
    $(window.document).ready(function () {
        // error is thrown here
        ko.applyBindings(self, window.document.getElementById("editAssigned"));
        $("#layoutId").attr("value", layoutId);
        updateTypeHiddenElement.attr("value", "companies");
    });
});

Here's my HTML:

$(document).ready(function () {
    'use strict';
    var vm = new Vm();
    ko.applyBindings(vm, document.getElementById("area1"));
});

A: There are a lot of great answers for this issue but I have a newbie answer.
I found that I accidentally added the same script in two places and it was trying to bind twice. So before you pull your hair out, make sure you check for this issue.

A: If you are reusing an element over and over (a Bootstrap modal dialog in my case), then calling ko.applyBindings(el) multiple times will cause this problem.
Instead just do it once like this:
if (!applied) {
    ko.applyBindings(el);
    applied = true;
}

Or like this:
var apply = function (viewModel, containerElement) {
    ko.applyBindings(viewModel, containerElement);
    apply = function() {}; // only allow this function to be called once.
}

PS: This might happen more often to you if you use the mapping plugin and convert your JSON data to observables.

A: I finally solved mine by returning { controlsDescendantBindings: true } in the init function of the binding handler. See this.

A: Something that can happen as well which throws this exception is the following. Say you have:
ko.applyBindings(myViewModel1, document.getElementById('element1'));
...
ko.applyBindings(myViewModel2, document.getElementById('element2'));

Now, when both #element1 and #element2 don't exist you'll get the error. The reason is that Knockout's applyBindings falls back on document.body as root element when #element1 and #element2 are not found. Now it tries to apply binding twice on the body...
Not a nice fallback of Knockout if you ask me. I'd rather have a clear error message that the element does not exist in the DOM (yet).

A: Updated Answer
Now that we can use dataFor() to check if the binding has been applied, I would prefer check the data binding, rather than cleanNode() and applyBindings().
Like this:
var koNode = document.getElementById('formEdit');
var hasDataBinding = !!ko.dataFor(koNode);
console.log('has data binding', hasDataBinding);
if (!hasDataBinding) { ko.applyBindings(vm, koNode);}

Original Answer.
A lot of answers already!
First, let's say it is fairly common that we need to do the binding multiple times in a page. Say, I have a form inside the Bootstrap modal, which will be loaded again and again. Many of the form input have two-way binding.
I usually take the easy route: clearing the binding every time before the the binding.
var koNode = document.getElementById('formEdit');
ko.cleanNode(koNode);
ko.applyBindings(vm, koNode);

Just make sure here koNode is required, for, ko.cleanNode() requires a node element, even though we can omit it in ko.applyBinding(vm).

A: You should never apply bindings more than once to a view. In 2.2, the behaviour was undefined, but still unsupported. In 2.3, it now correctly shows an error. When using knockout, the goal is to apply bindings once to your view(s) on the page, then use changes to observables on your viewmodel to change the appearance and behaviour of your view(s) on your page.

A: Two things are important for above solutions to work:

*

*When applying bindings, you need to specify scope (element) !!

*When clearing bindings, you must specify exactly same element used for scope.
Code is below
Markup

    <input type="text" data-bind="value: text1" >
</form>

Binding view
var myViewModel = {
  "data" : {
    "text1" : "bla bla"
  }
}:

Javascript
ko.applyBindings(myViewModel, document.getElementById('elt1'));

Clear bindings
ko.cleanNode(document.getElementById('elt1'));

A: You need to remove the bindings before you use applyBindings again:
ko.cleanNode($element[0]);

A: I had this error occur for a different reason.
I created a template for save/cancel buttons that I wanted to appear at top and bottom of the page.  It worked at first when I had my template defined inside of a


text:
Q: Visibility of reintroduced constructor I have reintroduced the form constructor in a base form, but if I override the original constructor in a descendant form, the reintroduced constructor is no longer visible.
type
  TfrmA = class(TForm)
  private
    FWndParent: HWnd;
  public
    constructor Create(AOwner: TComponent; const AWndParent: Hwnd); reintroduce; overload; virtual;
  end;

constructor TfrmA.Create(AOwner: TComponent; const AWndParent: Hwnd);
begin
  FWndParent := AWndParent;
  inherited Create(AOwner);
end;

type
  TfrmB = class(TfrmA)
  private
  public
  end;

type
  TfrmC = class(TfrmB)
  private
  public
    constructor Create(AOwner: TComponent); override;
  end;

constructor TfrmC.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
end;

When creating:
  frmA := TfrmA.Create(nil, 0);
  frmB := TfrmB.Create(nil, 0);
  frmC := TfrmC.Create(nil, 0); // Compiler error

My work-around is to override the reintroduced constructor or to declare the original constructor overloaded, but I'd like to understand the reason for this behavior.
type
  TfrmA = class(TForm)
  private
    FWndParent: HWnd;
  public
    constructor Create(AOwner: TComponent); overload; override;
    constructor Create(AOwner: TComponent; const AWndParent: Hwnd); reintroduce; overload; virtual;
  end;

type
  TfrmC = class(TfrmB)
  private
  public
    constructor Create(AOwner: TComponent; const AWndParent: Hwnd); override;
  end;

A: In your initial code your Create constructor hides the original Create. Which is why the compiler complains about TfrmC overriding a constructor it can no longer see from there.
You would normally get a compiler message about this, but "reintroduce" suppresses this. Whenever you need "reintroduce" to suppress compiler messages, alarm bells should go off as it is an indication that you are breaking polymorphism. Doesn't mean you shouldn't use it, but you should be aware of the implications.
In these cases, if I want to retain the ability to override the original constructor, I tend to add a different constructor, ie
constructor CreateWithParent(AOwner: TComponent; const AWndParent: HWnd); virtual;

and call the original constructor in its implementation. It does mean I need to call a different constructor, but as you already need to pass another parameter, that doesn't seem like such a bad trade-off.
Edit:
As I mentioned in the comments, the compiler complains about tfrmC.Create(nil, 0); having too many parameters. It seems as though tfrmC.Create(AOwner) hides tfrmA.Create(AOwner, AWndParent); Thinking about it on the way home (traffic jams seem to have an advantage after all), there is an explanation for this.
1) The overload on the tfrmA.Create serves no direct purpose other than to allow introduction of other constructors with the same name.
2) The TfrmC constructor effectively hides the TfrmA constructor, reintroducing the signature that was hidden by the TfrmA constructor. In effect this isn't an override of the original constructor but a re-introduction of a re-introduced one.
3) I feel the compiler should have emitted a warning about this hiding. The reason it doesn't is possibly the overload directive on the TfrmA constructor. When you remove that, you get an error about the TfrmC.Create declaration differing from the previous one.
4) As the TfrmA constructor was hidden by TfrmC the compiler correctly complains about TFrmC.Create(nil, 0) having too many parameters.
What is described under 2) becomes obvious when you add the signature of the TfrmA constructor to TfrmC with just the override directive. This constructor is then immediately redlined by the IDE. The reason: two constructors with the same name and  a missing overload directive for the TfrmC constructor that only has the AOwner parameter.
It also becomes clear when you comment out the second parameter in the instantiation of tfrmC and had only coded "inherited;" instead of "inherited Create(AOwner);" in its implementation. The compiler then complains about incompatible types.
The latter could have been solved by using either "inherited Create(AOwner);" (as you did) or "inherited Create(AOwner, 0);". While the latter would have ensured a walk back up the inheritance tree, the former would have jumped straight back to TForm1.Create.
Using a slightly modified version of your code and provided TfrmC is instantiated with a single parameter, the result of "inherited Create(AOwner)" would have been:
alt text http://www.bjmsoftware.com/delphistuff/overloading/InheritedCreate1Param.jpg
while the result of "inherited Create(AOwner, 0);" would have been:
alt text http://www.bjmsoftware.com/delphistuff/overloading/InheritedCreate2Params.jpg
Adding overload to the TfrmC constructor as I suggested in the comments overrides the original TForm1.Create and allows for two constructors with the same name. This can be illustrated in the test project by turning on the TFRMC_OVERLOAD and INSTANTIATE2 conditional defines. This instantiates TfrmC with TfrmC.Create(nil, 0) and results in:
alt text http://www.bjmsoftware.com/delphistuff/overloading/InheritedCreate2ParamsOverload.jpg
Which shows TfrmB.Create being called for TfrmC as TfrmB is the first ancestor with an implementation for the two-parameter constructor. While instantiating TfrmC with TfrmC.Create(nil) (turn the INSTANTIATE2 conditional define back off), results in the same picture as the first or second (depending on the TWOPARAMS define).

A: All methods declared with the same name need to be overloaded. The scope is the current class declaration.
The simplest solution is to use the overload directive again:
type
  TfrmC = class(TfrmB)
  private
  public
    constructor Create(AOwner: TComponent); overload; override;
  end;

The reason is because the original constructor in TCustomForm was not declared as overloaded.


text:
Q: Empty rows in report when using count function I am using BIRT reporting with my mongodb datasource. I am trying to COUNT some events. COUNT function gives the correct value but there is big empty space at the end of the page depending upon the count value. If the count value is big then the rest of the page is empty and on the next page same record is coming e.g. :
In this Image the rest of the page is empty and same record is coming on the next pages also. It looks like empty spaces are being printed.

This is how my report looks like :

The COUNT function:

I have tried using SUM also but I get this error when I use SUM function instead of COUNT :
    org.eclipse.birt.report.engine.api.EngineException: A BIRT exception occurred. See next exception for more information.
Can not convert the value of True to Double type.
   at org.eclipse.birt.report.engine.executor.ExecutionContext.addException(ExecutionContext.java:1245)
   at org.eclipse.birt.report.engine.executor.ExecutionContext.addException(ExecutionContext.java:1224)
   at org.eclipse.birt.report.engine.executor.DataItemExecutor.execute(DataItemExecutor.java:101)
   at org.eclipse.birt.report.engine.internal.executor.wrap.WrappedReportItemExecutor.execute(WrappedReportItemExecutor.java:46)
   at org.eclipse.birt.report.engine.internal.executor.emitter.ReportItemEmitterExecutor.execute(ReportItemEmitterExecutor.java:46)
   at org.eclipse.birt.report.engine.internal.executor.dup.SuppressDuplicateItemExecutor.execute(SuppressDuplicateItemExecutor.java:43)
   at org.eclipse.birt.report.engine.layout.html.HTMLAbstractLM.execute(HTMLAbstractLM.java:468)

Please help, thanks in Advance.

A: I got the issue to this problem. If we select "Hide Detail" Option from the group then this problem go away.


text:
Q: python sort dictionary by descending order of key I want to sort this dictionary d based on integer keys.
d = { '123': 'aaa',
      '124': 'bbb,
      '125': 'ccc',
    }

So final dictionary would look like this.
d = { '125': 'ccc',
      '124': 'bbb',
      '123': 'aaa,
    }

I know that Dictionaries do not have any inherent order. But is it achievable?


text:
Q: EasyShell doesn't open terminal correctly on Ubuntu I'm using EasyShell plugin with Eclipse Kepler on Ubuntu 14.04
The plugin works fin when I choose to explore a folder or a file but It doesn't work if I choose to open the selected file\folder in a terminal. It always opens the terminal to my home folder.
The configured gnome-terminal commands runs fine manually, but not through the plugin.

A: I fixed it by just removing the quotation marks.

A: I had the exact same problem.  I'm not sure how to fix it via the UI, but you can directly edit the preferences file to fix it:
Edit this file:
[WORKSPACE]/.metadata/.plugins/org.eclipse.core.runtime/.settings/com.tetrade.eclipse.plugins.easyshell.prefs

And add this:
targetPreference=gnome-terminal --working-directory\={1}

A: For those, whose problem is not resolved, my solutions is as follows;

*

*Go to preferences -> Easyshell

*Find Open (Gnome) Terminal here and click on it

*Click on edit and change the command with
gnome-terminal --working-directory=${easyshell:container_loc}


text:
Q: Socket.IO ERR_CONNECTION_REFUSED I am getting this error:

WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=3&transport=websocket' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

I have looked for this error but it seems for me that my configuration of the sockets is well and I do not think is for the warning of electron.
var express  = require('express');
var app      = express();
var server   = require('http').Server(app);
var io    = require('socket.io')(server);

var JSONTCPSOCKET = require('json-tcp-socket');
var JSONTCPSOCKET = new JSONTCPSOCKET({tls: false});

require("./rabbit")(io, JSONTCPSOCKET);

  var socket = io('http://localhost:8000',{transports: ['websocket',
    'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling', 'polling']});

Any idea?
Thanks mates!!

A: It was a silly mistake.
The file that contains the server that listen in that port is in my case server.js.
When you run it with node, the start file is server.js but when you run it with electron the start file is main.js and I was never running server.js when I executed with electron, so I was not listening in that port.


text:
Q: How can I attach source to an Android eclipse project dependencies? I have two Android eclipse projects, one that contains my application and one set as library that contains common code. The application project uses the common project as a dependency, when I attempt to debug the code in the common project by stepping through the application project I get this error:
The JAR of this class file belongs to container 'Android Dependencies' which does not allow modifications to source attachments on its entries
I am already aware of this answer which covers attaching sources to JARs, but it does not mention anywhere how to do the same for eclipse project dependencies.
How can I attach source to an Android eclipse project dependencies?


text:
Q: My loop does not work inside my getJson call my console.log(url) return the same thing every time but when i console it outside the json call, everything work just fine. why is that and how i can fix it? the for loop is counting before the Json make the call. for example when i console the i inside the Json it returns the number 8, 8 times but if i console the i outside de json but inside the for loop it returns 0 to 7
$(document).ready(function(){
    var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx","RobotCaleb","noobs2ninjas"];
    for(var i = 0;i<channels.length;i++){
        var url='https://api.twitch.tv/kraken/channels/'+channels[i]+'?client_id=pd57d4ktf8rjarn9q3qgtv4owbr5q0';
        console.log(url);
        $.getJSON(url,function(data){
            console.log(url);
        });
 }});

A: The two links in the comments give reasons for why this is happening but the specific reason you are seeing this is because your getJSON call is asynchronous. Your loop will complete before the callback that you pass to getJSON is executed. That is why your console.log outside of the callback is what you expect but the one inside the callback logs out the same end state 8 times.
The following snippet hopefully will give you a clearer indication of what is happening. Notice how the "In loop" lines all happen before any of the "In callback" lines.

for(var i = 0; i < 5; i++) {
  console.log("In loop", i);

  // Simulate an asynchronous request
  setTimeout(function() {
    /*
      By the time this executes, i has been incremented
      to 5 so the loop is finished.
    */
    console.log("In callback", i);
  }, 1);
}


text:
Q: Unable to Marshal value on Serializable Data I get the following error when trying to pass a HashMap to my MainActivity class (TabooCards implements Serializable). I read around here that HashMap is serializable, and that any Objects contained in the HashMap must also be serializable. I assume Integer is serializable, and I know TabooCards is serializable, so what's going wrong?
Code:
AsyncTask onPostExecute:
protected void onPostExecute(HashMap<Integer, TabooCard> result) {
            super.onPostExecute(result);
            Intent i = new Intent(getBaseContext(), MainActivity.class);
            i.putExtra("TABOO_CARDS", tabooCards);
            startActivity(i);
        }

TabooCards:
public class TabooCard implements Serializable{

    /**
     *
     */
    private static final long serialVersionUID = -6996042490365349623L;
    String mainWord, taboo1, taboo2, taboo3, taboo4, taboo5;

    public TabooCard() {
        this("Main Card", "Taboo 1", "Taboo 2", "Taboo 3", "Taboo 4", "Taboo 5");
    }

    public TabooCard(String mainword, String taboo1, String taboo2, String taboo3, String taboo4, String taboo5) {
        setMainWord(mainword);
        setTaboo1(taboo1);
        setTaboo2(taboo2);
        setTaboo3(taboo3);
        setTaboo4(taboo4);
        setTaboo5(taboo5);
    }

      //Various getter/setter methods

Logcat
   E/AndroidRuntime(28441): FATAL EXCEPTION: main
E/AndroidRuntime(28441): Process: com.jaytj.taboo, PID: 28441
E/AndroidRuntime(28441): java.lang.RuntimeException: Parcel: unable to marshal value com.jaytj.taboo.TabooCard@42d2fce8
E/AndroidRuntime(28441):        at android.os.Parcel.writeValue(Parcel.java:1266)
E/AndroidRuntime(28441):        at android.os.Parcel.writeMapInternal(Parcel.java:594)
E/AndroidRuntime(28441):        at android.os.Parcel.writeMap(Parcel.java:578)
E/AndroidRuntime(28441):        at android.os.Parcel.writeValue(Parcel.java:1197)
E/AndroidRuntime(28441):        at android.os.Parcel.writeArrayMapInternal(Parcel.java:618)
E/AndroidRuntime(28441):        at android.os.Bundle.writeToParcel(Bundle.java:1692)
E/AndroidRuntime(28441):        at android.os.Parcel.writeBundle(Parcel.java:636)
E/AndroidRuntime(28441):        at android.content.Intent.writeToParcel(Intent.java:7410)
E/AndroidRuntime(28441):        at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:2289)
E/AndroidRuntime(28441):        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1437)
E/AndroidRuntime(28441):        at android.app.Activity.startActivityForResult(Activity.java:3511)
E/AndroidRuntime(28441):        at android.app.Activity.startActivityForResult(Activity.java:3472)
E/AndroidRuntime(28441):        at android.app.Activity.startActivity(Activity.java:3714)
E/AndroidRuntime(28441):        at android.app.Activity.startActivity(Activity.java:3682)
E/AndroidRuntime(28441):        at com.jaytj.taboo.SplashActivity$AsyncWordGrabber.onPostExecute(SplashActivity.java:47)
E/AndroidRuntime(28441):        at com.jaytj.taboo.SplashActivity$AsyncWordGrabber.onPostExecute(SplashActivity.java:1)
E/AndroidRuntime(28441):        at android.os.AsyncTask.finish(AsyncTask.java:632)
E/AndroidRuntime(28441):        at android.os.AsyncTask.access$600(AsyncTask.java:177)
E/AndroidRuntime(28441):        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
E/AndroidRuntime(28441):        at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(28441):        at android.os.Looper.loop(Looper.java:157)
E/AndroidRuntime(28441):        at android.app.ActivityThread.main(ActivityThread.java:5356)
E/AndroidRuntime(28441):        at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(28441):        at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(28441):        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
E/AndroidRuntime(28441):        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
E/AndroidRuntime(28441):        at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
E/AndroidRuntime(28441):        at dalvik.system.NativeStart.main(Native Method)

A: Use Parcelable and not Serializable.
Read this tuto
This is how your class should be :
import android.os.Parcel;

import android.os.Parcelable;

public class TabooCard implements Parcelable {

    public static final Parcelable.Creator<TabooCard> CREATOR = new Parcelable.Creator<TabooCard>()
    {
        @Override
        public TabooCard createFromParcel(Parcel source)
        {
            return new TabooCard(source);
        }

        @Override
        public TabooCard[] newArray(int size)
        {
            return new TabooCard[size];
        }
    };

    String mainWord, taboo1, taboo2, taboo3, taboo4, taboo5;

    public TabooCard() {
        this("Main Card", "Taboo 1", "Taboo 2", "Taboo 3", "Taboo 4", "Taboo 5");
    }

    public TabooCard(String mainword, String taboo1, String taboo2, String taboo3, String taboo4, String taboo5) {
        setMainWord(mainword);
        setTaboo1(taboo1);
        setTaboo2(taboo2);
        setTaboo3(taboo3);
        setTaboo4(taboo4);
        setTaboo5(taboo5);
    }

    public TabooCard(Parcel in) {
        setMainWord(in.readString());
        setTaboo1(in.readString());
        setTaboo2(in.readString());
        setTaboo3(in.readString());
        setTaboo4(in.readString());
        setTaboo5(in.readString());
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(mainWord);
        dest.writeString(taboo1);
        dest.writeString(taboo2);
        dest.writeString(taboo3);
        dest.writeString(taboo4);
        dest.writeString(taboo5);
    }


text:
Q: Defining the context of a word - Python I think this is an interesting question, at least for me.

I have a list of words, let's say:

photo, free, search, image, css3, css, tutorials, webdesign, tutorial, google, china, censorship, politics, internet

and I have a list of contexts:

*

*Programming

*World news

*Technology

*Web Design

I need to try and match words with the appropriate context/contexts if possible.
Maybe discovering word relationships in some way.

Any ideas?
Help would be much appreciated!

A: This sounds like it's more of a categorization/ontology problem than NLP. Try WordNet for a standard ontology.
I don't see any real NLP in your stated problem, but if you do need some semantic analysis or a parser try NLTK.

A: Where do these words come from?  Do they come from real texts.  If they are then it is a classic data mining problem.  What you need to do is to your set of documents into the matrix where rows represent which document the word came from and the columns represent the words in the documents.
For example if you have two documents like this:
D1: Need to find meaning.
D2: Need to separate Apples from  oranges
you matrix will look like this:
      Need to find meaning Apples Oranges Separate From
D1:   1     1   1     1      0      0       0       0
D2:   1     1   0     0      1      1       1       1

This is called term by document matrix
Having collected this statistics you can use algorithms like K-Means to group similar documents together.  Since you already know how many concepts you have your tasks should be soomewhat easier.  K-Means is very slow algorithm, so you can try to optimize it using techniques such as SVD

A: I just found this a couple days ago: ConceptNet
It's a commonsense ontology, so it might not be as specific as you would like, but it has a python API and you can download their entire database (currently around 1GB decompressed). Just keep in mind their licensing restrictions.
If you read the papers that were published by the team that developed it, you may get some ideas on how to relate your words to concepts/contexts.

A: The answer to your question obviously depends on the target taxonomy you are trying to map your terms into. Once you have decided on this you need to figure out how fine-grained the concepts should be. WordNet, as it has been suggested in other responses, will give you synsets, i.e. sets of terms which are more or less synonymous but which you will have to map to concepts like 'Web Design' or 'World News' by some other mechanism since these are not encoded in WordNet. If you're aiming at a very broad semantic categorization, you could use WordNet's higher-level concept nodes which differentiate, e.g. (going up the hierarchy) human from animal, animates from plants, substances from solids, concrete from abstract things, etc.
Another kind-of-taxonomy which may be quite useful to you is the Wikipedia category system. This is not just a spontaneous idea I just came up with, but there has been a lot of work on deriving real ontologies from Wikipedia categories. Take a look at the Java Wikipedia Library - the idea would be to find a wikipedia article for the term in question (e.g. 'css3'), extract the categories this article belongs to, and pick the best ones with respect to some criterion (i.e. 'programming', 'technology', and 'web-development'). Depending on what you're trying to do this last step (choosing the best of several given categories) may or may not be difficult.
See here for a list of other ontologies / knowledge bases you could use.


text:
Q: How do I prevent desktop shortcuts from being made in Windows? It is a common practice to have installers place shortcuts by default on the desktop, but most installers allow you to disable this by unchecking the appropriate checkbox. There are also installers (like Adobe Creative Cloud updates) that don't have an option to not place a shortcut on the desktop. I really hate desktop shortcuts but I still want to use my desktop for temporary files, quick management, etc. Is there any way I can automatically hide shortcuts (*.lnk files) on my desktop?

A: First, make a copy of your desktop (e.g. DesktopCopy folder containing the shortcuts you want on the desktop) and put it in the documents folder (or another user defined folder).
Secondly, create a batch file which will copy (and overwrite!) your desktop with the files from the DesktopCopy folder). You can use the mirror function of robocopy deleting files not present in the source directory.
Then, with the task scheduler create a task (CopyDesktopContents), which starts at windows start up or logging in and which runs the batch.
If you want to add your own shortcuts on your desktop, just do so and again copy the contents of your desktop to the DesktopCopy folder, so that next time you (or another user) starts up the computer or logs in, the new copy will be used by the batch file.

A: I have an easy way to do it.
Go to your File Explorer (ctr + e) and right-click the desktop folder. Next, click on properties and go to security tab, then click on edit and change the permission to deny for the users.

DENY

Then click apply and okay. NOW YOU'RE READY!

A: @ralf,  I tried your solution. After denying permissions, I restarted my PC. I got an error message something like, can't access the desktop. so your solution doesn't work. Can you or anyone else suggest a better solution?
Warm regards,
Raahul Dev
#DesigningLives

A: Our network spawns at least two shortcuts approximately every hour, which I despise. If I leave them alone, they just reside where they are, but if I delete them they come back within a couple of hours. There are also about a dozen other shortcuts they force onto our desktops which cannot be deleted by users at all. For the un-delete-able shortcuts, I conned an admin into creating an Unused Shortcuts folder and moving ALL of the unwanted, unused shortcuts into that folder where they only take up one spot on my desktop instead of 20. They're there, but I don't see them. For the two re-spawning shortcuts, I simply moved those to my least used monitor where their unwanted presence creates the least irritation.


text:
Q: PosgreSQL вставка в две таблицы за одну транзакцию Есть две таблицы. Нужно вставить данные в обе за одну транзакцию.
Планирую использовать конструкцию "BEGIN;...;COMMIT;"
Есть одна сложность - в поле второй таблицы нужно добавить id из первой таблицы, который генерируется автоматически.
Как это сделать?

A: Если ключ генерируется автоматически, то
create table t1 (id serial primary key, s varchar );
create table t2 (ref_id int, s varchar );

with i as (
    insert into t1(s) values ('text') returning id
)
insert into t2 (ref_id, s) select i.id, 'another text' from i;

А если ключ генерируется с помощью sequence, то
create sequence my_sequence;
create table t1 (id int primary key, s varchar );
create table t2 (ref_id int, s varchar );
insert into t1(id, s) values (nextval('my_sequence'), 'text');
insert into t2(ref_id, s) values (currval('my_sequence'), 'another text');

Впрочем, первый подход работает и с sequence тоже, да и вообще более гибкий, потому что позволяет протаскивать сколько угодно полей


text:
Q: Vim not using 256 color, ncurses-term installed, "xterm-256color: command not found" First I want to say I am using Ubuntu Mate 16.04.
I'm trying to get the solarized colorscheme to work in vim but am running into problems. It works fine in gvim, but I seem to only be getting 8 color support in vim.
It is also not specific to the solarized colorscheme, many other colorschemes do not appear correctly.
I have installed the ncurses-term package, and set TERM=xterm-256color in a variety of different ways (manually, in .bashrc, or as a command when mate-terminal is run).
When I run tput colors  I get 256
I also have, or have tried the following in different combinations in my .vimrc
 syntax on
 set t_Co=256
 let g:solarized_termcolors=256
 set background=dark

BUT when I run $TERM it gives me xterm-256color: command not found. I think this is where the issue is.
I also know that /lib/terminfo/x/xterm-256color exists, but /usr/share/terminfo/x/xterm-256color does not exist. Therefore I have tried copying xterm-256color into /usr/share/terminfo/x/ but that didn't help either.

A: Turns out I didn't take a close enough look at the 256-color palette, the colors I was looking for are not in the palette, and thus that is the reason I was having a problem.

A: Just go to the Preferences in the menu of the terminal and change the Profile colour scheme to reflect you want solarized.


text:
Q: How can I disable TCP/IP for an Ethernet adapter? I have CentOS 6.3 running in a (virtual) machine with two Ethernet adapters.  I have eth0 connected to a TCP/IP LAN and eth1 connected to a DSL modem.  The system is intended as a dedicated router/firewall, and has iptables set up to do SNAT, DNAT, and the desired filtering.
This was working great but I changed DSL modems and unfortunately the new (faster) one is idiotproofed and so automatically does NAT and will not allow me to pass my public IP along to eth1.  I can't tolerate double NAT so I did some research and read that this modem can be 'tricked' into giving my computer a public IP by doing the PPPoE on the computer.
I therefore set up pppd to use eth1, creating the ppp0 connection which I then substitute for eth1 in my custom iptables config script.  This seems to work to a degree but I had to open up the firewall to get it to work, and it's flaky.
Partly to help in troubleshooting, I want to totally rule out the possibility of any TCP/IP traffic being directly routed to eth1 where my 'friendly' modem will happily NAT it.
To the best of my knowledge, PPPoE sits below, not above IP - on the physical interface it deals directly in Ethernet frames.  Therefore I should not even have to have IP networking configured on eth1 at all in order for pppd to work, and IP networking running on eth1 therefore is just complicating matters needlessly.
Here's where I discover, silly me, I don't know how to disable the TCP/IP stack on Linux!  I know on a Windows box you can just uncheck the TCP/IP protocol in the adapter properties, but here I am running a text-only CentOS and I have no idea how to do it.
Apparently it's not a very common desire, because I've been searching the Internet to no avail.  It seems like a hard-wired assumption that an Ethernet adapter is a TCP/IP connection.  Well, usually...
Thanks for any help!
Kevin

A: Just remove the IPv4 and IPv6 addresses with ip addr flush dev eth1 and ip -6 addr flush dev eth1.

A: You can't disable TCP/IP but you can disable the interface: just run an ip link set eth1 down in the console.
Leave /etc/sysconfig/network-scripts/ifcfg-eth1 with only ONBOOT=no inside to make the change persistent.
Also check How to disable a NIC in CentOS?
PD: As gertvdijk noted, this will also disable the ability to run pppd through eth1.