text:
Q: clone  and add remove button In my template file I have something similar to this :
<select name="author[]">
{section name="something" loop=$something}
<option value="{$something[something].name}">{$something[something].name}</option>
{/section}
</select>

what I want is to create a button that adds another select element displaying the same options of my first select element. How can I do that using jQuery?
this jsfiddle does the same concept that I want. but adds a text input not a select input. also, it does not add any values from the first input.
What I want is a button that copies my select code and display it again with all its options and adds a remove button for each extra select element just like the example that I have provided.
[Edit]
Now I know that I can use clone to copy elements. But, I cannot seem to find a way to add a remove button for each element that I clone. How can that be done?
[Edit2]
This JSfiddle does the job of adding the remove button. However, I do not want the remove button to be displayed on my original select element
[Edit3]
I have manged to get what I wanted by using CSS to hide the remove button from the first select element see this JSFIDDLE. Nevertheless, I would like to see it executed by only using jQuery.

A: You could use jquery clone.
Something like this:
$('[name="author[]"]').clone().appendTo('#your_div_id_where_you_want_it');

You might want to give your select box an id to make selecting and cloning it look more clean. Also the [] in the name attribute may cause an issue so making an id would solve that too. The select would look like this if you want to add the id:
<select id="author" name="author[]">

And then the clone line would look like this:
  $('#author').clone().appendTo('#your_div_id_where_you_want_it');

A: jQuery's API features powerful selectors, which you can (and should) make use of:
Focusing on IDs alone complicates your code when you're dealing with dynamic DOM manipulations (which is the rule) - the recommendation is to use class selectors instead.
Your code can be as simple as:
jQuery(function($){
    $(".add").click(function() {
        $("#select").clone()
            .removeAttr("id")
            .append( $('Remove') )
            .appendTo("#additionalselects");
    });
    $("body").on('click',".delete", function() {
        $(this).closest(".input").remove();
    });
});

Here's a link to jsfiddle


text:
Q: What the word to describe this phenomenon? I wrote a program, it returned an error. But if I reopen it, run it again, it return the right answer perfectly.I remember Wiki have this item,but I can't remember.

A: Intermittent Error - An error that occurs sporadically, not consistently. It is the most difficult type of problem to diagnose and repair.

A: UNDEFINED BEHAVIOR.

It's a phrase, not a word. You are just (un)lucky it executed properly the second time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make single stacked bar chart in ggplot2? Ancestry <- data.frame(Race = c("European", "African American", "Asian", "Hispanic", "Other"), Proportion = c(40, 30, 10, 15, 5))
Ancestry %>%
ggplot(aes(y = Proportion, fill = Race)) +
  geom_bar(stat="identity", colour="white")

Running the above code gives me the following error:
Warning in min(x, na.rm = na.rm) :
  no non-missing arguments to min; returning Inf
Warning in max(x, na.rm = na.rm) :
  no non-missing arguments to max; returning -Inf
Warning in min(diff(sort(x))) :
  no non-missing arguments to min; returning Inf
Warning in x - width/2 :
  longer object length is not a multiple of shorter object length
Warning in x + width/2 :
  longer object length is not a multiple of shorter object length
Error in data.frame(list(y = c(40, 30, 10, 15, 5), fill = c(3L, 1L, 2L,  :
  arguments imply differing number of rows: 5, 2947

I'm looking to create a stacked barchart similar to this:

A: We can create a dummy variable to group all enteries into one group and then use geom_bar to create a stacked bar plot and use geom_text to name the Proportions.
library(ggplot2)

#Dummy group variable
Ancestry$row <- 1

#Create a label variable
Ancestry$percent <- (Ancestry$Proportion/sum(Ancestry$Proportion)) * 100

ggplot(Ancestry, aes(x = row,y = Proportion, fill = Race)) +
    geom_bar(stat="identity") +
    geom_text(aes(label = percent),
        position = position_stack(vjust = 0.5))

A: You need to create a dummy variable for x-axis. Then use geom_col which is similar to geom_bar(stat = "identity") to plot the stacked barplot + geom_text to put the text on the bar.
The plot you showed used theme_economist from the ggthemes package.
library(tidyverse)

Ancestry <- data.frame(Race = c("European", "African American", "Asian", "Hispanic", "Other"),
                       Proportion = c(40, 30, 10, 15, 5))

Ancestry <- Ancestry %>%
  mutate(Year = "2006")

ggplot(Ancestry, aes(x = Year, y = Proportion, fill = Race)) +
  geom_col() +
  geom_text(aes(label = paste0(Proportion, "%")),
            position = position_stack(vjust = 0.5)) +
  scale_fill_brewer(palette = "Set2") +
  theme_minimal(base_size = 16) +
  ylab("Percentage") +
  xlab(NULL)

library(ggthemes)

ggplot(Ancestry, aes(x = Year, y = Proportion, fill = Race)) +
  geom_col() +
  geom_text(aes(label = paste0(Proportion, "%")),
            position = position_stack(vjust = 0.5)) +
  theme_economist(base_size = 14) +
  scale_fill_economist() +
  theme(legend.position = "right",
        legend.title = element_blank()) +
  theme(axis.title.y = element_text(margin = margin(r = 20))) +
  ylab("Percentage") +
  xlab(NULL)

Created on 2018-08-26 by the reprex package (v0.2.0.9000).

A: You don't need to create a dummy grouping variable for x-axis to create a single stacked bar. You can just add an empty string within aes() for specific axis. Also, theme_blank() removes all unnecessary grid keeping it tidy.
library(tidyverse)
Ancestry <- tibble(Race = c("European", "African American", "Asian", "Hispanic", "Other"),
                   Proportion = c(40, 30, 10, 15, 5))
ggplot(Ancestry, aes(x = "", y = Proportion, fill = Race)) +
       geom_col() +
       geom_text(aes(label = paste0(Proportion, "%")),
                     position = position_stack(vjust = 0.5)) +
       scale_fill_brewer(palette = "Set2") +
       theme_blank() +
       labs(x="", y="Percentage")


text:
Q: batch file to check vpn connection when is online/up I need to check the vpn connection when is online/up with a batch file.
Actually i use this code:
PING -n 5 www.google.com|FIND /I "TTL">NUL

IF NOT "%ERRORLEVEL%"=="1" (
Echo "Vpn Connection Is Up"
)
IF "%ERRORLEVEL%"=="1" (
Echo "Vpn Connection Is Down"
)

Sometimes the ping give a non response or give a general failure response.
I would like to know that there is a better batch code alternative than the ping command.
I tried this alternative codes but do not recognize vpn when is online/up because the adapter is always in my pc installed.
First Alternative Code:
ipconfig|find /i "VPN" && GOTO startAPP || GOTO connectVPN

Second Alternative Code:
ipconfig|find /i "VPN"

if %errorlevle%==1 goto:connectVPN

echo Starting APP !
exit/b

:connectVPN
echo connecting to VPN

Third Alternative Code:
:start
cls
rasdial | find /I "%vpnname%" > nul
if errorlevel 1 goto vpndown
if errorlevel 0 goto vpnup

Can You recommend an alternative command to ping to be integrated into my batch code please ?
The alternatives code do not recognize when vpn connection is online, it's recognize if exist the adampter installed in my pc but i need to know when vpn is online/up (ready to go on internet).

A: Another way to do that, is to use rasdial command, which is used for VPN connections. Especially, use:
@echo off

rasdial | findstr /ic:"No" >nul
if not %errorlevel% EQU 0 (
    echo Found a VPN connection!
    goto :found
) else (
    echo We didn't find any VPN connections!
    goto :notfound
)

:found
rem Do something if a VPN connection is found/online:

:notfound
rem Do something if a VPN connection isn't found/online:

A: The best way to do this is using netsh wlan show networks. This command will show you your current connected network adapter. We can use find /I "VPN" to look is your VPN is currently connected. The %ERRORLEVEL% will allow you to extract a yes/no.
Is-VPN-Up.Bat:
netsh wlan show networks | FIND "VPN" /I /C >NUL
IF Not "%ERRORLEVEL%"=="1" (
    Echo "Vpn Connection Is Up"
) ELSE (
    Echo "Vpn Connection Is Down"
)

A: I think if you incorporate powershell into your batch (or powershell on its own) you can see if connection is up.
@echo off
for /f "tokens=2" %%i in ('powershell "Get-NetAdapter | select Name,Status" ^| findstr /i "Wifi"') do (
   if /i "%%i"=="up" echo VPN %%i
   if /i "%%i"=="down" echo VPN %%i
)

You could also make it ping google, first, then if an issue is found, ping the gateway, if there's an issue, check the connection, something almost like this:
@echo off
:start
ping -n 2 www.google.com | findstr /i "ttl">nul
if not "%errorlevel%"=="0" (
    echo "Oops something is wrong, let's test gateway"
    goto testgate
) else (
    echo "Internet Still reachable"
    timeout 5 /nobreak>nul
    goto start
)

:testgate
ping -n 2 10.3.1.1 | findstr /i "ttl">nul
if not "%errorlevel%"=="0" (
    echo "Hmm, gateway also not reachable, will test VPN"
        for /f "tokens=2" %%i in ('powershell "Get-NetAdapter | select Name,Status" ^| findstr /i "VPN"') do (
           if /i "%%i"=="up" (
               echo "Adapter connection %%i, will retry internet ping now"
               goto start
     ) else  (
               echo Adapter connection Down or Disconnected
               echo let's start something up
               pause
               goto start
               goto :eof
           )
        )
      ) else (
          echo "Gateway Connection Is Up"
          goto start
 )


text:
Q: Dynamic content without multiple pages Let me start by saying i am new to mysql and php, and I'm sure this is a noob question but I've been searching google and can't find any solution.
Basically I want to create 1 template file that will read all of a table from a database with multiple rows and columns but only display one row at a time.
An example would be http://www.w3schools.com/php/php_mysql_select.asp scroll towards the bottom where it shows peter griffen and glen quagmire i would want it to only display 'glen quagmire' or only display 'peter griffen' depending on which link was previously clicked.
would i need to somehow assign an ID to the link url so php knew which row to parse etc.. ?

A: One straightforward way is to use the query string.  Make the link View #1.  Then use a where id='$id' clause in the SQL query, setting $id equal to the query string parameter $_GET['id'].


text:
Q: How do unsigned transactions propagate when network compromised? say if my application is relatively new and has lesser nodes can be prone to 51% attack.
Example:
Person A - 100BTC
Person B - 50BTC
Person C - 0BTC (Malicious user)
If person C somehow get control over the network creates the longest Chain & has blocks with invalid transactions i.e. A sent to C 80 BTC & B sent to C 50 BTC which is not really signed by A & B with there privateKey(invalid transactions created by C).
The question here is tough Network is compromised as the transactions are not singed by original owners will the C able to spend them ? is consensus gone for a toss here? if I miss the trick somewhere please do point.

A: C cannot spend other's money, unless he could gain access other's private keys and sign transactions. Even if he try to, the block won't be considered as valid since transactions we'rent signed by the owners of the coin.

A: The rules, known to all participants, say that a transaction must be properly-signed. These are the very same rules that say how many bitcoins a transaction transfers. So if a transaction is not properly-signed, it does not transfer any bitcoins.
Let me state this again: There are rules that allow you to determine how many bitcoins a transaction transfers. These very same rules say that a transaction must be properly-signed. Therefore, a transaction that is not properly-signed does not transfer any bitcoins.
Nodes do not trust each other in the bitcoin network. Every message sent is checked for validity and, if invalid, it has to be ignored because it doesn't mean anything. A transaction that is not properly signed isn't a transaction, it's just garbage. Nodes can send you all the garbage they want to, but you'll never process any of it because you can't. Your code simply doesn't have rules to make sense of garbage.

A: I got my answer after detail research hope it makes sense.
Person C cannot spend A, B money. All he can do is reverse transactions and create a double spend situation and he can erase A, B transactions in the process of making a longest chain but cannot spend money from other wallets tough network is compromised because of private/public keys.


text:
Q: Troubles with gson.toJson(Collection) I have a problem with Gson to change a collection to a Json object. This is my code:
Collection<BomItem> items = bh.getAllItems();
Iterator<BomItem> itemIterator = items.iterator();

Collection<JsonItem> jsonItems = new Vector<JsonItem>();
JsonItem jsonItem = new JsonItem();

while(itemIterator.hasNext()) {
    BomItem item =  itemIterator.next();
    jsonItem.setItemId(item.getItemId());
    jsonItem.setName(item.getDescription());
    jsonItems.add(jsonItem);
}

System.out.println("json size:" + jsonItems.size());
Gson gson = new Gson();

String json = gson.toJson(jsonItems);
System.out.println("Json: " + json);

This is the output:
09:36:13,846 INFO  [STDOUT] json size:402
09:36:13,849 INFO  [STDOUT] Json: [{"itemId":68073,"name":"Automatically inserted"},{"itemId":68073,"name":"Automatically inserted"},{"itemId":68073,"name":"Automatically inserted"},...}

The JsonString is created, but only with the latest object, over and over again. What am I doing wrong?

A: You are no reinstantiating your jsonItem in the loop, meaning that you are adding over and over the same reference to a mutable object. The values are therefore always the ones of the last object of your collection.
Move JsonItem jsonItem = new JsonItem(); inside the while-loop.

A: while(itemIterator.hasNext()) {
    BomItem item =  itemIterator.next();

    //declare jsonitem inside the loop
    JsonItem jsonItem = new JsonItem();
    jsonItem.setItemId(item.getItemId());
    jsonItem.setName(item.getDescription());
    jsonItems.add(jsonItem);
}


text:
Q: What is the difference between SQLEXPRESS and MSSQLSERVER? I am using SQL Server 2008 R2, when I looked into the services for SQL Server I saw there are two different services with different instances.

*

*SQLEXPRESS

*MSSQLSERVER
Can anyone help me to get clear the difference between #1 and #2?
Thanks in advance

A: You can install multiple copies of SQL Server onto the same machine. To keep them apart, all "copies" (called instances) except the first (default) one have to be named.
So by default, when you install your first instance of SQL Server, you won't give it any instance name - it'll be the default instance that you connect to use the server name of ., (local) or your machine name (or IP address).
Any further instance you want to install needs to get a separate, unique instance name.
Visual Studio will by default install SQL Server Express onto your machine (unless you explicitly tell it not to), and that will be called the SQLEXPRESS instance on your machine (hence the service name also is called SQLEXPRESS). You connect to that named instance using .\SQLEXPRESS or (local)\SQLEXRPESS.
So most likely, in your case, you installed a "full" version of SQL Server onto your machine (as the default instance - service is called MSSQLSERVER), and Visual Studio installed a second copy of SQL Server - an Express version - as SQLEXPRESS

A: MSSQLSERVER is the default instance (accessed via localhost) and SQLEXPRESS is a named instance (accessed by localhost/SQLEXPRESS)
Did you install twice?


text:
Q: Uncaught ReferenceError: app is not defined at Controllers.js Currently I am working WCF project.I am trying to consuming Wcf service in Anjular JavaScript by using MVC. I am getting following error when I lunch developer tools in Google Chrome. I am following this tutorial which will be found on this link http://www.c-sharpcorner.com/uploadfile/rahul4_saxena/crud-operation-in-mvc4-using-angularjs-and-wcf-rest-services/. But when I run application in Google Chrome its gives me following errors and unable to display data from database and can not perform insert update and delete operation.
Controllers.js:5 Uncaught ReferenceError: app is not defined
    at Controllers.js:5
Modules.js:7 Uncaught ReferenceError: angular is not defined
    at Modules.js:7
    at Modules.js:8

My wcf service is working fine but AngularJS application is not working.
I also added AngularJS JavaScript package in my project .This is code for Controller. The name of the controller is CRUD_AngularJs_RESTController.
/// <reference path="../angular.min.js" />
/// <reference path="Modules.js" />
/// <reference path="Services.js" />

app.controller("CRUD_AngularJs_RESTController", function ($scope, CRUD_AngularJs_RESTService) {

$scope.OperType = 1;
//1 Mean New Entry

GetAllRecords();
//To Get All Records
function GetAllRecords() {
    var promiseGet = CRUD_AngularJs_RESTService.getAllStudent();
    promiseGet.then(function (pl) { $scope.Students = pl.data },
    function (errorPl) {
            $log.error('Some Error in Getting Records.', errorPl);
    });
}

//To Clear all input controls.
function ClearModels() {
    $scope.OperType = 1;
    $scope.StudentID = "";
    $scope.Name = "";
    $scope.Email = "";
    $scope.Class = "";
    $scope.EnrollYear = "";
    $scope.City = "";
    $scope.Country = "";
}

//To Create new record and Edit an existing Record.
$scope.save = function () {
    var Student = {
        Name: $scope.Name,
        Email: $scope.Email,
        Class: $scope.Class,
        EnrollYear: $scope.EnrollYear,
        City: $scope.City,
        Country: $scope.Country
    };
if ($scope.OperType === 1) {
    var promisePost = CRUD_AngularJs_RESTService.post(Student);
    promisePost.then(function (pl) {
        $scope.StudentID = pl.data.StudentID;
        GetAllRecords();

        ClearModels();
    }, function (err) {
            console.log("Some error Occured" + err);
        });
    } else {
        //Edit the record
        debugger;
        Student.StudentID = $scope.StudentID;
        var promisePut = CRUD_AngularJs_RESTService.put($scope.StudentID, Student);
        promisePut.then(function (pl) {
        $scope.Message = "Student Updated Successfuly";
        GetAllRecords();
        ClearModels();
    }, function (err) {
            console.log("Some Error Occured." + err);
        });
    }
};

//To Get Student Detail on the Base of Student ID
$scope.get = function (Student) {
    var promiseGetSingle = CRUD_AngularJs_RESTService.get(Student.StudentID);
    promiseGetSingle.then(function (pl) {
        var res = pl.data;
        $scope.StudentID = res.StudentID;
        $scope.Name = res.Name;
        $scope.Email = res.Email;
        $scope.Class = res.Class;
        $scope.EnrollYear = res.EnrollYear;
        $scope.City = res.City;
        $scope.Country = res.Country;
        $scope.OperType = 0;
    },
    function (errorPl) {
        console.log('Some Error in Getting Details', errorPl);
    });
}

This is the code for Module .The name of the Module is RESTClientModule
/// <reference path="../angular.min.js" />
var app;

(function () {
    app = angular.module("RESTClientModule", []);
})();

This is code for Service
/// <reference path="../angular.min.js" />
/// <reference path="Modules.js" />

app.service("CRUD_AngularJs_RESTService", function ($http) {
//Create new record
this.post = function (Student) {
    var request = $http({
        method: "post",
        url: "http://localhost:50028/StudentService.svc/AddNewStudent",
        data: Student
    });
    return request;
}

//Update the Record
this.put = function (StudentID, Student) {
    debugger;
    var request = $http({
        method: "put",
        url: "http://localhost:50028/StudentService.svc/UpdateStudent",
        data: Student
    });
    return request;
}

this.getAllStudent = function () {
    return $http.get("http://localhost:50028/StudentService.svc/GetAllStudent");
};

//Get Single Records
this.get = function (StudentID) {
    return $http.get("http://localhost:50028/StudentService.svc/GetStudentDetails/" + StudentID);
}

//Delete the Record
this.delete = function (StudentID) {
    var request = $http({
        method: "delete",
        url: "http://localhost:50028/StudentService.svc/DeleteStudent/" + StudentID
    });
    return request;
    }
});

Here is screen shot of result when I run the application.

A: You are using app before you have defined and initialised it.
app.controller("CRUD_AngularJs_RESTController", function ($scope, CRUD_AngularJs_RESTService)

You define it further down in the code:
var app;

(function () {
   app = angular.module("RESTClientModule", []);
})();

You should also be declaring it without being wrapped in the function.
var app = angular.module("RESTClientModule", []);

Then you can use, after it:
app.controller("CRUD_AngularJs_RESTController", function ($scope, CRUD_AngularJs_RESTService)

Got through the browser console and methodically address each error in turn like this.


text:
Q: Are `--events` and `--routines` really needed to get a `mysqldump --all-databases` of an entire mysql instance? Several fine answers on here have already exquisitely argued that
mysqldump --hex-blob --events --routines --triggers  [...]  --all-databases

should be all - modulo storage-engine considerations - one needs to get a

mysqldump of an entire mysql instance ... everything written in one file:
  table structures, indexes, triggers, stored procedures, users,
  encrypted passwords....

And I wanted to believe - and use - that; however, reading up on the manpage of mysqldump(1) (for MySQL 5.7.27) I find that:

*

*--events, -E
[...]
If you require events to be created with their original timestamp attributes, do not use --events. Instead, dump and reload
  the contents of the mysql.event table directly, using a MySQL account
  that has appropriate
  privileges for the mysql database.

... and that:

*

*--routines, -R
[...]
If you require routines to be created with their original timestamp attributes, do not use --routines. Instead, dump and reload
  the contents of the mysql.proc table directly, using a MySQL account
  that has appropriate
  privileges for the mysql database.

This leads me to believe that since --all-databases will also cause the mysql database to be included in the dump, and by that, the mysql.event and mysql.proc tables, that I would not have to include the --events and --routines options at all to arrive at an as-complete-as-possible dump.
What's more, including those options, I expect, would get me a less-than-complete dump instead because:

The output generated by using --events contains CREATE EVENT
  statements to create the events. However, these statements do not
  include attributes such as the event creation and modification
  timestamps, so when the events
  are reloaded, they are created with timestamps equal to the reload time.

... and likewise:

The output generated by using --routines contains CREATE PROCEDURE and
  CREATE FUNCTION statements to create the routines. However, these
  statements do not include attributes such as the routine creation and
  modification timestamps, so when the routines are reloaded, they are
  created with timestamps equal to the reload time.

Although, the mysql database would still also be included, so I'm not sure what the net effect combining --events and --routines with --all-databases will be in the resulting dump. I suspect it will depend on whether mysql will be dumped last, first, or somewhere in-between.
Does this reasoning make any sense or am I missing something?


text:
Q: Adding addition logic to a stored procedure Im working in a stored procedure where i need to update its function.
The Stored proc insert data to a table and add a 0 flag and we run a batch it will set the flag to 1 saying the record were already processed.
I am editing the stored proc to always insert a 1 flag to specific record so it would not be process.
The code work like this
INSERT INTO [dbo].[personel]
        ([FirstName]
        ,[LastName]
        ,[IdNo]
        ,[ProcessedIndicator]
        ,[CreateDate]
Select AP.FirstNm
    ,AP.LastNm
    ,AP.Idno
    ,CASE 0
       WHEN AP.Locotion = '' AND AP.Position 0001 BETWEEN  AND 0005
         THEN insert 1
       ELSE '0'
     END
    ,GetDate()
from dbo.AllPersonel AS AP

A: Your CASE statement has several syntax (and spelling) problems. Try this:
CASE
    WHEN AP.Location = '' AND AP.Position BETWEEN 0001 AND 0005 THEN 1
    ELSE '0'
END

The CASE statement has two flavours:
CASE someExpression
    WHEN someValue THEN someResult
    ...
    ELSE someDefault
END

or
CASE
    WHEN someCondition THEN someResult
    ...
    ELSE someDefault
END

You were trying to mix the two forms.


text:
Q: Can you load in a javascript file with HTTPS on an HTTP website? If I have a website called http://www.example.com .
Can I then load in an external javascript file truw HTTPS link like this: https://platform.twitter.com/widgets.js ?
Is this possible?
Thanks

A: Yes.
Just use a script tag as normal.

A: Do you have acces to the website? then it is fairly easy: 'import' this script on the webpage by setting the src to the url:
<script type="text/javascript" src="https://platform.twitter.com/widgets.js"></script>

Btw this goes in the head of your webpage.


text:
Q: Shortcut works, but properties dialog says target name is invalid I created a shortcut (in C:\Users\Public\Desktop) to a text file. I then right-clicked it and selected Properties. This opened the Properties Shortcut tab. I want to grant another user permission to edit the shortcut, but when I try to switch to the Security tab, I get:
Problem with Shortcut: The name ... is not valid
The shortcut works, opening the file, C:\Users\xxx\Desktop\create_project_tips.txt, in Notepad, when I click it, but the properties dialog doesn't like it.
Any ideas what is wrong?
In answer to a comment, the .txt file is/was already set to allow other users to both write and read it. I want to allow the short cut to also be modifiable by others.


text:
Q: Sufficient condition for a convex polynomial. Let
\begin{align*}
p(x)=\sum_{i=0}^{n}a_ix^i,
\end{align*}
I want to restrict the coefficients of $p(x)$ to make it convex.
Here are good answers,
https://mathoverflow.net/questions/28983/characterizing-convex-polynomials.
The first one is @coudy's answer, a direct way.
The second gives semidefinite matrix method using SOS equivalent property.
They can be used to generate convex polynomials well.
However,
they are not convenient to determine whether a polynomial is convex.
So I am seeking for a sufficient condition.
For example,
let $p(x)=a_4x^4+a_3x^3+a_2x^2+a_1x+a_0,$
then $p''(x)=12a_4x^2+6a_3x+2a_2.$
Thus, $p(x)$ is convex iff $(6a_3)^2-48a_2a_4\geq0.$
I think this is pretty good!
For higher degree,
is there a good way like this?
I just want some sufficient conditions about the coefficients of $p(x).$
I hope I've made my question clear,
and any help will be appreciated.


text:
Q: JSON String tidy/formatter for Java I have a valid JSON String that I want to tidy/format such that each property/value pair is on its own line, etc. (it currently is on one line with no spaces/line breaks).
I am using the Apache Sling JSONObject to model my JSON Object and turn it into a String, so if the Sling JSONObject can be set to output a tidy string (which I do not think it can) that would work too.
If I need a 3rd party lib I would prefer one with as few dependencies as possibles (such as Jackson which only requires the std JDK libs).

A: public static String formatJSONStr(final String json_str, final int indent_width) {
    final char[] chars = json_str.toCharArray();
    final String newline = System.lineSeparator();

    String ret = "";
    boolean begin_quotes = false;

    for (int i = 0, indent = 0; i < chars.length; i++) {
        char c = chars[i];

        if (c == '\"') {
            ret += c;
            begin_quotes = !begin_quotes;
            continue;
        }

        if (!begin_quotes) {
            switch (c) {
            case '{':
            case '[':
                ret += c + newline + String.format("%" + (indent += indent_width) + "s", "");
                continue;
            case '}':
            case ']':
                ret += newline + ((indent -= indent_width) > 0 ? String.format("%" + indent + "s", "") : "") + c;
                continue;
            case ':':
                ret += c + " ";
                continue;
            case ',':
                ret += c + newline + (indent > 0 ? String.format("%" + indent + "s", "") : "");
                continue;
            default:
                if (Character.isWhitespace(c)) continue;
            }
        }

        ret += c + (c == '\\' ? "" + chars[++i] : "");
    }

    return ret;
}

A: +1 for JohnS's gson answer, but here's a way with the "standard" JSONObject library:
public class JsonFormatter{

    public static String format(final JSONObject object) throws JSONException{
        final JsonVisitor visitor = new JsonVisitor(4, ' ');
        visitor.visit(object, 0);
        return visitor.toString();
    }

    private static class JsonVisitor{

        private final StringBuilder builder = new StringBuilder();
        private final int indentationSize;
        private final char indentationChar;

        public JsonVisitor(final int indentationSize, final char indentationChar){
            this.indentationSize = indentationSize;
            this.indentationChar = indentationChar;
        }

        private void visit(final JSONArray array, final int indent) throws JSONException{
            final int length = array.length();
            if(length == 0){
                write("[]", indent);
            } else{
                write("[", indent);
                for(int i = 0; i < length; i++){
                    visit(array.get(i), indent + 1);
                }
                write("]", indent);
            }

        }

        private void visit(final JSONObject obj, final int indent) throws JSONException{
            final int length = obj.length();
            if(length == 0){
                write("{}", indent);
            } else{
                write("{", indent);
                final Iterator<String> keys = obj.keys();
                while(keys.hasNext()){
                    final String key = keys.next();
                    write(key + " :", indent + 1);
                    visit(obj.get(key), indent + 1);
                    if(keys.hasNext()){
                        write(",", indent + 1);
                    }
                }
                write("}", indent);
            }

        }

        private void visit(final Object object, final int indent) throws JSONException{
            if(object instanceof JSONArray){
                visit((JSONArray) object, indent);
            } else if(object instanceof JSONObject){
                visit((JSONObject) object, indent);
            } else{
                if(object instanceof String){
                    write("\"" + (String) object + "\"", indent);
                } else{
                    write(String.valueOf(object), indent);
                }
            }

        }

        private void write(final String data, final int indent){
            for(int i = 0; i < (indent * indentationSize); i++){
                builder.append(indentationChar);
            }
            builder.append(data).append('\n');
        }

        @Override
        public String toString(){
            return builder.toString();
        }

    }

}

Usage:
public static void main(final String[] args) throws JSONException{
    final JSONObject obj =
            new JSONObject("{\"glossary\":{\"title\": \"example glossary\", \"GlossDiv\":{\"title\": \"S\", \"GlossList\":{\"GlossEntry\":{\"ID\": \"SGML\", \"SortAs\": \"SGML\", \"GlossTerm\": \"Standard Generalized Markup Language\", \"Acronym\": \"SGML\", \"Abbrev\": \"ISO 8879:1986\", \"GlossDef\":{\"para\": \"A meta-markup language, used to create markup languages such as DocBook.\", \"GlossSeeAlso\": [\"GML\", \"XML\"]}, \"GlossSee\": \"markup\"}}}}}");
    System.out.println(JsonFormatter.format(obj));
}

Output:
{
    glossary :
    {
        title :
        "example glossary"
        ,
        GlossDiv :
        {
            GlossList :
            {
                GlossEntry :
                {
                    SortAs :
                    "SGML"
                    ,
                    GlossDef :
                    {
                        GlossSeeAlso :
                        [
                            "GML"
                            "XML"
                        ]
                        ,
                        para :
                        "A meta-markup language, used to create markup languages such as DocBook."
                    }
                    ,
                    GlossSee :
                    "markup"
                    ,
                    GlossTerm :
                    "Standard Generalized Markup Language"
                    ,
                    ID :
                    "SGML"
                    ,
                    Acronym :
                    "SGML"
                    ,
                    Abbrev :
                    "ISO 8879:1986"
                }
            }
            ,
            title :
            "S"
        }
    }
}

A: With gson you can do:
JsonParser parser = new JsonParser();
Gson gson = new GsonBuilder().setPrettyPrinting().create();

JsonElement el = parser.parse(jsonString);
jsonString = gson.toJson(el); // done

A: The jackson way:
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
...
OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(node);

A: Many JSON libraries have a special .toString(int indentation) method
// if it's not already, convert to a JSON object
JSONObject jsonObject = new JSONObject(jsonString);
// To string method prints it with specified indentation
System.out.println(jsonObject.toString(4));

A: You don't need an outside library.
Use the built in pretty printer in Sling's JSONObject: http://sling.apache.org/apidocs/sling5/org/apache/sling/commons/json/JSONObject.html#toString(int)

public java.lang.String toString(int indentFactor)
                            throws JSONException
Make a prettyprinted JSON text of this JSONObject. Warning: This method assumes that the
  data structure is acyclical.
Parameters:
indentFactor - The number of spaces to add to each level
  of indentation.
Returns: a printable, displayable, portable,
  transmittable representation of the object, beginning with { (left
  brace) and ending with } (right brace).
Throws: JSONException - If the
  object contains an invalid number.

A: The JSON string will have a leading "[" and a trailing "]".  Remove these and then use the split method from String to separate the items into an array.  You can then iterate through your array and place the data into relevant areas.

A: if your using CQ5 or any JCR based CMS as i guess :)
you can use java json parser to do the job. it has a JSONObject class and a toString() method to convert it to String.
for further reference refer
http://json.org/java/

A: Underscore-java has statistic method U.formatJson(json). I am the maintainer of the library.
U.formatJson("{\"a\":{\"b\":\"data\"}}");

// {
//    "a": {
//      "b": "data"
//    }
// }


text:
Q: Pass Ruby object's instance variables to another class's initializer as a map I'm using the xml-mapping gem to read some XML, and I want to feed the mapping objects into the initializers for some existing domain classes. So given XML like:
<foo bar="baz"><qux>quux</qux></foo>

I get an object like:
#<Foo @bar="baz", @qux="quux">

I then want to feed it to a domain class like:
class MyFoo
  def initialize(bar:, qux:)
    # ... etc.
  end
end

(Note that in MyFoo the attributes are read-only, and there's some validation and transformation that goes on in the initializer, so it's not simply a matter of copying instance variables from one to the other.)
I tried transforming the instance variables to a map, thus:
foo.instance_variables.map { |name| [name, foo.instance_variable_get(name)] }.to_h

which produces:
{ :@bar->"baz", :@qux->"quux" }

This is almost what I need for the MyFoo initializer, but not quite -- what I need is
{ :bar->"baz", :qux->"quux" }

Is there a way to transform the instance variable names to symbols without the @-sign?
Alternatively, is there an easier way to say "initialize yourself from all the attributes in this object"?

A: Andrey's comment works fine, but I dislike relying on instance variables directly. I would suggest adding a custom to_h method to your Foo class. You could even tie this in with xml-mapping with the following:
class Foo
  # ...
  def self.__fields__
    @__fields__ ||= all_xml_mapping_nodes.map { |r| r.instance_variable_get(:@attrname) }
  end

  def to_h
    self.class.__fields__.each_with_object({}) do |field, acc|
      acc[field] = send(field)
    end
  end
end

Then you could call MyFoo.new(foo.to_h).
EDIT
As an extension to XML::Mapping:
module XmlMappingExtensions

  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def __fields__
      @__fields__ ||= all_xml_mapping_nodes.map { |r| r.instance_variable_get(:@attrname) }
    end
  end

  def to_h
    self.class.__fields__.each_with_object({}) do |field, acc|
      acc[field] = send(field)
    end
  end

end

And then either include XmlMappingExtensions in your Foo class, or:
module XML::Mapping
  # Note: this may break XML::Mapping if it is using this method
  # and there is probably a more graceful way to do this
  # but I just tried it and it seems to work fine...
  def self.included(base)
    base.send(:include, XmlMappingExtensions)
  end
end

after you have loaded XML::Mapping and before you have loaded your Foo class.


text:
Q: Should the padding and margin be 4dp or 8dp under the 48dp rhythm in Android design? Recently I read the Design Guide on Metrics and Grids. It talks about a 48dp rythm which I should utilize in my layouts.
But the Chapter "Mind Gap" confuses me. It states:

Spacing between each UI element is 8dp.

But in this graphic:

And in the example from the same page both 8dp and 4dp are used as paddings/margins.
So what is the actual value I am supposed to use?

A: The guide you read talks about spacing between elements - or in other words the distance you want between elements. You should pick your paddings and margins so they add up to an 8dp distance between elements.
When two elements are next to each other (for example in a vertical list) their paddings and margins add up. To keep the 8dp distance between elements you have to use 4dp vertical padding. If you would use the 8dp everywhere you would get a 16dp distance between elements.

Just consider having two Buttons below each other like this:

The 4dp bottom padding of the upper Button and and the 4dp top padding of the lower Button add up which results in the nice 8dp distance between the two Buttons you actually want.


text:
Q: Chromium max number of concurrent HTTP connections Could someone point me to the maximum number of concurrent HTTP connections in chromium by default. In case I need to change the value is there a flag which enables that. If not, could you point me to the location in the chromium source where this can be achieved.

A: Check out the 'MaxConnectionsPerProxy' policy template at http://dev.chromium.org/administrators/policy-templates.[1][2]  It doesn't look like Chrome or Chromium will support configuring the maximum number of concurrent HTTP connections like Firefox does in about:config.[3]
References:

*

*http://code.google.com/p/chromium/issues/detail?id=63658

*http://dev.chromium.org/administrators/policy-templates

*http://code.google.com/p/chromium/issues/detail?id=87381


text:
Q: how to use \selectlanguage in ltablex? Using ltablex.sty I need a multipage-table with columns in (polutoniko)greek, so I use >{\selectlanguage{greek}}X in the preamble of the column (I tried it with >{begin{otherlanguage}{greek}}X<{\end{otherlanguage}}, which makes no difference).
LaTeX breaks as soon as the Greek text extends to more than one line, i.e. it works with single words, but not with sentences, whereas it works everywhere else in the long (original) document.
.log'ix says:
(/usr/local/texlive/2014/texmf-dist/tex/latex/gfsporson/lgrporson.fd)
! TeX capacity exceeded, sorry [grouping levels=255].
\UseTextSymbol #1#2->\hmode@start@before@group {
                                                \def \@wrong@font@char {\Mes...
l.53   \end{tabularx}
If you really absolutely need more capacity,
you can ask a wizard to enlarge me.

\documentclass[ngerman]{scrbook}
\usepackage{savesym}
\usepackage[LGR,T1]{fontenc}
\usepackage[utf8]{inputenc}
\input{ix-utf8enc.dfu}
\usepackage[math=normal,main=ngerman,greek,]{babel}
\usepackage{teubner}
\savesymbol{breve}
\savesymbol{aa}
\usepackage[osf,sc]{mathpazo}
\restoresymbol{pplj}{breve}
\restoresymbol{pplj}{aa}
\ifFamily{pplj}{porson}
\usepackage{array}
\usepackage{booktabs}
\usepackage{calc}
\usepackage{ltablex}
\usepackage{ragged2e}
\usepackage{soulutf8}
\tracingstats=1
\tracinggroups=1
\newcommand{\hrsp}{\ifmmode\mskip1mu\else\kern0.08em\fi}
\languageattribute{greek}{polutoniko}
\begin{document}
some thing outside the table

\begin{tabularx}{1\linewidth}{l|l|l|>{\selectlanguage{polutonikogreek}}X|>{\selectlanguage{polutonikogreek}}X|X}
Thema&\emph{Phaidros}&\emph{Symposion}&\multicolumn{1}{l}{\textlatin{\emph{Phaidros}-Stelle}}&\multicolumn{1}{l}{\textlatin{\emph{Symposion}-Stelle}}&\emph{la
    difference}\\\midrule
     \endfirsthead
    Thema&\emph{Phaidros}&\emph{Symposion}&\multicolumn{1}{l}{\textlatin{\emph{Phaidros}-Stelle}}&\multicolumn{1}{l}{\textlatin{\emph{Symposion}-Stelle}}&\emph{la
    difference}\\\midrule
     \endhead
    &237 c&194 e, 199 b--c, 201 d--e, 204 e&περὶ δ''αὖ μέθας
    τυραννεύσασα, τὸν κεκτημένον ταύτῃ ἄγουσα, δῆλον οὗ τεύξεται
    προσρήματος.&&\\
    &237\hrsp d&199\hrsp d und e, 200\hrsp a und e, 201\hrsp a,
    205\hrsp a--d, 206\hrsp b--209\hrsp e&ktl.&ktl.&etc.\\
    &239\hrsp b&183\hrsp a&&&\\
    &240\hrsp a&192\hrsp b&&&\\
    &240\hrsp e&183\hrsp b--c&&&\\
  \end{tabularx}

\end{document}

A: The main problem is bad interaction with tabularx: stating \selectlanguage{polutonikogreek} in the prefix to an X column causes errors that are amplified by teubner; but without it the problem is still present causing \textpi to be considered undefined.
A temporary workaround might be delaying the language setting when the paragraph is started:
\documentclass[ngerman]{scrbook}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\input{ix-utf8enc.dfu}
\usepackage[math=normal,main=ngerman,greek,]{babel}
\languageattribute{greek}{polutoniko}

\usepackage{savesym}
\usepackage{teubner}
\savesymbol{breve}
\savesymbol{aa}
\usepackage[osf,sc]{mathpazo}
\restoresymbol{pplj}{breve}
\restoresymbol{pplj}{aa}
\ifFamily{pplj}{porson}
\usepackage{array}
\usepackage{booktabs}
\usepackage{calc}
\usepackage{tabularx}
\usepackage{ltablex}
\usepackage{ragged2e}
\usepackage{soulutf8}

\newcommand{\Xgreektext}{%
  \everypar\expandafter{\the\everypar\csname otherlanguage*\endcsname{polutonikogreek}}%
}
\newcommand{\hrsp}{?}

\begin{document}
some thing outside the table

\begin{tabularx}{1\linewidth}{
  l|
  l|
  X|
  >{\Xgreektext\relax}X|
  >{\Xgreektext\relax}X|
  X
}
Thema&
  \emph{Phaidros}&
  \emph{Symposion}&
  \multicolumn{1}{l|}{\textlatin{\emph{Phaidros}-Stelle}}&
  \multicolumn{1}{l|}{\textlatin{\emph{Symposion}-Stelle}}&
  \emph{la difference}\\
\midrule
\endfirsthead
Thema&
  \emph{Phaidros}&
  \emph{Symposion}&
  \multicolumn{1}{l|}{\textlatin{\emph{Phaidros}-Stelle}}&
  \multicolumn{1}{l|}{\textlatin{\emph{Symposion}-Stelle}}&
  \emph{la difference}\\
\midrule
\endhead
    &237 c&194 e, 199 b--c, 201 d--e, 204 e&
περὶ δ''αὖ μέθας
    τυραννεύσασα, τὸν κεκτημένον ταύτῃ ἄγουσα, δῆλον οὗ τεύξεται
    προσρήματος.&&\\
    &237\hrsp d&199\hrsp d und e, 200\hrsp a und e, 201\hrsp a,
    205\hrsp a--d, 206\hrsp b--209\hrsp e&ktl.&ktl.&etc.\\
    &239\hrsp b&183\hrsp a&&&\\
    &240\hrsp a&192\hrsp b&&&\\
    &240\hrsp e&183\hrsp b--c&&&\\
  \end{tabularx}

\end{document}

(Note: the definition of \hrsp wasn't given.)

A: You can make the utf8 handling more robust:
\documentclass[ngerman]{scrbook}
\usepackage{savesym}
\usepackage[LGR,T1]{fontenc}
\usepackage[utf8]{inputenc}
\input{ix-utf8enc.dfu}
\usepackage[math=normal,main=ngerman,greek,]{babel}
\usepackage{teubner}
\savesymbol{breve}
\savesymbol{aa}
\usepackage[osf,sc]{mathpazo}
\restoresymbol{pplj}{breve}
\restoresymbol{pplj}{aa}
\ifFamily{pplj}{porson}
\usepackage{array}
\usepackage{booktabs}
\usepackage{calc}
\usepackage{ltablex}\keepXColumns
\usepackage{ragged2e}
\usepackage{soulutf8}
\tracingstats=1
\tracinggroups=1
\languageattribute{greek}{polutoniko}

\makeatletter
\let\zzz\UTFviii@two@octets
\protected\def\UTFviii@two@octets{\zzz}
\makeatother

\begin{document}
some thing outside the table

\begin{tabularx}{1\linewidth}{l|l|l|
>{\selectlanguage{polutonikogreek}}X|
>{\selectlanguage{polutonikogreek}}X|X}
    &237 c&194 e, 199 b--c, 201 d--e, 204 e&περὶ δ''αὖ μέθας
  \end{tabularx}

\end{document}

A: @egreg, @David-Carlisle: One can get it work. With xetex and tabu it actually works. The magic thing is >{\hspace{0pt}\selectlanguage{greek}}. For unknown reasons LaTeX needs \hspace{0pt}, else you get problems with \selectlanguage{greek} and/or the line is 1/2 half line lower.

\documentclass[german]{scrbook}
\usepackage{array}
\usepackage{booktabs}
\usepackage{calc}
\usepackage{fontspec}
\setmainfont{texgyrepagella-regular}
\setsansfont{texgyreheros-regular}
\newfontfamily\greekfont[Script=Greek,Ligatures=TeX,Scale=MatchUppercase]{GFS
  Porson}
\usepackage{polyglossia}
\setmainlanguage[latesthyphen=true,babelshorthands=true]{german}
\setotherlanguage[variant={polytonic,ancient}]{greek}
\usepackage{linegoal}
\usepackage{longtable}
\usepackage{ragged2e}
\usepackage[figuresright]{rotating}
\usepackage[linegoal]{tabu}
\begin{document}
\begin{sidewaystable}
some thing outside the table

\begin{longtabu} to1\linewidth{X[1,L]|X[1.2,L]|X[1.2,L]|>{\hspace{0pt}\selectlanguage{greek}}X[4]|>{\hspace{0pt}\selectlanguage{greek}}X[4]|X}
\rowfont[L]{\hspace{0pt}\selectlanguage{german}}Thema&\emph{Phaidros}&\emph{Symposion}&\emph{Phaidros}-Stelle&\emph{Symposion}-Stelle&\emph{la
    difference}\\\midrule
     \endfirsthead
    \rowfont[L]{\hspace{0pt}\selectlanguage{german}}Thema&\emph{Phaidros}&\emph{Symposion}&\emph{Phaidros}-Stelle&\emph{Symposion}-Stelle&\emph{la
    difference}\\\midrule
     \endhead
    &237 c&194 e, 199 b--c, 201 d--e, 204 e& περὶ δ'\,αὖ
    μέθας τυραννεύσασα, τὸν κεκτημένον ταύτῃ ἄγουσα, δῆλον οὗ τεύξεται
    προσρήματος.&&\\
    &237\hrsp d&199\hrsp d und e, 200\hrsp a und e, 201\hrsp a,
    205\hrsp a--d, 206\hrsp b--209\hrsp e&ktl.&ktl.&etc.\\
    &239\hrsp b&183\hrsp a&&&\\
    &240\hrsp a&192\hrsp b&&&\\
    &240\hrsp e&183\hrsp b--c&&&\\
    &242\hrsp d&202\hrsp d&&&\\
  \end{longtabu}
\end{sidewaystable}
\end{document}

xetexify it, you get a nice table. The thing which I neither understand nor like: With tables like this, TeX alway complains (several times, probably one complaint per line):
  See the LaTeX manual or LaTeX Companion for explanation.
  Type  H <return>  for immediate help.
  ...

  l.86   \end{longtabu}

  ! LaTeX Error: Command \rmfamily invalid in math mode.`


text:
Q: Converting bitmap to grayscale I have a WinForm application, and I want to load a Bitmap(.bmp) in a picturebox directly converted to grayscale. I have the code on how to load and filter the image, and I have also the code for converting the image...but I don't know how to connect these into a working program
private void btnLoad_Click(object sender, EventArgs e)
{
    OpenFileDialog fDialog = new OpenFileDialog();
    fDialog.Filter = "Bitmaps |*.bmp| GIFs |*.gif| JPEGs |*.jpg;*.jpeg| TIFs |*.tif";
    fDialog.InitialDirectory = @"C:\\";
    if (fDialog.ShowDialog() == DialogResult.OK)
    {
        pcbImage.Image = Image.FromFile(fDialog.FileName);
        pcbImage.SizeMode = PictureBoxSizeMode.StretchImage;
    }
}

A: Your question shows you are pretty confused about images and .NET Framework.
With my answer, I won't provide you with code, as it takes a little extra time, but I want to help you with my advices. Here is the algorithm, coding will be up to you.
First of all, get the image as RGB using the Image class. Once you have loaded the image you have a structure made of pixels, each one having the three components R, G and B. Please don't be offended if I start from the very basics, but I have no idea about your actual level of experience.
You now have to generate a new image with the same widht and height of the original image. A grayscale image is characterized by having R==G==B, which means the new image must have all 3 values the same for each pixel.
In order to get the value, you have quite a few options: a common option (mostly wrong) is to perform arithmetic mean, ie. C = (R+G+B)/3 (you have to asssign it thrice, once for each component). I'll tell you later why this choice is wrong but commonly accepted.
Here is the pseudo-code that works for you
Image old;
old = Image.Load("file.bmp"); //I don't currently have MSDN at hand, nor I remember how to load the bitmap
Image new = new Image{ Width = old.Width; Height = old.Height };
for (i=0; i<old.Width-1; i++)
    for (j=0; j<old.Height; j++)
    {
        Color p = old[i,j];
        byte gray = (p.R+p.G+p.B)/3;
        new[i,j] = new Color(gray,gray,gray);
    }
 }
 pictureBox.Image = new;

Again notice: this code resembles pseudo-code, and I didn't actually test it.
Why is arithmetical mean wrong?
(the most interesting part of the question, from the scientific point)
Grayscale images are based on the concept of luminance, which is the power of the light reflected by an object and impressed on a luminance sensor (ie. a grayscale camera). Colour natural light is made up of electro-magnetic waves with a wide spectrum, but common sensors are triggered only by frequencies in red, green and blue spectrums. The human eye, also, is more sensitive to green colour rather than others (I had a diagram that shows human eye response to light at different frequencies).
This means that assuming the three light's components provide equal contribute to luminance is wrong, as when you show a viewer two lamps of the same power, one filtered green and one filtered blue, the observer will tell you that the green is brighter.
There is a conversion table (I update the post later if I find it) that shows how to perform a weighted mean with proper coefficients to deal with this phenomenon. Also, it has been found that images converted through this table look more realistic than other images converted with regular mean.
[Follow-up] I just found this article with working code samples
Edit
Now that you have shown a good question (and told that you have the conversion code) let me help you. If you posted your conversion code, it would have been more helpful. You have to separately load your image from disk, edit it and bind to the PictureBox.
Supposing you have a private Image ConvertToGrayscale(Image source);, here is the code that works for you:
private void btnLoad_Click(object sender, EventArgs e)
{
    OpenFileDialog fDialog = new OpenFileDialog();
    fDialog.Filter = "Bitmaps |*.bmp| GIFs |*.gif| JPEGs |*.jpg;*.jpeg| TIFs |*.tif";
    fDialog.InitialDirectory = @"C:\\";
    if (fDialog.ShowDialog() == DialogResult.OK)
    {
        Image old = Image.FromFile(fDialog.FileName);
        pcbImage.Image = ConvertToGrayscale(old);
        pcbImage.SizeMode = PictureBoxSizeMode.StretchImage;
    }
}


text:
Q: Call JavaFX application twice I would need help with the following: I am implementing an application in javafx, this application Is called through a click on a button.
The problem is that when I close the application then I can not call it again.
I have read that you can not call the Application.launch() method more than once.
But I found something on the service class. The examples in the documentation page are not very clear. Anyone have an idea of how this could be done?
Thank you.
http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm
my code:

private void jButton1ActionPerformed (java.awt.event.ActionEvent evt) {

      WebMap n1 = new WebMap () / / application in javafx

      n1.Lunch ();
}

WebMap class: / / javafx application
public void Lunch () {
     Application.launch ();
}

A: You can't launch a JavaFX application more than once in the same process, so don't try to do that.
You need to find an alternative mechanism to do whatever it is you are trying to do.
If you are embedding JavaFX scenes in a Swing application you should be creating new JFXPanels in Swing, not creating new JavaFX Applications on Swing button presses.
If you are intending to have a pure JavaFX application, then there is no need to have a Swing button which launches a JavaFX application, you can just use a JavaFX button instead and directly display the JavaFX scene.
There is no need to use a Service in this case, Service is used for performing repeated background tasks on a another thread, which has nothing to do with what you are attempting.
Read JavaFX for Swing developers if you want to integrate a Swing and JavaFX application.

A: As a committer of the com.bitplan.javafx open source project I can point you to the work-around we have been using for a while now:
https://github.com/BITPlan/com.bitplan.javafx/blob/master/src/main/java/com/bitplan/javafx/WaitableApp.java
 WaitableApp.toolkitInit();

will initialize the JavaFX environment.
https://github.com/BITPlan/com.bitplan.javafx/blob/master/src/main/java/com/bitplan/javafx/SampleApp.java
will show an example of how the WaitableApp base class is used in general. You also might want to have a look at the Junit Testcases of the project.
WaitableApp
/**
 * Waitable Application that does not need launch
 *
 * @author wf
 *
 */
public abstract class WaitableApp extends Application {
  protected Stage stage;
  static boolean toolkitStarted;

  /**
   * allow startup without launch
   */
  @SuppressWarnings("restriction")
  public static void toolkitInit() {
    if (!toolkitStarted) {
      toolkitStarted = true;
      // do not exit on close of last window
      // https://stackoverflow.com/a/10217157/1497139
      Platform.setImplicitExit(false);
      /// https://stackoverflow.com/a/38883432/1497139
      // http://www.programcreek.com/java-api-examples/index.php?api=com.sun.javafx.application.PlatformImpl
      com.sun.javafx.application.PlatformImpl.startup(() -> {
      });
    }
  }

  @Override
  public void start(Stage stage) {
    this.stage = stage;
  }

  public Stage getStage() {
    return stage;
  }

  public void setStage(Stage stage) {
    this.stage = stage;
  }

  /**
   * wait for close
   *
   * @throws InterruptedException
   */
  public void waitStatus(boolean open) {
    int sleep = 1000 / 50; // human eye reaction time
    try {
      if (open)
        while ((stage == null) || (!stage.isShowing())) {
          Thread.sleep(sleep);
        }
      else
        while (stage != null && stage.isShowing()) {
          Thread.sleep(sleep);
        }
    } catch (InterruptedException e) {
      ErrorHandler.handle(e);
    }
  }

  public void waitOpen() {
    waitStatus(true);
  }

  public void waitClose() {
    waitStatus(false);
  }

  /**
   * show me
   */
  public void show() {
    // ignore multiple calls
    if (stage != null)
      return;
    Platform.runLater(() -> {
      try {
        this.start(new Stage());
      } catch (Exception e) {
        ErrorHandler.handle(e);
      }
    });
  }

  /**
   * close this display
   */
  public void close() {
    Platform.runLater(() -> {
      if (stage != null)
        stage.close();
    });
    this.waitClose();
    // allow reopening
    stage = null;
  }
}


text:
Q: Using a .Zap eraser file in html I am making a website and my client wants what he refers to as a "Eraser file" to be on the top section of the site. Here is a example website that uses this feature http://flashpoint.gatech.edu/
How can I use this file and implement it in html? I have searched for eraser and zap file answers, but could not find anything on them.

A: This is very easy because it is actually a jQuery plugin...
(I did not find any viable CDN for that library, so I cannot give you the live example in a JSFiddle. Please download this in a file called "eraser.js" and put it in the same directory as this HTML file. You should be able to erase the Stack Overflow logo.)
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Eraser</title>
</head>
<body>
  <img src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="eraser.js"></script>
  <script>$('img').eraser();</script>
</body>
</html>


text:
Q: Listen to hardware button click event in android As a simple test I'm trying to have a broadcastReceiver that will notify the user with a Toast message that an hardware button was clicked in android.
I've created a receiver tag in my manifest file with a name .TestReceiver that listens to Action_CALL_BUTTON to be informed when the user clicks on the green SEND button:
<receiver android:name=".TestReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.ACTION_CALL_BUTTON" />
    </intent-filter>
</receiver>

Next, I created the TestReceiver class that extends BroadcastReceiver and creates a Toast.
When I click on the call button I don't see the Toast message but I tested it on an activity and it shows.
What am I missing here?
package com.example.helloandroid;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class TestReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        CharSequence text = "Hello toast!";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();

    }

}

Thanks

A: Here are some reasons why any BroadcastReceiver might fail to receive:

*

*In your specific case, ACTION_CALL_BUTTON isn't a broadcast Intent action. It is an activity Intent action, which will not be intercepted by BroadcastReceivers. You can tell this via the "Activity Action" statement in the documentation for this particular action.

*The broadcast Intent might not be eligible for manifest-registered receivers. ACTION_BATTERY_STATUS is one such action. These can only be received by receivers registered in Java via registerReceiver(). Unfortunately, which follow this rule are only sporadically documented.

*You may need a special permission to receive an Intent. For example, ACTION_BOOT_COMPLETED only works if you hold the RECEIVE_BOOT_COMPLETED permission. These are usually mentioned in the documentation for that action.

A: So I can register to the ACTION_CALL_BUTTON using registerReceiver() ?
I didn't see any permission required for that.

A: hey you can follow this link.you can see a tutorial of custom Intent to call Broadcast intent by clicking on button
This is Manifest
<receiver android:name="MyReceiver">
  <intent-filter>
     <action android:name="com.tutorialspoint.CUSTOM_INTENT">
  </action>
  </intent-filter>

this is a Broadcast Receiver class
public class MyReceiver extends BroadcastReceiver
{

   @Override
   public void onReceive(Context context, Intent intent) {
   Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}

Declare this method in Main Activity
public void broadcastIntent(View view)
{
    Intent intent = new Intent();
    intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
    sendBroadcast(intent);
}
}

and finally Your Button
 <Button android:id="@+id/btnStartService"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/broadcast_intent"
  android:onClick="broadcastIntent"/>

A: You can use onKeyDown() method
method :-
@Override
public boolean onKeyDown(int keycode, KeyEvent e) {
    switch(keycode) {
        case KeyEvent.KEYCODE_MENU:
           // Your Task on hard menu click
            break;
        case KeyEvent.KEYCODE_BACK:
          // Your Task on hard back click
             break;

            return true;
    }

    return super.onKeyDown(keycode, e);
}


text:
Q: Copy text of single cell to clipboard My CurrentCellValue is always null.
I want to mark a row but also if I choose to copy (Ctrl+C) a cell I want that value to be copied, now I get the whole row.
<dxg:GridControl
    Name="GridControl"
    ColumnsSource="{Binding Columns}"
    ItemsSource="{Binding Orders}"
    ColumnGeneratorTemplate="{StaticResource ColumnTemplate}"
    AutoGenerateColumns="None"
    ColumnGeneratorStyle="{StaticResource CommonColumnStyle}"
    SelectedItems="{Binding SelectedOrders}"
    SelectionMode="Row"
    CustomSummary="GridControl_OnCustomSum"
    SelectionChanged="GridControl_OnSelectionChanged"
    CopyingToClipboard="GridControl_OnCopyingToClipboard">

private void GridControl_OnCopyingToClipboard(object sender, CopyingToClipboardEventArgs e)
{
    Clipboard.Clear();
    Clipboard.SetText(GetRowData());
    e.Handled = true;
}

private string GetRowData()
{
    return GridControl.CurrentCellValue.ToString();
}

SOLUTION:
 <dxg:TableView Name="GridTableView" NavigationStyle="Cell" />

Now I have a value in CurrentCellValue

A: *

*If there's only one cell that you may wish to copy text from:

You can add "SelectedItem" Binding to your GridControl, and in "GridControl_OnCopyingToClipboard" try to find inside the selectedItem the relevant text that you want to copy.

*If there're several cells in a row that you may wish to copy from them, and it really matters which one you clicked on inside same row, then you might want to reconsider this line:
SelectionMode="Row"... And change "Row" to "Cell", then again add "SelectedItem" Binding as I mentioned above, and get the text from it


text:
Q: Which firmware should I download for iPad 2 A1397? I want to update an iPad 2, I've done this before but not with this model yet
The model is A1397, according to Apple warranty check is: iPad 2 3G (Verizon)
I want to download the file .ipsw directly from Apple server without using iTunes
Which version I download: iPad 2 (CDMA) or iPad 2 (GSM)?

A: The best way to find out is actually to use iTunes & see which file it downloads.
You don't need to let it go through the entire process, you can set it to download only.
Based on personal experience - my iPhone, according to all online evidence, [& the fact that it has a SIM card] is a UK GSM model - yet iTunes always downloads the CDMA update for it.
I've never attempted to download the GSM instead to see what happens.
I always do an update in clear steps…

*

*Download only

*Sync

*Backup

*Update

Everymac lists that as as CDMA, btw.
For independent download - http://ipswdownloader.com carries listings of Apple's file locations, but they don't list 8.2 yet.

A: You need the CDMA version. (Direct link)
Edit: oops, didn't see your question has already been answered.


text:
Q: Understanding function for file-page-manager program So I have to code the following function for a file-page-manager program, but I don't understand how to handle the null terminating feature.
RC insertRecord(FileHandle &fileHandle, const vector<Attribute>
&recordDescriptor, const void *data, RID &rid)

Given a record descriptor, insert a new record into the file identified by the provided handle. You
can assume that the input is always correct and free of error. That is, you do not need to check to
see if the input record has the right number of attributes or if the attribute types match. However,
in order to deal with NULL values in the attributes, the first part in *data contains n bytes for
passing the null information about each fields. The value n can be calculated by using this
formula: ceil(number of fields in a record / 8). For example, if there are 5 fields, ceil(5/8) = 1
byte. If there are 20 fields, the size will be ceil(20/8) = 3 bytes. The left-most bit in the first byte
corresponds to the first field. The right-most bit in the first byte corresponds to the eighth field. If
there are more than eight fields, the left-most bit in the second byte corresponds to the ninth field
and so on. If the corresponding bit to each field is set to 1, then the actual data does not contain
any value for this field. For example, if there are three fields in a record and the second field
contains NULL, the bit representation in a byte is 0100000. In addition, in the actual data, the
incoming record contains the first and the third values only. That is, the third field value is
placed right after the first field value in this case.
I don't understand, so if we have 3 attributes then 3/8=3 bytes, so the first 3 bytes of data will correspond to the null feature; however, how do we convert these bytes to bits in c++, so we can actually see where the null values are?

A: What the instructions describe is a bitmask. Each field in the record is represented by a single bit. If that bit is 1, the data does not contain an input for the field. This allows you to determine the length of the data pointed to by data.
There are typically 8 bits per byte, so if you have 9 fields, you will need 9 bits which will take 2 bytes. 17 fields, 17 bits, 3 bytes and so on. This is the origin of the provided formula for computing the length of the null information.
So if you have 3 fields you need 3/8= 0.375 bytes. This needs to be rounded up (the ceil function) to the nearest whole byte, or 1 byte.


text:
Q: Select Codeigniter Output - From Cache or Render View As I understand Codigniter cache works on matching the URI. Therefore if caching is set in a method that contains a form it will display the empty form all the time.
Is there a way to set whether to display the cache file or render the view?
Pseudocode:
if form validation = FALSE
    serve cache file
else
    render view
endif

Also is there a way to check if the form is being displayed because it is the first load or if it is being displayed because there are errors?

A: Using the Codeigniter caching way, it is not possible to display from cache conditionally. Because Codeigniter decides to display from cache before calling the controller itself.
What you can do is to use your custom caching library. There are several caching libraries for Codeigniter. You can try https://github.com/philsturgeon/codeigniter-cache

A: You can conditionally set your cache from whatever your output gives you. Though it does not render your "view" from cache, but it'll significantly improve your performance if you do any heavy processing on your forms.
For example, you can do this in your controller:
$this->load->driver('cache');

if (!$this->form_validation->run())
{
    if (!$cache = $this->cache->get('some unique variable'))
    {
        $cache = $this->some_model->some_function();
        // Do your rendering here.
    }
}

$this->load->view('some_view', array('data' => $cache));

That way you can use something like file caching, memcached or apc to cache your variables.


text:
Q: Pulling results from one function into another function I am using Access 2010.  How do I get the information in a recordset from one function moved into a different function?  The following code is giving me an object variable not set error:
Function Main()
Dim rs as DAO.RecordSet
Dim i as integer

Set rs = QueryResults(i)
   Do While Not rs.EOF
       debug.print rs!result
       rs.MoveNext
   Loop
End Function

Function QueryResults(i as Integer) as DAO.RecordSet
Dim stQuery as String
Dim rsResults as DAO.RecordSet
Dim i2 as Integer

i2 = i
stQuery = "Select query that uses i2 to get results"
Set rsResults = CurrentDb.OpenRecordset(stQuery)
End Function

I can step through and see that the QueryResults function is working.  I can print out each line from rsResults and see that it has what I want.  The problem comes when the code hits the "do while not rs.EOF" line.  It says that rs was never set to anything.
What am I doing wrong?  Both functions are in the same module.  It seems like it shouldn't be that hard to get results from one function into another function.

A: When you want a function to return something, you must assign that something to the function name.
Change the last part of your QueryResults function to this:
'Set rsResults = CurrentDb.OpenRecordset(stQuery)
Set QueryResults = CurrentDb.OpenRecordset(stQuery)
End Function


text:
Q: Stopping DC motor when motion being blocked without a limiting switch Is there a way to stop a DC motor when its motion be blocked ? For example if it rotates in a free motion raising a load and the load reached a blocking part making the shaft not rotating while the current is on, ( without using a micro limiting switch).

A: Monitoring the motor current would appear to be a viable way of detecting suddenly increased load (like blockage, etc.)  If you are controlling the motor from a microcontroller, you could make it adaptive to avoid false triggering.


text:
Q: query will run for ages if called by page I have built two queries that are executed in 2 or 3 seconds at most each if run directly in mysql or via phpMyAdmin.
Query 1 in phpMyAdmin says:

Showing rows 0 - 49 (1945 Total, Query took 3.9455 seconds.)

Query 2 in phpMyAdmin says:

Showing rows 0 - 49 (901 Total, Query took 2.0582 seconds.)

then I have built a page where I run the queries and print the result in tables
The page is (as all the other pages in my application) open in a container via jQuery load.
If I try to open the page I see that mysql starts running and never stops (minutes). If I stop mysql service the static parts of the page are correctly rendered (table headers). As you can see in the following code the queries have no input parameters or variables that can give an error.
Page code is the following:
<?php
try{
    $sql_aperta="
        SELECT veicoli.nome as portafoglio, serie.serie, data_acq,
        Descrizione, cedente, ammesso, prezzo_acq, originator, gruppo,
        COALESCE(sum(incassi_row.importo_inc),0) as flussi
        FROM crediti
        JOIN azioni_row ON crediti.id_cre = azioni_row.id_cred
        JOIN serie ON crediti.cod_serie = serie.id
        JOIN sofferenze ON crediti.cod_soff = sofferenze.id_soff
        LEFT JOIN incassi_row ON crediti.id_cre = incassi_row.id_cre
        JOIN veicoli ON crediti.titolare = veicoli.id
        WHERE crediti.stato = 'aperta'
        GROUP BY crediti.id_cre";
    $dati_aperta = $pdo->query($sql_aperta)->fetchAll();
}
catch(PDOException $e){
    $error = 'Errore ad estrarre i dati: '.$e->getMessage();
}
try{
    $sql_chiusa="
        SELECT veicoli.nome as portafoglio, serie.serie, data_acq,
        Descrizione, cedente, ammesso, prezzo_acq, originator, gruppo,
        COALESCE(sum(incassi_row.importo_inc),0) as flussi, data_chius,
        DATEDIFF(data_chius, data_acq) as coll_time
        FROM crediti
        JOIN azioni_row ON crediti.id_cre = azioni_row.id_cred
        JOIN serie ON crediti.cod_serie = serie.id
        JOIN sofferenze ON crediti.cod_soff = sofferenze.id_soff
        LEFT JOIN incassi_row ON crediti.id_cre = incassi_row.id_cre
        JOIN veicoli ON crediti.titolare = veicoli.id
        WHERE crediti.stato = 'chiusa'
        GROUP BY crediti.id_cre";
    $dati_chiusa = $pdo->query($sql_chiusa)->fetchAll();
}
catch(PDOException $e){
    $error = 'Errore ad estrarre i dati: '.$e->getMessage();
}
?>

Sofferenze - Track record

<?php echo $data; ?>

Aggregato aperto

Portafoglio	Lotto	Data acquisizione
        Controparte nominativo	Cedente nominativo
        Valore nominale ammesso	Prezzo	Cedente originario
        Gruppo	%prezzo/nominale	Totale flussi	% flussi/nominale

    <?php
    foreach($dati_aperta as $ap){
        echo '

            '.$ap['portafoglio'].'
            '.$ap['serie'].'
            '.mysql2table($ap['data_acq']).'
            '.$ap['Descrizione'].'
            '.prot2name($ap['cedente'],$pdo).'
            '.num2cur($ap['ammesso']).'
            '.num2cur($ap['prezzo_acq']).'
            '.prot2name($ap['originator'],$pdo).'
            '.$ap['gruppo'].'
            '.num2cur(round($ap['prezzo_acq']/$ap['ammesso']*100,2)).'%
            '.$ap['flussi'].'
            '.num2cur(round($ap['flussi']/$ap['ammesso']*100,2)).'%

';
    }
    ?>

Aggregato chiuso

Portafoglio	Lotto	Data acquisizione
        Controparte nominativo	Cedente nominativo
        Valore nominale ammesso	Prezzo	Cedente originario
        Gruppo	%prezzo/nominale	Totale flussi	% flussi/nominale
        Data chiusura	Collection time

    <?php
    foreach($dati_chiusa as $ch){
        echo '

            '.$ch['portafoglio'].'
            '.$ch['serie'].'
            '.mysql2table($ch['data_acq']).'
            '.$ch['Descrizione'].'
            '.prot2name($ch['cedente'],$pdo).'
            '.num2cur($ch['ammesso']).'
            '.num2cur($ch['prezzo_acq']).'
            '.prot2name($ch['originator'],$pdo).'
            '.$ch['gruppo'].'
            '.num2cur(round($ch['prezzo_acq']/$ch['ammesso']*100,2)).'%
            '.$ch['flussi'].'
            '.num2cur(round($ch['flussi']/$ch['ammesso']*100,2)).'%
            '.mysql2table($ch['data_chius']).'
            '.$ch['coll_time'].'

';
    }
    ?>


text:
Q: Unable to access ssh server over WAN I seem to be having some issues with my dd-wrt router and port forwarding. It seems like it should be clear as day - just put map the incoming port to the destination port and specify the IP. I picked a port number > 2000 and mapped it to 22 for ssh.
Seems like when I try to access my machine on the LAN it works flawlessly, but when I try to access via WAN, it timeouts. Also, if I try to access it with an incorrect port via WAN, it refuses which is expected. However, I'm puzzled what could be causing the timeout.
I tried "ssh -vvv" as well as traceroute, but those don't tell me very much. What can I try to debug this issue?
EDIT: Also, I just wanted to add that I tried rebooting the router, specifying different ports to use, and temporarily disabling the firewall. Nothing seems to be changing the issue.
EDIT2: Just found out it was my router having problems with using my own IP and NAT. I found out everything works if I ssh outside to another server, and then back in to my own.

A: Do an external port scan and make sure the port is actually open. Also, instead of mapping a random port to the actual port just map 22 to your server - one less step in the routing process.
As a final note, if your modem is actually a modem/router these problems always crop up if you have another device behind it handling the routing and port forwarding.


text:
Q: How to write group by query in dynamic linq query I am struggling to write 'Group by query' in dynamic linq query.
public IEnumerable<DashboardReport> GetDashTransactionsReports(string dimensionColumn)
    {
        var result = (from t in _dashboardContext.GetTransactionsReports()
                      group t by t.DimensionTransactionYear
                          into g
                          select new DashboardReport()
                          {
                              Name = g.Key,
                              Value = g.Sum(s => s.MeasureTotal)
                          }).ToList();

        var resultList = _dashboardContext.GetTransactionsReports().AsQueryable().GroupBy("TransactionMonth", "DashTransaction", null).Select("TransactionMonth");

        return result;

    }

"result" is used normal 'GroupBy' query. I'm turning it to dynamic way as "resultList" where I am struggling. Any idea ?
I am using the following Dynamic Linq's Group by method:
public static IQueryable GroupBy(this IQueryable source, string keySelector, string elementSelector, params object[] values)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (keySelector == null) throw new ArgumentNullException("keySelector");
        if (elementSelector == null) throw new ArgumentNullException("elementSelector");
        LambdaExpression keyLambda = DynamicExpression.ParseLambda(source.ElementType, null, keySelector, values);
        LambdaExpression elementLambda = DynamicExpression.ParseLambda(source.ElementType, null, elementSelector, values);
        return source.Provider.CreateQuery(
            Expression.Call(
                typeof(Queryable), "GroupBy",
                new Type[] { source.ElementType, keyLambda.Body.Type, elementLambda.Body.Type },
                source.Expression, Expression.Quote(keyLambda), Expression.Quote(elementLambda)));
    }


text:
Q: My code returning incorrect values In my PHP code I run the following statement:
$stmt = $pdo->prepare("SELECT * FROM `tb_services` WHERE tb_services.user_id = :var1 AND
(tb_services.user_id = :var1 OR tb_services.user_id = (SELECT subuser_owner_id FROM tb_users WHERE user_id = :var1))
AND tc_services.sub_id = :var2");
$stmt->bindParam(":var1", $_GET['var1']);
$stmt->bindParam(":var2", $_GET['var2']);

However doing $stmt->rowCount() returns 0, but when I run this exact statement(filled with the same values that I'm inputting instead of the :var1, :var2) it finds the row perfectly.
while($info = $stmt->fetch(PDO::FETCH_ASSOC)) {
The above is the code that is not running. As the return of the rowCount() is 0 and the while loop is not running, that just shows to me that it is for some reason not finding the row. If I input static values into the SQL statement, it works perfectly.

A: I have found the error. I was overlooking my code and saw the stupid mistake I made. For anyone out there that might experience a similar problem, the following MySQL statement:
$stmt = $pdo->prepare("SELECT * FROM `tb_services` WHERE tb_services.user_id = :var1 AND
(tb_services.user_id = :var1 OR tb_services.user_id = (SELECT subuser_owner_id FROM     tb_users WHERE user_id = :var1))
AND tc_services.sub_id = :var2");

should be
$stmt = $pdo->prepare("SELECT * FROM `tb_services` WHERE(tb_services.user_id = :var1 OR     tb_services.user_id = (SELECT subuser_owner_id FROM     tb_users WHERE user_id = :var1))
AND tc_services.sub_id = :var2");

*

*Removing the first tb_services.user_id = :var1 as that caused the error.


text:
Q: Can ${}_2F_1\left(1,b;1+b;z\right)$ be simplified? I would like to ask a question about hypergeometric function ${}_2F_1$. Specifically, I hope to solve the equation
$$
\frac{\delta x}{1-\delta}{}_2F_1\left(1,1-\delta;2-\delta;x\right)=a,
$$
where $\delta\in\left(0,1\right)$ and $a\geq 1$. Is the $x$ has the closed-form solution? If not, for the special case when $\delta=\frac{1}{2}$, can we get $x$?
I think the above hypergeometric function has the special structure, but I checked the literatures and cannot find useful results. I appreciate if you can help to solve it, or give some suggestions.
Thanks.


text:
Q: Post media tweets with Twitter Fabric SDK I have included Twitter Fabric SDK in my android application and can post tweets from it. I would like to post images as well though but that doesn't seem possible through the StatusesService that is used to post text-only tweets.
Is it not possible to do this through the SDK? Do I have to do an explicit http post for this?

A: According to the Fabric SDK, yes you can embed media in your Tweet through TweetUI.
Sample Code
Initialize with Fabric
Fabric.with(this, new TweetComposer());

Tweet Code
TweetComposer.Builder builder = new TweetComposer.Builder(this)
     .text("just setting up my Fabric.")
     .image(myImageUri);

builder.show();

File myImageFile = new File("/path/to/image");
Uri myImageUri = Uri.fromFile(myImageFile);

Remember

In the event that the Twitter app is not installed, TweetComposer will
  create an intent to interact with the Twitter.com in a browser. The
  browser ignores a specified image.

A: package ...

public class StatusFragment extends Fragment {
Button btn_select, btn_post_image;
EditText edt_status;
String status;
ImageView img_status;
private static final int RESULT_LOAD_IMAGE = 1;
SharedPreferences mSharedPreferences;
String selectedImagePath;
Uri selectedImage;
TypedFile typedFile;
private static final String IMAGE_DIRECTORY_NAME = "Hello Twitter";
String mCurrentPhotoPath;
File mFile;
ProgressDialog pDialog;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_status, container, false);
    btn_post_image = (Button) rootView.findViewById(R.id.btn_post_image);
    btn_select = (Button) rootView.findViewById(R.id.btn_select);
    edt_status = (EditText) rootView.findViewById(R.id.edt_status);
    img_status = (ImageView) rootView.findViewById(R.id.img_status);
    btn_post_image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (StatusFragment.CheckNetwork.isInternetAvailable(getActivity()))  //if connection available
            {
                pDialog = new ProgressDialog(getActivity());
                pDialog.setMessage("Uploading......");
                pDialog.show();
                final TwitterSession session = Twitter.getSessionManager().getActiveSession();
                mFile = new File(getRealPathFromURI(selectedImage));
                TypedFile typedFile = new TypedFile("application/octet-stream", mFile);
                TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient(session);
                MediaService ms = twitterApiClient.getMediaService();
                ms.upload(typedFile, null, null, new Callback<Media>() {

                    @Override
                    public void success(Result<Media> mediaResult) {
                        // show on User Timeline

//                            StatusesService statusesService =    TwitterCore.getInstance().getApiClient(session).getStatusesService();
//                                 statusesService.update(edt_status.getText().toString(), null, false, null, null, null, true, false, mediaResult.data.mediaIdString, new Callback<Tweet>() {
//                                @Override
//                                public void success(Result<Tweet> tweetResult) {
//                                    //...
//                                    Toast.makeText(getActivity(), "Upload Complete", Toast.LENGTH_SHORT).show();
//                                    pDialog.dismiss();
//                                }
//
//                                @Override
//                                public void failure(TwitterException e) {
//                                    //...
//                                    Toast.makeText(getActivity(), "Upload Error" + e.getMessage(), Toast.LENGTH_SHORT).show();
//                                    pDialog.dismiss();
//                                }
//
//                            });

                        // Show on Home Timeline
                        StatusesService statusesService = TwitterCore.getInstance().getApiClient(session).getStatusesService();

                        statusesService.update( " content: " + edt_status.getText().toString(), null, false, null, null, null, true, false, mediaResult.data.mediaIdString, new Callback<Tweet>() {
                            @Override
                            public void success(Result<Tweet> tweetResult) {
                                pDialog.dismiss();
                                Toast.makeText(getActivity(), "Upload Completed", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void failure(TwitterException e) {
                                //...
                                pDialog.dismiss();
                                Toast.makeText(getActivity(), "Upload Error"+e.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                        });

                    }

                    @Override
                    public void failure(TwitterException e) {
                        //...
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            } else{
                Toast.makeText(getActivity(), "Network error", Toast.LENGTH_SHORT).show();
            }
        }

    });

    btn_select.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_IMAGE);

        }

    });

    return rootView;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK) {
        selectedImage = data.getData();
        img_status.setImageURI(selectedImage);

    }

}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri contentUri) {
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } catch (Exception e) {
        return contentUri.getPath();
    }
}

public static class CheckNetwork {
    static String TAG = CheckNetwork.class.getSimpleName();

    public static boolean isInternetAvailable(Context context) {
        NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

        if (info == null) {
            Log.d(TAG, "no internet connection");
            return false;
        } else {
            if (info.isConnected()) {
                Log.d(TAG, " internet connection available...");
                return true;
            } else {
                Log.d(TAG, " internet connection");
                return true;
            }

        }
    }
}

public class MyTwitterApiClient extends TwitterApiClient {

    public MyTwitterApiClient(TwitterSession session) {
        super(session);
    }

    public UploadMediaService getUploadMediaService() {

        return getService(UploadMediaService.class);
    }

}

interface UploadMediaService {

    @Multipart
    @POST("1.1/media/upload.json")
    void upload(@Part("media") TypedFile file, @Part("additional_owners") String owners, Callback<MediaEntity> cb);

}

public void openPath(Uri uri) {
    InputStream is = null;
    try {
        is = getActivity().getContentResolver().openInputStream(uri);
        //Convert your stream to data here
        is.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

Try it!


text:
Q: DSC for initialising and formatting disks I need to format a disk for servers using DSC. I tried using the below from
https://blogs.msdn.microsoft.com/timomta/2016/04/23/how-to-use-powershell-dsc-to-prepare-a-data-drive-on-an-azure-vm/#comment-1865
But it doesnt work as it doesn't seem to be complete, I get errors

"+ xWaitforDisk Disk2  + ~~~~~~~~~~~~ Resource 'xWaitForDisk' requires
  that a value of type 'String' be provided for property 'DiskId'.
At line:18 char:1  + DiskNumber = 2  + ~~~~~~~~~~ The member
  'DiskNumber' is not valid. Valid members are  'DependsOn', 'DiskId',
  'DiskIdType', 'PsDscRunAsCredential', 'RetryCount',
  'RetryIntervalSec'. "

Configuration DataDisk
{
    Import-DSCResource -ModuleName xStorage
    Node localhost
    {
        xWaitforDisk Disk2
        {
            DiskNumber = 2
            RetryIntervalSec = 60
            Count = 60
        }
    xDisk FVolume
    {
        DiskNumber = 2
        DriveLetter = 'F'
        FSLabel = 'Data'
    }
}

A: You need to replace DiskNumber with DiskID.
Take a look at the examples on GitHub https://github.com/PowerShell/StorageDsc/tree/dev/Modules/StorageDsc/Examples/Resources
You can find the DiskId with powershell use the command: Get-Disk


text:
Q: cast to base-type not supported for generic method I have an interface IGenericOrder as follows:
using System;
using System.Linq.Expressions;

namespace MyNamespace
{
    interface IGenericOrder<T> where T : new()
    {
        Func<T, int> GetStatement(string name);
    }

    public class GenericOrder<T> : IGenericOrder<T> where T : new()
    {
        public Func<T, int> GetStatement(string name)
        {
            return (T) => 4;
        }
    }
}

Now when I create an instance of that class and cast it back to IGenericOrder<object>
var sorter = (IGenericOrder<object>) new GenericOrder<Foo>();

I get Exception:

InvalidCastException: The instance of type GenericOrder<Foo> cannot be cast to IGenericOrder<object>

Which seems clear as the Interface IGenericOrder is not covariant. However if I make the interface covariant (interface  IGenericOrder<out T>) I get a compiler-error:

Invalid variance: The type parameter 'T' must be contravariantly valid on IGenericOrder<T>.GetStatement(string). 'T' is covariant.

As I read from here covariance can only used when

[the generic type parameter] is used only as a method return type and is not used as a type of formal method parameters.

Does this mean I cannot use co-/contravariance for methods that themselfes return generic instances?
I am using .Net 4.5

A: To understand what is going on look at the definition of Func<T,TResult> delegate:
public delegate TResult Func<in T, out TResult>(
    T arg
)

As you can see, its first type parameter T is an in parameter. Therefore, you cannot use an out parameter as Func's first type argument. The second type parameter TResult is out, so using T as TResult would work:
interface IGenericOrder<out T> where T : new() {
    Func<int,T> GetStatement(string name);
}

public class GenericOrder<T> : IGenericOrder<T> where T : new() {
    public Func<int,T> GetStatement(string name) {
        return (x) => default(T);
    }
}

Demo.

A: You are using T as the first type parameter of Func, so the only valid mode is contravariance because the T represents the type of the function's parameter. What you are trying to achieve with your cast is unsafe: you are saying "Here's a function which takes a Foo as a parameter. Please treat this as a function which takes any object as a parameter." If instead you had a Func<int, T>, you could use covariance, because a function that returns a Foo can also be viewed as a function that returns an object.


text:
Q: Cakephp Sanitization i'm using Sanitize::clean for posts comments , but it's replace New Line from textarea with \n
i need clean data but with orginal style and not convert NEW LINE to \n
thanks

A: Use this on your variable:
nl2br(h($var))
nl2br inserts HTML line breaks before all newlines in a string while h is CakePHP's shortcut for PHP's htmlspecialchars function.
You should not need to do more than nl2br(h($var)) on your data.


text:
Q: Truncate Custom Attribute Label/Options using SQL Query I am using Magento 1.9.x.
I have created several custom attributes in Magento project. They all have thousands of labels or options. I don't want to remove custom attribute just want to delete all their values only.
For example I have one attribute as Manufacturer and 1200 options for that attribute now I want to delete all values of Manufacturer Attribute.
How can I do this using SQL queries?
I am following below process

*

*Get attribute_id from Table: eav_attribute by searching attribute_code (In my case it is "manufacturer" and attribute_id is 81)

*In table eav_attribute_option, searching 81 under attribute_id field will get us all option_ids

*By taking all id's in eav_attribute_option_value, I am searching under option_id and getting value field and removing.

Final Query would be like:
DELETE eav_attribute_option , eav_attribute_option_value  FROM eav_attribute_option  INNER JOIN eav_attribute_option_value
WHERE eav_attribute_option.option_id= eav_attribute_option_value.option_id and eav_attribute_option.attribute_id = 81

To perform such action for multiple Custom Attributes I need to run this query for multiple time.
Any specific solution??

A: Find Below Query
To view Options
SELECT `option`.`attribute_id`, `option`.`option_id`,
        `attribute`.`attribute_code`, `value`.`value`
    FROM `eav_attribute_option` AS `option`
    INNER JOIN `eav_attribute` AS `attribute`
        ON `attribute`.`attribute_id` = `option`.`attribute_id`
    INNER JOIN `eav_attribute_option_value` AS `value`
        ON `value`.`option_id` = `option`.`option_id`
        WHERE `attribute`.`attribute_id`=81

To Delete Options
DELETE `value`,`option`
    FROM `eav_attribute_option` AS `option`
    INNER JOIN `eav_attribute` AS `attribute`
        ON `attribute`.`attribute_id` = `option`.`attribute_id`
    INNER JOIN `eav_attribute_option_value` AS `value`
        ON `value`.`option_id` = `option`.`option_id`
        WHERE `attribute`.`attribute_id`=81


text:
Q: java Memory Leaks and grow Surviving Generations i have problem with my project that need send many of request to server
problem is continues growing Surviving Generations ..
i develop my project with Netbeans IDE and i am using NetBeans Profiler to detect a Memory Leak .
i created a class for testing:
test class
public class test {

    public test(String url) throws IOException {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        client.execute(request);
        System.out.println("\nSending 'GET' request to URL : " + url);
    }

}

main class
public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {

        for (int i = 1; i < 10000; i++) {
            new test("http://foo.dev/article?id="+i);
        }
    }
}

NetBeans Profiler results:
Surviving Generations

Heap Result

netbeans site:

Typically, the Surviving Generations value starts to grow during an
  application's startup, but after some time it should reach some stable
  limit and level off. When this happens it indicates that no objects
  are being created continuously and leaking. If the Surviving
  Generations line continues to grow all the time (regardless of how
  quickly), then the application is most likely leaking.

my question is why Surviving Generations line continues to grow and What is the cause in my Code ?
any help please...


text:
Q: Liferay startup windows 8.1 too slow Liferay 6.2 startup is too slow with my windows 8.1 development enviroment....
1.- With my windows 8.1 64 bits development enviroment:
About 12 -15 minutes startup....Changing jvm parameters, same results...too slow. The critical step is "INFO [localhost-startStop-1][AutoDeployDir:139] Auto deploy scanner started for ...." with 5-7 minutes duration. Tested with Java 6 , Java 7 and Java 8, (32 and 64 bits versions).
2.- With the SAME windows 8 machine, but using them like virtual box host and Linux Ubuntu guest....With the same jvm parameters....
About 3 minutes (that's a normal startup time!). With ubuntu virtual machine critical step "INFO [localhost-startStop-1][AutoDeployDir:139] Auto deploy scanner started for ...." is 30 seconds! and within a virtual machine!
3.- With the SAME windows 8 machine, but using them like virtual box host and Windows 7 guest.....With the same jvm parameters...
Just only 3 minutes too! And within a virtual machine!
Definitely the problem seems to be Windows 8.1 . ... but... what is the problem, tomcat + win8? liferay 6.2 + win 8.1?
Anyone works with Windows 8.1? I have discarted hardware problem with the Ubuntu virtual machine (only 3 minutes startup) and the Windows 7 virtual machine (only 3 minutes). I tested all posible java versions and parameters, and liferay startup is  not normal.

A: Best combination should be

*

*Windows server 2008 64bit, 64-bit JDK 1.6 and Tomcat 64-bit.

*Windows server 2003 32bit, 32-bit JDK 1.6 and Tomcat 32-bit.


text:
Q: In case that I cannot know whether datetime is offset-aware or not, how to subtract offset-naive and offset-aware datetime? I am having a hard time dealing with timezone. Can somebody give me some advice?
It is not known whether the time 'lastday' is offset-aware or not. In this case, how can I subtract two time 'lastday' and 'today'?
Assuming that 'lastday' is offset-aware,
by executing the following code:
lastday = snapshotinfo.dateCreated
print 'lastday:',lastday
today = datetime.datetime.today()
print 'today:',today
today = pytz.utc.localize(today)
print 'today after localize:',today
diff = abs(today - lastday).days
print 'diff:', diff

I can get the following result
lastday: 2017-03-27 00:24:16.295000+09:00
today: 2017-03-27 18:23:41.284000
today after localize: 2017-03-27 18:23:41.284000+00:00
diff: 1

But on another server,'lastday' is offset-naive. In this case, I get the following error:
lastday: 2017-03-27 00:23:21.000215
today: 2017-03-27 18:33:34.883176
today after localize: 2017-03-27 18:33:34.883176+00:00
diff = abs(today - lastday).days
TypeError: can't subtract offset-naive and offset-aware datetimes

How do I know whether 'lastday' is offset-naive or not? If I can know it, I think I can decide whether or not to convert 'today'.