Wednesday, January 31, 2018

oracle - Delphi - prevent against SQL injection



I need to protect an application from SQL injection. Application is connecting to Oracle, using ADO, and search for the username and password to make the authentication.




From what I've read until now, the best approach is by using parameters, not assigning the entire SQL as string. Something like this:



query.SQL.Text := 'select * from table_name where name=:Name and id=:ID'; 
query.Prepare;
query.ParamByName( 'Name' ).AsString := name;
query.ParamByName( 'ID' ).AsInteger := id;
query.Open;



Also, I'm thinking to verify the input from user, and to delete SQL keywords like delete,insert,select,etc...Any input character different than normal ASCII letters and numbers will be deleted.



This will assure me a minimum of security level?



I do not want to use any other components than Delphi 7 standard and Jedi.


Answer



Safe



query.SQL.Text := 'select * from table_name where name=:Name';



This code is safe because you are using parameters.
Parameters are always safe from SQL-injection.



Unsafe



var Username: string;
...
query.SQL.Text := 'select * from table_name where name='+ UserName;



Is unsafe because Username could be name; Drop table_name;
Resulting in the following query being executed.



select * from table_name where name=name; Drop table_name;


Also Unsafe



var Username: string;
...

query.SQL.Text := 'select * from table_name where name='''+ UserName+'''';


Because it if username is ' or (1=1); Drop Table_name; --
It will result in the following query:



select * from table_name where name='' or (1=1); Drop Table_name; -- '


But this code is safe




var id: integer;
...
query.SQL.Text := 'select * from table_name where id='+IntToStr(id);


Because IntToStr() will only accept integers so no SQL code can be injected into the query string this way, only numbers (which is exactly what you want and thus allowed)



But I want to do stuff that can't be done with parameters




Parameters can only be used for values. They cannot replace field names or table names.
So if you want to execute this query



query:= 'SELECT * FROM :dynamic_table '; {doesn't work}
query:= 'SELECT * FROM '+tableName; {works, but is unsafe}


The first query fails because you cannot use parameters for table or field names.
The second query is unsafe but is the only way this this can be done.
How to you stay safe?



You have to check the string tablename against a list of approved names.




Const
ApprovedTables: array[0..1] of string = ('table1','table2');

procedure DoQuery(tablename: string);
var
i: integer;
Approved: boolean;
query: string;
begin

Approved:= false;
for i:= lo(ApprovedTables) to hi(ApprovedTables) do begin
Approved:= Approved or (lowercase(tablename) = ApprovedTables[i]);
end; {for i}
if not Approved then exit;
query:= 'SELECT * FROM '+tablename;
...


That's the only way to do this, that I know of.




BTW Your original code has an error:



query.SQL.Text := 'select * from table_name where name=:Name where id=:ID'; 


Should be



query.SQL.Text := 'select * from table_name where name=:Name and id=:ID'; 



You cannot have two where's in one (sub)query


php - Why can I use a string literal as a class in php7?



Consider the following code:



class foo {
static $bar = 'baz';
}
var_dump('foo'::$bar);






It throws an error in PHP5 (as expected):




Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) in [...][...] on line 4








But it works without an issue in PHP7 and outputs:



string(3) "baz"





Is that intentional or a bug?


Answer



I think it's because they rewrote stuff regarding evaluation.




like the following is not possible in PHP5 but in PHP 7:



echo (new X)->toString();


Same would go for



echo ('X')::$bar



See Changes to the handling of indirect variables, properties, and methods



This is mainly about the left-to-right evaluation but it also affects the evaluation in general.



More information can be found on PHP RFC: Uniform Variable Syntax (Status: implemented) - Thanks to Nikic:




This RFC proposes the introduction of an internally consistent and
complete variable syntax. To achieve this goal the semantics of some

rarely used variable-variable constructions need to be changed.



c# - How can I get a pc's user name?




I'm trying the get the user's name [ex) admin, John, Lucy, etc.] so I can store it to a string and create a file path to save files in my application. I have absolutely no idea how to do this. I tried using the Microsoft.AspNet.Identity; namespace but that didn't help me any, as the UserManager class item is templated to take a User, which is what I'm trying to find in the first place. I'm honestly just walking through the forest at night right now. Can't see and no idea where to go. Any help would be awesome!! Thanks


Answer



Try this to get the username of the currently logged on user:



string username = Environment.UserName;



Microsoft Docs



This is in the system namespace, so there's no need to use Windows Identity.


String to byte[] - c# act like java







I need to convert a string to a byte[]. If that were it the task would be simple. I need to write it in C#, but I need it to act like Java.



There are two problems I'm seeing:



Endianness: Java stores things internally as Big Endian, while .NET is Little Endian by default.



Signedness: C# bytes are unsigned. Java bytes are signed.



How can I take a UTF-8 string, and get a byte[] that will match what it would in Java.



To give more context, I have these two functions (one in java, one in c#), they create different hashes, I suspect it's due to the difference in byte representation in .net vs java.
Java:



String key = "test";
String data = "test";
String algorithm = "HmacSHA1";
Charset charset = Charset.forName("utf-8");
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(signingKey);
return new String(Base64.encodeBase64(mac.doFinal(data.getBytes(charset))), charset);


C#:



string key = "ed2ee2e0-65c1-11de-8a39-0800200c9a66";
string data = "test";
byte[] aKey = Encoding.UTF8.GetBytes(key);
byte[] aData = Encoding.UTF8.GetBytes(data);
HMACSHA1 oEncode = new HMACSHA1(aKey);
byte[] aBytes = oEncode.ComputeHash(aData);
return Convert.ToBase64String(aBytes);

PHP error: Cannot modify header information – headers already sent







So I have this output on my page.. not understanding why I have it popping up. I'm new to php though, so maybe it's something easy to fix




-I have a header.php file, which includes all important info, as well has the banner of the page. This header.php is included on every page.



-I have it checking the session value to make sure user is allowed to be at a certain page. If user is not allowed to be there, I kick them back to login page



This is where the error comes up though. This is what I have:



include_once ("header.php");

if ($_SESSION['uid']!='programmer')
{

header('Location: index.php');
echo 'you cannot be here';
exit;
}


The index that it is redirecting to also has the header. So is having these multiple header references giving me this error? I see no other way to do this, and it's driving me nuts!

PHP mail() works from command line but not apache



I'm trying to figure out why the mail function in PHP fails when called via web browser (i.e. apache), but I can run the same script from the command line using




php -f mailtest.php




This is one of my client's Fedora servers, so I don't grok it completely, but I do have root access should I need to change anything.




from php.ini:




sendmail_path = /usr/sbin/sendmail -t -i




Not sure if this could matter, but /usr/sbin/sendmail is a symlink to /etc/alternatives/mta, which is a symlink back to /usr/sbin/sendmail.sendmail. FWIW the apache user does have permission to run sendmail (tested sendmail directly from the command line).



OS: Fedora Core 7 Linux (kernel 2.6.23.17)  
Apache: 2.2.8

PHP: 5.2.6


Any help here will be greatly appreciated!


Answer



I found the problem. SELinux was preventing apache from being able to use sendmail. To diagnose, I used



$ sestatus -b | grep sendmail  
httpd_can_sendmail off



Then to actually fix the problem:



$ restorecon /usr/sbin/sendmail
$ setsebool -P httpd_can_sendmail 1


Read more about it here.


typescript - Enable Access-Control-Allow-Origin in angular 5 from Client side

I am using httpClient angular package for get requests. I am using https://api.independentreserve.com/Public/GetValidPrimaryCurrencyCodes url for fetching data. It is giving CORS error in console.



I don't have access to server side code, but still I want to enalbe CORS in angular service. This is my service function




myfunction() {
let head = new HttpHeaders();
head.append('Access-Control-Allow-Headers', 'Content-Type');
head.append('Access-Control-Allow-Methods', 'GET');
head.append('Access-Control-Allow-Origin', '*');
return this.http.get("https://api.independentreserve.com/Public/GetValidPrimaryCurrencyCodes", {headers: head}).toPromise();
}


I have tried it with chrome cors extension, and it works fine. But I want this to be enabled from angular code.




I have also tried working with proxies, following tutorial. BUt it is still not working. This is my object in proxy.conf.json file.



{
"/api": {
"target": "https://www.independentreserve.com/Public/GetValidPrimaryCurrencyCodes",
"secure": false
},
"changeOrigin": true
}



and added "start": "ng serve --proxy-config proxy.conf.json" in package.json file. It is not working this way either.



Can any body give me some solution?

php - Filter array by sub element that starts with string

How can I filter an array when a sub element starts with a certain string? This will filter results when 'name' matches 'bk-' but how can I alter it so matched elements starting with 'bk-' instead?



$starts_with = 'bk-';

$new_facets = array_filter($facets, function ($var) use ($starts_with) {
return ($var['name'] == $starts_with);

});

Tuesday, January 30, 2018

fopen incompatible type char (*)[9] instead of char(*) in C

My program in C reads data in a file in order to initialise variables but it won't open the file. It fails when it reaches fopen. Xcode outputs the following warning for both fopen and printf. I understand the error but I don't know how to correct it, I tried many tricks but it won't do, can anyone help me out ? I just want my program to open Try1.txt.


Incompatible pointer types passing 'char (*)[9]' to parameter of type const char*'


So this is the code inside my main function :


FILE *infile = NULL;
const char infilename [] = "Try1.txt";
infile = fopen(&infilename, "r");
if (infile == NULL)
{
printf("Failed to open file: %s\n", &infilename);
return 1;
}

Note that the program stops before reaching the if loop because it never prints. I tried to initialise the size and to add '\0' at the end of my string too.

javascript - Is there any way to distinguish between an unset property and a property set to undefined?





Say I have the object testObject = {a: undefined}. If I then console.log(testObject.a), I get undefined. But the same happens if I console.log(testObject.b), which doesn't exist. Is there any way in JavaScript to distinguish between a and b here? I ask mostly out of curiosity, I have no use case.


Answer



hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property.



In given case -




  testObject = {a: undefined};

testObject.hasOwnProperty('a') //true
testObject.hasOwnProperty('b') //false

go - Slice append change other elements in Slice



I'm solving Leetcode question at https://leetcode.com/problems/subsets with Golang and iterative solution. The algorithm is basically trying to add the new element to the existing array. After all, it will generate all of the subsets.



But when some elements added to the existing array solution, it change the other element also. Here's the code I provided. I put some debugging Println also.




package main

import (
"fmt"
)

func main() {
fmt.Println(subsets([]int{0, 1, 2, 3, 4}))
}


func subsets(nums []int) [][]int {
res := [][]int{}

res = append(res, []int{})
for i := 0; i < len(nums); i++ {
for j := range res {
fmt.Println(i)
temp := append(res[j], nums[i])
fmt.Println(temp)

res = append(res, temp)
fmt.Println(res)
}
}

return res
}


Output




0
[0]
[[] [0]]
1
[1]
[[] [0] [1]]
1
[0 1]
[[] [0] [1] [0 1]]

2
[2]
[[] [0] [1] [0 1] [2]]
2
[0 2]
[[] [0] [1] [0 1] [2] [0 2]]
2
[1 2]
[[] [0] [1] [0 1] [2] [0 2] [1 2]]
2

[0 1 2]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2]]
3
[3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3]]
3
[0 3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3]]
3
[1 3]

[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3]]
3
[0 1 3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3]]
3
[2 3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3]]
3
[0 2 3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3]]

3
[1 2 3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3]]
3
[0 1 2 3]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3]]
4
[4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3] [4]]
4

[0 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3] [4] [0 4]]
4
[1 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3] [4] [0 4] [1 4]]
4
[0 1 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3] [4] [0 4] [1 4] [0 1 4]]
4
[2 4]

[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3] [4] [0 4] [1 4] [0 1 4] [2 4]]
4
[0 2 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 3] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4]]
4
[1 2 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] **[0 1 2 3]** [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4]]
4
[0 1 2 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] **[0 1 2 4]** [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4]]

4
[3 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4]]
4
[0 3 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4]]
4
[1 3 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4]]
4

[0 1 3 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4] [0 1 3 4]]
4
[2 3 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4] [0 1 3 4] [2 3 4]]
4
[0 2 3 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4] [0 1 3 4] [2 3 4] [0 2 3 4]]
4
[1 2 3 4]

[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4] [0 1 3 4] [2 3 4] [0 2 3 4] [1 2 3 4]]
4
[0 1 2 4 4]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4] [0 1 3 4] [2 3 4] [0 2 3 4] [1 2 3 4] [0 1 2 4 4]]
[[] [0] [1] [0 1] [2] [0 2] [1 2] [0 1 2] [3] [0 3] [1 3] [0 1 3] [2 3] [0 2 3] [1 2 3] [0 1 2 4] [4] [0 4] [1 4] [0 1 4] [2 4] [0 2 4] [1 2 4] [0 1 2 4] [3 4] [0 3 4] [1 3 4] [0 1 3 4] [2 3 4] [0 2 3 4] [1 2 3 4] [0 1 2 4 4]]


When it add the [0 1 2 4] element, it also change the existing [0 1 2 3] to [0 1 2 4]. Is there any specific reason why this happen?


Answer



In your append function calls you are using slices meaning you work with references, thus no guarantee that the values will remain static as @zerkms mentioned.

What you can do is create a copy of the slice temp returned from the 1st append call and use it in the 2nd append. This will make passing a copy of the temp slice and with that avoiding any interferences.



package main

import (
"fmt"
)

func main() {
fmt.Println(subsets([]int{0, 1, 2, 3, 4}))

}

func subsets(nums []int) [][]int {
res := [][]int{}

res = append(res, []int{})
for i := 0; i < len(nums); i++ {
for j := range res {
fmt.Println(i)
temp := append(res[j], nums[i])

copy_temp := make([]int, len(temp))
copy(copy_temp, temp)
fmt.Println(copy_temp)
res = append(res, copy_temp)
fmt.Println(res)
}
}

return res
}


php - send mail from form won't work

I know that this is a question that has been answered lots and I've read a few of them, but I just can not seem to get my send mail function to work. So the basics are I have an HTML contact form:




























This is attached an external file called mail_handler.php, this seems to be where I just can't get my file to work.


    $email = $_POST["email"]; //users email
$name = $_POST["name"]; //users name
$msg = $_POST["message"]; //users message
$to = "email@mydomain.co.uk"; //my email
$subject = "New online enquiry"; //subject line
$headers = "From: $email \n"; //who is the email from
$message = "Name: $name \n sent the following enquiry: $msg"; //email content
$user = "$email";
$usersubject = "Thank You"; //subject for user email
$userheaders = "From: enquiries@samsonvilliers.co.uk \n"; //who email is from
$usermessage = "Thank you for sending a message, we will be in touch soon.";//thank you message to users email
mail($to,$subject,$message,$headers); //mail to me
mail($user,$usersubject,$usermessage,$userheaders); //mail to user
header('Location: send_mail.html'); //send to a new page with thank you message.
?>

I have tried altering the code in many different ways, but nothing seems to work, I am sure that I am making a very simple mistake, but any guidance would be very appreciated.

dom - HTML code for bold arrow symbol

I searched internet the maximum I can. But couldn't find the HTML code for the symbol attached below:



enter image description here



I need to use this in a anchor tag.

Find Multiple user's accounts in mySQL with PHP





Can you help me, please, to solve this. There is a table (user's access log) in mysql: "user_id" "Ip" "access_date".
Is it possible to display all User's double accounts (multiaccounts, users with different ID, but used same IP), without huge load on mysql & server resources?

Like:
"10" "155.166.11.2" "2018-01-22 13:08:36"
"122" "127.0.0.1" "2018-01-22 13:19:00"
"13" "144.11.11.4" "2018-01-31 17:16:56"
"10" "127.0.0.1" "2018-01-31 17:26:35"
"99" "155.166.11.2" "2018-01-31 17:26:55"
"13" "12.11.22.4" "2018-01-31 17:43:56"
"18" "145.106.11.2" "2018-01-31 18:50:18"
"11" "144.11.11.4" "2018-01-31 18:54:18"
"10" "155.166.11.2" "2018-01-31 19:08:26"



Result:
"10, 99, 122" - same user
"11, 13" - same user.


Answer



you could use a subquery with count group by ip > 1




if you want the user on same result



select m.ip, group_concat(m.user_id)
from my_table m.ip
inner join (
select ip
from my_table
group by ip
having count(*) > 1


) t on t.ip = m
group by m.ip


otherwise if you want user_id on different row



select m.user_id
from my_table m.ip
inner join (
select ip

from my_table
group by ip
having count(*) > 1

) t on t.ip = m

google maps - Cant acces a variable from inside a function of an event listener / Angular 2



i am using google maps api v3 and have some polygons on my map. I am trying to add an event that on click deletes them all and calls another function inside the callback function for the event but i keep getting TypeError: Cannot read property 'length' of undefined on line 64 (thats inside the event listener and its telling me the Polys array its not defined). Also if i try to add a function inside the listener it wont recognize it, i figure it has to do with an scope problem but i dont know how to resolve it.
Thanks for the help in advance.






export class InicioComponent implements OnInit, AfterViewInit {

locaciones: Locacion[] = [];
regiones: Region[];
polys: any[] = [];
constructor(private locacionService: LocacionService, private router: Router) { }

getLocaciones(): void {

this.locacionService.getLocaciones().then(locaciones => this.locaciones = locaciones);
}

public loadLocaciones(router: Router) {
for (let i = 0; i < this.locaciones.length; i++) {
const marker = new google.maps.Marker({
position: new google.maps.LatLng(this.locaciones[i].latitud, this.locaciones[i].longitud),
map: map,
label: {
color: 'black',

fontWeight: 'bold',
text: this.locaciones[i].nombre,
},
idLocacion: this.locaciones[i].id
});
google.maps.event.addListener(marker, 'click',() => {
router.navigate(['/locacion', this.locaciones[i].id]);
});
}
}

getRegiones() {
this.locacionService.getRegiones().then(regiones => {
this.regiones = regiones;
console.log(this.regiones);
});
}
loadRegiones(regiones: Region[]) {
for(let i = 0; i < regiones.length; i++) {
const p = new google.maps.Polygon({
paths: regiones[i].mapData.bounds,

strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
idRegion: regiones[i].id
});
p.setMap(map);
this.polys.push(p);
google.maps.event.addListener(p, 'click', function(event){

for( let j = 0; j < this.polys.length; j++) {
this.polys[j].setMap(null);
}
this.loadLocaciones();

});
}
}





Answer



You need to use arrow function ()=>, instead of the function keyword. When you use the function keyword, you loose scope to this. Change your code to this:



google.maps.event.addListener(p, 'click', (event) => {
for( let j = 0; j < this.polys.length; j++) {
this.polys[j].setMap(null);
}
this.loadLocaciones();
});


android - Java: Get time in "hh:MM:ss a" format

I was building an android app and i was using Date class in my project to get the current date. I formatted the date with simpledateformatter and displayed it like dd-mm-yyyy (i.e. day month year) .



Now i also want to get the time in format of hh:MM:ss a (hours minutes seconds AM/PM)




As i was using date's instance i saw that it displays date and time also ( in default format). So i tried to fetch time from the date's instance.(let's say d is date class instance). I also found getTime() method of date class and performed d.getTime() but it returned me a long (which is duration from some fixed time from past to current time). Now i want time in desired format but this getTime() method is giving me long.



May you provide me some way on how to process this long value to get the desired format of time out of it. For example , d.getTime() return me some value( say 11233) and i want in format like this (11:33:22).

reference - What's the difference between SoftReference and WeakReference in Java?



What's the difference between java.lang.ref.WeakReference and java.lang.ref.SoftReference ?


Answer



From Understanding Weak References, by Ethan Nicholas:




Weak references




A weak reference, simply put, is a
reference that isn't strong enough to
force an object to remain in memory.
Weak references allow you to leverage
the garbage collector's ability to
determine reachability for you, so you
don't have to do it yourself. You
create a weak reference like this:



WeakReference weakWidget = new WeakReference(widget);



and then
elsewhere in the code you can use
weakWidget.get() to get the actual
Widget object. Of course the weak
reference isn't strong enough to
prevent garbage collection, so you may
find (if there are no strong
references to the widget) that

weakWidget.get() suddenly starts
returning null.



...



Soft references



A soft reference is exactly like a
weak reference, except that it is less
eager to throw away the object to

which it refers. An object which is
only weakly reachable (the strongest
references to it are WeakReferences)
will be discarded at the next garbage
collection cycle, but an object which
is softly reachable will generally
stick around for a while.



SoftReferences aren't required to
behave any differently than

WeakReferences, but in practice softly
reachable objects are generally
retained as long as memory is in
plentiful supply. This makes them an
excellent foundation for a cache, such
as the image cache described above,
since you can let the garbage
collector worry about both how
reachable the objects are (a strongly
reachable object will never be removed

from the cache) and how badly it needs
the memory they are consuming.




And Peter Kessler added in a comment:




The Sun JRE does treat SoftReferences differently from WeakReferences. We attempt to hold on to object referenced by a SoftReference if there isn't pressure on the available memory. One detail: the policy for the "-client" and "-server" JRE's are different: the -client JRE tries to keep your footprint small by preferring to clear SoftReferences rather than expand the heap, whereas the -server JRE tries to keep your performance high by preferring to expand the heap (if possible) rather than clear SoftReferences. One size does not fit all.



python 3.x - Python3: If elif else with while loops in a function

I am quite confused about what is wrong with my code. I am trying to make a math practice program. However, when I choose an operation, no matter what I type in, it will always take me to addition. Can someone please help me solve this problem. My little brother is not very excitedly waiting. :)



from random import randint
print("Welcome to Luke's Math Practice")
score = 0

def mathAddition():
global score
numberOne = randint(0, 100)

numberTwo = randint(0, 100)
answer = input(f"{numberOne} + {numberTwo} = ")
correctAnswer = numberOne + numberTwo
if int(answer) == correctAnswer:
print("Correct!")
score = score + 1
elif int(answer) != correctAnswer:
print("Incorrect!")
print("The Correct Answer was", correctAnswer)
print("Your Score Is:", score)

choiceOperation()
else:
print("Sorry That Was an Invalid Answer")

def mathSubtraction():
global score
numberOne = randint(0, 100)
numberTwo = randint(0, 100)
answer = input(f"{numberOne} - {numberTwo} = ")
correctAnswer = numberOne - numberTwo

if int(answer) == correctAnswer:
print("Correct!")
score = score + 1
elif int(answer) != correctAnswer:
print("Incorrect!")
print("The Correct Answer was", correctAnswer)
print("Your Score Is:", score)
choiceOperation()
else:
print("Sorry That Was an Invalid Answer")


def mathMultiplication():
global score
numberOne = randint(0, 20)
numberTwo = randint(0, 20)
answer = input(f"{numberOne} * {numberTwo} = ")
correctAnswer = numberOne * numberTwo
if int(answer) == correctAnswer:
print("Correct!")
score = score + 1

elif int(answer) != correctAnswer:
print("Incorrect!")
print("The Correct Answer was", correctAnswer)
print("Your Score Is:", score)
choiceOperation()
else:
print("Sorry That Was an Invalid Answer")

def mathDivision():
global score

numberOne = randint(0, 20)
numberTwo = randint(0, 20)
answer = input(f"{numberOne} / {numberTwo} = ")
correctAnswer = numberOne / numberTwo
if int(answer) == correctAnswer:
print("Correct!")
score = score + 1
elif int(answer) != correctAnswer:
print("Incorrect!")
print("The Correct Answer was", correctAnswer)

print("Your Score Is:", score)
choiceOperation()
else:
print("Sorry That Was an Invalid Answer")

def choiceOperation():
operationChoice = input("Would you like to practice adding, subtracting, multiplying, or dividing? ")
if operationChoice == "add" or "+" or "adding" or "addition":
while True:
mathAddition()

elif operationChoice == "subtract" or "-" or "subtracting" or "subtraction":
while True:
mathSubtraction()
elif operationChoice == "multiply" or "*" or "x" or "multipying" or "multiplication":
while True:
mathMultiplication()
elif operationChoice == "divide" or "/" or "dividing" or "division":
while True:
mathDivision()
else:

print("Sorry, That Was an Invalid Choice")

choiceOperation()

How to deal with floating point number precision in JavaScript?



I have the following dummy test script:






function test() {
var x = 0.1 * 0.2;
document.write(x);
}
test();






This will print the result 0.020000000000000004 while it should just print 0.02 (if you use your calculator). As far as I understood this is due to errors in the floating point multiplication precision.



Does anyone have a good solution so that in such case I get the correct result 0.02? I know there are functions like toFixed or rounding would be another possibility, but I'd like to really have the whole number printed without any cutting and rounding. Just wanted to know if one of you has some nice, elegant solution.



Of course, otherwise I'll round to some 10 digits or so.


Answer



From the Floating-Point Guide:





What can I do to avoid this problem?



That depends on what kind of
calculations you’re doing.




  • If you really need your results to add up exactly, especially when you
    work with money: use a special decimal
    datatype.


  • If you just don’t want to see all those extra decimal places: simply
    format your result rounded to a fixed
    number of decimal places when
    displaying it.

  • If you have no decimal datatype available, an alternative is to work
    with integers, e.g. do money
    calculations entirely in cents. But
    this is more work and has some
    drawbacks.





Note that the first point only applies if you really need specific precise decimal behaviour. Most people don't need that, they're just irritated that their programs don't work correctly with numbers like 1/10 without realizing that they wouldn't even blink at the same error if it occurred with 1/3.



If the first point really applies to you, use BigDecimal for JavaScript, which is not elegant at all, but actually solves the problem rather than providing an imperfect workaround.


javascript - How does the spread syntax affect array splice



I found the following code and I don't know what is the difference between A and B:



var fruits = ["Banana", "Orange", "Apple", "Mango"];


A



fruits.splice(2,0,["Lemon", "Kiwi"]);


B



fruits.splice(...[2,0].concat(["Lemon", "Kiwi"]));




var fruits = ["Banana", "Orange", "Apple", "Mango"];
var A = fruits.splice(2, 0, ["Lemon", "Kiwi"]);
var B = fruits.splice(...[2, 0].concat(["Lemon", "Kiwi"]));

console.log(A)
console.log(B)




Answer



First of all, Statement A & Statement B will generate different results.



In Statement A, you are inserting an array (["Lemon", "Kiwi"]) as an array element at position 2 while removing 0 items. So, you are inserting a string array in another string array at position 2.





var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.splice(2,0,["Lemon", "Kiwi"]);

console.log(fruits);





However, Statement B is much more interesting. To, understand it fully, first log out it's core portion like this:





console.log(...[2,0].concat(["Lemon", "Kiwi"]));  // basic array concatenation then spread





As you can see it generates, 2 0 Lemon Kiwi. Then it is passed as parameter to fruits.splice(..here..). According to array#splice it will enter two strings (Lemon & Kiwi) at position 2, while removing 0 elements.





var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.splice(...[2,0].concat(["Lemon", "Kiwi"]));
// is same as fruits.splice(2, 0, 'Lemon', 'Kiwi')

console.log(fruits);





NOTE:




  • array#splice updates the original array.

  • Statement A inserts an array (IE ["Lemon", "Kiwi"]) in parent string array whereas, Statement B inserts two strings (IE 'Lemon', 'Kiwi') in parent string array.


c++ - Cast a void pointer to a struct or memcpy to new struct?

I am passing a void * as an argument to a function foo(void* parm) which calls function bar(STmyStruct* parm)
Should I cast the void pointer to STmyStruct* or create a new struct, memcpy what the void* points to and then pass a pointer to that struct?
I guess solution A is more efficient?



A:    foo(void* parm)
{

bar((STmyStruct*) parm)
}

B: foo(void* parm)
{
STmyStruct myStr;
memcpy(&myStr, parm, sizeof(STmyStruct));
bar(&myStr)
}



bar(STmyStruct* mystr);

python - Query about IF statements

opened_file = open('AppleStore.csv')
from csv import reader
read_file = reader(opened_file)
apps_data = list(read_file)

games_social_ratings = []
for row in apps_data[1:]:

rating = float(row[7])
genre = row[11]
if genre=='Games'or 'Social Networking':
games_social_ratings.append(rating)
print(len(games_social_ratings))
print(len(apps_data))


I am working through an online coding course which imports a bunch of data on apps on the appstore and asks us to work out the average rating of games or social networking apps. When doing so I accidentally typed the if statement as shown above:




if genre=='Games'or 'Social Networking':


Heres what I dont understand, there are in total 7197 apps, if I use the above IF statement, the length of my games_social_rating list is 7197. The total number of games apps are 3862 and the total number of social networking apps are 167. Where is the number 7197 coming from? Can someone tell me what the computer is doing when I type in the above code? I would've thought an error would come up instead.



My only reasoning is that 'social networking' registers as a true statement and thus since the sentence



if genre=='Games'or 'Social Networking':



reads
if genre=='games' or true:



In which case it would append every item in the list. But why would it be a true statement?

javascript - Check whether a string matches a regex in JS



I want to use JavaScript (can be with jQuery) to do some client-side validation to check whether a string matches the regex:



^([a-z0-9]{5,})$


Ideally it would be an expression that returned true or false.



I'm a JavaScript newbie, does match() do what I need? It seems to check whether part of a string matches a regex, not the whole thing.



Answer



Use regex.test() if all you want is a boolean result:





console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false

console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true

console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true






...and you could remove the () from your regexp since you've no need for a capture.


debian - "Call to undefined function mysql_connect()" after upgrade to php-7


Warning This extension was deprecated in PHP 5.5.0, and it was removed
in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be
used. See also MySQL: choosing an API guide. Alternatives to this function include:




mysqli_connect()

PDO::__construct()



use MySQLi or PDO



$con = mysqli_connect('localhost', 'username', 'password', 'database');


Read this

python - Hiding axis text in matplotlib plots



I'm trying to plot a figure without tickmarks or numbers on either of the axes (I use axes in the traditional sense, not the matplotlib nomenclature!). An issue I have come across is where matplotlib adjusts the x(y)ticklabels by subtracting a value N, then adds N at the end of the axis.



This may be vague, but the following simplified example highlights the issue, with '6.18' being the offending value of N:



import matplotlib.pyplot as plt
import random
prefix = 6.18


rx = [prefix+(0.001*random.random()) for i in arange(100)]
ry = [prefix+(0.001*random.random()) for i in arange(100)]
plt.plot(rx,ry,'ko')

frame1 = plt.gca()
for xlabel_i in frame1.axes.get_xticklabels():
xlabel_i.set_visible(False)
xlabel_i.set_fontsize(0.0)
for xlabel_i in frame1.axes.get_yticklabels():

xlabel_i.set_fontsize(0.0)
xlabel_i.set_visible(False)
for tick in frame1.axes.get_xticklines():
tick.set_visible(False)
for tick in frame1.axes.get_yticklines():
tick.set_visible(False)

plt.show()



The three things I would like to know are:




  1. How to turn off this behaviour in the first place (although in most cases it is useful, it is not always!) I have looked through matplotlib.axis.XAxis and cannot find anything appropriate


  2. How can I make N disappear (i.e. X.set_visible(False))


  3. Is there a better way to do the above anyway? My final plot would be 4x4 subplots in a figure, if that is relevant.



Answer



Instead of hiding each element, you can hide the whole axis:




frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)


Or, you can set the ticks to an empty list:



frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])



In this second option, you can still use plt.xlabel() and plt.ylabel() to add labels to the axes.


How to get an enum value from a string value in Java?



Say I have an enum which is just



public enum Blah {
A, B, C, D
}


and I would like to find the enum value of a string, for example "A" which would be Blah.A. How would it be possible to do this?



Is the Enum.valueOf() the method I need? If so, how would I use this?


Answer



Yes, Blah.valueOf("A") will give you Blah.A.



Note that the name must be an exact match, including case: Blah.valueOf("a") and Blah.valueOf("A ") both throw an IllegalArgumentException.



The static methods valueOf() and values() are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, Dialog.ModalityType shows both methods.


character - Why choose that birth name for John Blake? - Movies & TV




Near the end of The Dark Knight Rises, we learn that




John Blake's birth name is Robin, and that John Blake is merely an alias.




What motivated the Nolan brothers to include this in the film? Are they merely nudging and winking at the audience? Furthermore, why Robin? The real Robin's (original) name is Dick Grayson (though as the character evolved, was reborn, became Nightwing among others his identity changed).


Answer



Analyzing the past two films and Rises, Nolan (Director) and his brother Jonathan (Screenplay Writer) are trying to envision a world where they asked the question… "What if... Batman existed in our current world today as opposed to the comics." Thus the feel and directing has a less comic book-ish (if that's a word) look, and more of a real world view.




This film take on Robin is quite incredible when you think about it. Like the previous person in this article wrote, he is an embodiment of all the Robin’s in the comics. In contrast you have Nolan’s Robin (John Blake) who is, at this point, the first Robin “Dick Grayson” to Batman. He’s referred to being hot headed and angry like the Robin “Jason Todd”. For the “Tim Drake” Robin… well, he was the one that was able to deduce batman of his true identity and was also depicted as an orphan. And with the film using elements from the “The Dark Knight Returns” comic by Frank Miller, the role of that Robin was a female “Carrie”.


javascript - jQuery scroll to element



I have this input element:






Then I have some other elements, like other text inputs, textareas, etc.




When the user clicks on that input with #subject, the page should scroll to the last element of the page with a nice animation. It should be a scroll to bottom and not to top.



The last item of the page is a submit button with #submit:






The animation should not be too fast and should be fluid.




I am running the latest jQuery version. I prefer to not install any plugin but to use the default jQuery features to achieve this.


Answer



Assuming you have a button with the id button, try this example:



$("#button").click(function() {
$([document.documentElement, document.body]).animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});



I got the code from the article Smoothly scroll to an element without a jQuery plugin. And I have tested it on the example below.









Test




Test 2






Java String Scanner input does not wait for info, moves directly to next statement. How to wait for info?

I am writing a simple program that prompts a user to enter a number of students, then asks the user to enter each student's name and score in order to determine which student has the highest score.




I have written the program code and it compiles. First line asks for a number of students and waits for input. The second line is supposed to ask for a student name and wait for input, then a third line should print ans ask for that student's score, and wait for input but after the second line prints, the third line is immediately called (2nd line does not wait for input) and then I get a runtime error when trying to enter the requested information after the third line.



How do I adjust the code so that the second line prints and waits for a string to be entered before printing the third line?



import java.util.Scanner;

public class HighestScore {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);


System.out.print("Enter the number of students: ");
int numOfStudents = input.nextInt();

System.out.print("Enter a student's name: ");
String student1 = input.nextLine();

System.out.print("Enter that student's score: ");
int score1 = input.nextInt();


for (int i = 0; i <= numOfStudents - 1; i++) {

System.out.println("Enter a student's name: ");
String student = input.nextLine();

System.out.println("Enter that student's score: ");
int score = input.nextInt();

if (score > score1) {
student1 = student;

score1 = score;
}
}
System.out.println("Top student " +
student1 + "'s score is " + score1);
}
}

Monday, January 29, 2018

ajax - How to pass a value of a variable from a java class to the jsp page



I have 2 files named Admin.java and index.jsp.



In Admin.java through a function I retrieve the value of the varible named res. This variable needs to be passed to a JSP page.



The Admin.java is in C:\Users\praveen\workspace\SemanticWeb\src\controller whereas the index.jsp is in C:\Users\praveen\workspace\SemanticWeb\WebContent.



The code of Admin.java is:



public Admin() 
{
super();
}

protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{

if (action.equals("login"))
{
String userName="";
String password="";

userName = request.getParameter("username");
password = request.getParameter("password");

response.setCharacterEncoding("UTF-8");

SemanticSearch semsearch = new SemanticSearch(request.getSession());
semsearch.loadData(REALPATH + RDFDATASOURCEFILE1);

String res=semsearch.searchForUser(userName, password);
System.out.println("The value of res been passed is "+res);

request.setAttribute("rest", res);

return;
}


The code of index.jsp is



function login(user, pass) 
{

$.ajax({
type:"GET",
url: "Admin?action=login",
dataType: "text",
data: { username: user, password: pass },
success: function(response){

}


within the



function(response)
{
......
}


I need to access the value of res passed by Admin.java. I am not able to get any proper help for my code on the Internet. Please can someone help me with this.


Answer



From your code,



request.setAttribute("rest", res);


You shouldn't set it as request attribute. Setting request attributes is only useful if you're forwarding to a JSP file. You need to write it straight to the response yourself. Replace the line by



response.getWriter().write(res);


This way it'll end up in the response body and be available as variable response in your JS function.



See also:




linux - How to redirect output to a file and stdout



In bash, calling foo would display any output from that command on the stdout.



Calling foo > output would redirect any output from that command to the file specified (in this case 'output').



Is there a way to redirect output to a file and have it display on stdout?



Answer



The command you want is named tee:



foo | tee output.file


For example, if you only care about stdout:



ls -a | tee output.file



If you want to include stderr, do:



program [arguments...] 2>&1 | tee outfile


2>&1 redirects channel 2 (stderr/standard error) into channel 1 (stdout/standard output), such that both is written as stdout. It is also directed to the given output file as of the tee command.



Furthermore, if you want to append to the log file, use tee -a as:




program [arguments...] 2>&1 | tee -a outfile

c# - ReSharper "Cannot resolve symbol" even when project builds

My Tools:



Visual Studio 2012 Ultimate + Update 1



ReSharper v7.1.25.234




My Solution Build Status: Build Successfully



But when I install ReSharper and ReSharper code analysis is enable, many keywords of my code are red with this error:



"Cannot resolve symbol XXX"



Enter image description here







Another picture of my project >>



The ReSharper “CANNOT RESOLVE SYMBOL” errors are everywhere, but my project build process is successfully, and it works correctly.



Enter image description here



Additional Note: If I disable ReSharper Code Analysis, my project will be Normal, but I want to use ReSharper code analysis.







I tried ReSharper → OptionsGeneralClear Cache. But I still have this problem!







  • One month ago, I got these errors when I uninstalled Visual Studio 2012 RC and installed VS 2012 RTM.


  • I've already uninstalled and installed ReSharper again. But I have this problem yet!


  • My solution has five projects >> two loaded projects (main project + resource project) and three unloaded projects








I realize that my Visual Studio also has bigger problems (More information on Stack Overflow)




  • I can't add any reference to my projects (even inside new solutions and new projects)


  • I can't install any package (by "Packet Manager Console" or Manage NuGet Package)


  • I can't update any package (by "Packet Manager Console" or Manage NuGet Package)





I've done a lot of suggestions (of myself and others)




  • Re-resister some DLL files


  • Using some windows and registry repair tools


  • Remove ReSharper


  • Repair Visual Studio


  • and...





But I could not solve it.



I'm thinking of installing a new Windows :(






What is wrong, and how can I fix it?

android - debug-apk work fine but sign apk release crash on main acitvity



debug apk run fine but release sign apk crash on main activity checked everything . don't know where is the problem.[build.gradle][1]



android {
compileSdkVersion 28
defaultConfig {
applicationId "com.newtrendsdeveloper.unorthodox"
minSdkVersion 19

targetSdkVersion 28
versionCode 51
versionName "4.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
buildTypes {
release {
minifyEnabled true
shrinkResources true

proguardFiles 'proguard-rules.pro'
}
debug {}
}



flavorDimensions "color"
productFlavors {
blue {}
green {
applicationIdSuffix ".test"

versionNameSuffix "\"4.0-Microsoft Windows [Version 10.0.17134.407]\n" +
" (c) 2018 Microsoft Corporation. All rights reserved.\n" +
" \n" +
" C:\\Users\\HP\\Downloads\\Tusky-master\\Tusky-master\\app>\";" + getGitSha()
}
}

lintOptions {
disable 'MissingTranslation'
}

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
androidExtensions {
experimental = true
}
testOptions {
unitTests {
includeAndroidResources = true

}
}


}



ext.supportLibraryVersion = '28.0.0'
ext.daggerVersion = '2.19'



// if libraries are changed here, they should also be changed in LicenseActivity

dependencies {
implementation('com.mikepenz:materialdrawer:6.0.enter code here9@aar') {
transitive = true
}


Answer



Most probably it's the minifyEnabled true in your gradle file.



This removes unused code and obfuscates the code. So you can check what is the crash log, probably it's a class not found or null pointer exception. Check what is missing, and then in the build output you can search for a file called usage.txt. This includes all the things that were removed, and you can make sure it is being removed. If it is, then modify the proguard rules to keep that class.



You can check the documentation to understand more about proguard:

https://developer.android.com/studio/build/shrink-code



Of course another way to check if this is the issue is just to change the minifyEnabled to false and try again. If that works, then you can turn it back on and figure out what is causing the problem.


linux - How to redirect and append both stdout and stderr to a file with Bash?



To redirect stdout to a truncated file in Bash, I know to use:



cmd > file.txt


To redirect stdout in Bash, appending to a file, I know to use:



cmd >> file.txt


To redirect both stdout and stderr to a truncated file, I know to use:



cmd &> file.txt


How do I redirect both stdout and stderr appending to a file? cmd &>> file.txt did not work for me.


Answer



cmd >>file.txt 2>&1


Bash executes the redirects from left to right as follows:




  1. >>file.txt: Open file.txt in append mode and redirect stdout there.

  2. 2>&1: Redirect stderr to "where stdout is currently going". In this case, that is a file opened in append mode. In other words, the &1 reuses the file descriptor which stdout currently uses.


How to unload a package without restarting R

I would like to add an alternative solution. This solution does not directly answer your question on unloading a package but, IMHO, provides a cleaner alternative to achieve your desired goal, which I understand, is broadly concerned with avoiding name conflicts and trying different functions, as stated:



mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use



Function with_package offered via the withr package offers the possibility to:



attache a package to the search path, executes the code, then removes the package from the search path. The package namespace is not unloaded, however.



library(withr)
with_package("ggplot2", {
ggplot(mtcars) + geom_point(aes(wt, hp))
})
# Calling geom_point outside withr context
exists("geom_point")
# [1] FALSE

geom_point used in the example is not accessible from the global namespace. I reckon it may be a cleaner way of handling conflicts than loading and unloading packages.

java - Odd syntax in API "String::concat"

I was looking at some of the changes made to the Java SE API with 1.8, and I when looking at the new method Map.merge it shows an example of how to use it with the line



map.merge(key, msg, String::concat)


I understand how to use a lambda expressions to create anonymous functional interfaces, but this seems to use a method as a BiFunction. I like to understand and use obscure java syntaxes, but I can't find any mention of this one anywhere.

r - Trendline cannot be displayed after putting observer in my shiny app



Hello I have shiny app that takes a dataset as input, cleans it from NAs and then makes a plot out of it. The I give user the choice to add a trendline in that plot.
This is how my dataset looks like:



gene_symbol Entrez_ID Ensembl_ID     Lex1  Lex2  Lex3  Lex4  Lex5  Lex6  Lex7  Lex8  Lex9 Lex10


1 A1BG 5171 ENSG00000121~ 9 1 12 8 9 1 32 126 29 24
2 A1BG-AS1 52447 ENSG00000268~ 30 46 58 94 53 11 125 142 67 67
3 A1CF 9119 ENSG00000148~ 0 0 0 0 0 87 0 0 0 0
4 A2M 14002 ENSG00000175~ 273 520 1387 1549 2064 1101 2508 6420 3269 4475
5 A2M-AS1 38572 ENSG00000245~ 2 2 7 11 14 8 13 6 20 16
6 A2ML1 11899 ENSG00000166~ 0 0 0 0 0 2 0 2 1 0
7 A2ML1-AS1 44904 ENSG00000256~ 0 0 0 0 0 1 0 0 0 0
8 A2ML1-AS2 45000 ENSG00000256~ 0 0 0 0 0 0 0 0 0 0
9 A2MP1 44659 ENSG00000256~ 1 1 4 4 2 1 0 9 1 0
10 A3GALT2 15764 ENSG00000184~ 0 0 0 0 0 0 0 0 0 0



This is the working app.



#ui.r
library(shiny)
library(ggplot2)
library(plotly)



fluidPage(

# App title ----
titlePanel(div("CROSS CORRELATION",style = "color:blue")),

# Sidebar layout with input and output definitions ----
sidebarLayout(

# Sidebar panel for inputs ----
sidebarPanel(


# Input: Select a file ----
fileInput("file1", "Input CSV-File",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),

# Horizontal line ----
tags$hr(),


# Input: Checkbox if file has header ----
checkboxInput("header", "Header", TRUE),

# Input: Select separator ----
radioButtons("sep", "Separator",
choices = c(Comma = ",",
Semicolon = ";",
Tab = "\t"),
selected = ","),



# Horizontal line ----
tags$hr(),

# Input: Select number of rows to display ----
radioButtons("disp", "Display",
choices = c(Head = "head",
All = "all"),
selected = "head")






),
# Main panel for displaying outputs ----
mainPanel(

tabsetPanel(type = "tabs",

tabPanel("Table",
shiny::dataTableOutput("contents")),
tabPanel("Correlation Plot",
tags$style(type="text/css", "
#loadmessage {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
padding: 5px 0px 5px 0px;

text-align: center;
font-weight: bold;
font-size: 100%;
color: #000000;
background-color: #CCFF66;
z-index: 105;
}
"),conditionalPanel(condition="$('html').hasClass('shiny-busy')",
tags$div("Loading...",id="loadmessage")
),

fluidRow(
column(3, uiOutput("lx1")),
column(3,uiOutput("lx2"))),
hr(),
fluidRow(
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"
),
column(3,uiOutput("td")),

column(3,uiOutput("an"))),
fluidRow(
plotlyOutput("sc"))
))
)))
#server.r
function(input, output) {
rt<-reactive({
req(input$file1)


csvdata <- read.csv(input$file1$datapath,
header = input$header
)
if(input$disp == "head"){
head(csvdata)
} else{
csvdata
}
csvdata$Lex1=as.numeric(levels(csvdata$Lex1))[csvdata$Lex1]
csvdata$Lex2=as.numeric(levels(csvdata$Lex2))[csvdata$Lex2]

csvdata$Lex3=as.numeric(levels(csvdata$Lex3))[csvdata$Lex3]
csvdata$Lex4=as.numeric(levels(csvdata$Lex4))[csvdata$Lex4]
csvdata$Lex5=as.numeric(levels(csvdata$Lex5))[csvdata$Lex5]
csvdata$Lex6=as.numeric(levels(csvdata$Lex6))[csvdata$Lex6]
csvdata$Lex7=as.numeric(levels(csvdata$Lex7))[csvdata$Lex7]
csvdata$Lex8=as.numeric(levels(csvdata$Lex8))[csvdata$Lex8]
csvdata$Lex9=as.numeric(levels(csvdata$Lex9))[csvdata$Lex9]
csvdata$Lex10=as.numeric(levels(csvdata$Lex10))[csvdata$Lex10]
csvdata$Lex11=as.numeric(levels(csvdata$Lex11))[csvdata$Lex11]
csvdata$Lex12=as.numeric(levels(csvdata$Lex12))[csvdata$Lex12]



capture.output(csvdata[rowSums(is.na(csvdata)) > 0,],file = "Missing_genes.csv")


row.has.na <- apply(csvdata, 1, function(x){any(is.na(x))})
csvdata2 <- csvdata[!row.has.na,]

csvdata2
})


output$contents <- shiny::renderDataTable({

rt()
})


output$lx1<-renderUI({
selectInput("lx1", label = h4("Select 1st Expression Profile"),
choices = colnames(rt()[,4:15]),

selected = "Lex1")
})
output$lx2<-renderUI({
selectInput("lx2", label = h4("Select 2nd Expression Profile"),
choices = colnames(rt()[,4:15]),
selected = "Lex2")
})

output$td<-renderUI({
radioButtons("td", label = h4("Trendline"),

choices = list("Add Trendline" = "lm", "Remove Trendline" = ""),
selected = "")
})

output$an<-renderUI({

radioButtons("an", label = h4("Correlation Coefficient"),
choices = list("Add Cor.Coef" = cor(subset(rt(), select=c(input$lx1)),subset(rt(), select=c(input$lx2))), "Remove Cor.Coef" = ""),
selected = "")
})



output$sc<-renderPlotly({

p1 <- ggplot(rt(), aes_string(x = input$lx1, y = input$lx2))+
# Change the point options in geom_point
geom_point(color = "darkblue") +
# Change the title of the plot (can change axis titles
# in this option as well and add subtitle)
labs(title = "Cross Correlation") +

# Change where the tick marks are
scale_x_continuous(breaks = seq(0, 80000, 10000)) +
scale_y_continuous(breaks = seq(0, 120000, 20000)) +
# Change how the text looks for each element
theme(title = element_text(family = "Calibri",
size = 10,
face = "bold"),
axis.title = element_text(family = "Calibri Light",
size = 16,
face = "bold",

color = "darkgrey"),
axis.text = element_text(family = "Calibri",
size = 11))+
theme_bw()+
geom_smooth(method = input$td)+
annotate("text", x = 50000, y = 50000, label = as.character(input$an))

ggplotly(p1,source = "select", tooltip = c("key")) %>%
layout(hoverlabel = list(bgcolor = "white",
font = list(family = "Calibri",

size = 9,
color = "black")))

})




}



And here is the code that I added in order to make data labels persistent in my plot.



# 1. create reactive values
vals <- reactiveValues()
# 2. create df to store clicks
vals$click_all <- data.frame(x = numeric(),
y = numeric(),
label = character())
# 3. add points upon plot click

observe({
# get clicked point
click_data <- event_data("plotly_click", source = "select")
# get data for current point
label_data <- data.frame(x = click_data[["x"]],
y = click_data[["y"]],
label = click_data[["key"]],
stringsAsFactors = FALSE)
# add current point to df of all clicks
vals$click_all <- merge(vals$click_all,

label_data,
all = TRUE)
})
# 4. add labels for clicked points
geom_text(data = vals$click_all,
aes(x = x, y = y, label = label),
inherit.aes = FALSE, nudge_x = 0.25)


This is the new non-functional server.r which provides this issue that prevents the trendline from displaying. I know they are not errors but warnings but they still cause the issue:




Warning in qt((1 - level)/2, df) : NaNs produced
Warning in qt((1 - level)/2, df) : NaNs produced
Warning in qt((1 - level)/2, df) : NaNs produced
Warning in qt((1 - level)/2, df) : NaNs produced
Warning in qt((1 - level)/2, df) : NaNs produced
Warning in qt((1 - level)/2, df) : NaNs produced
Warning in qt((1 - level)/2, df) : NaNs produced

#server.r

function(input, output) {
rt<-reactive({
req(input$file1)

csvdata <- read.csv(input$file1$datapath,
header = input$header
)
if(input$disp == "head"){
head(csvdata)
} else{

csvdata
}
csvdata$Lex1=as.numeric(levels(csvdata$Lex1))[csvdata$Lex1]
csvdata$Lex2=as.numeric(levels(csvdata$Lex2))[csvdata$Lex2]
csvdata$Lex3=as.numeric(levels(csvdata$Lex3))[csvdata$Lex3]
csvdata$Lex4=as.numeric(levels(csvdata$Lex4))[csvdata$Lex4]
csvdata$Lex5=as.numeric(levels(csvdata$Lex5))[csvdata$Lex5]
csvdata$Lex6=as.numeric(levels(csvdata$Lex6))[csvdata$Lex6]
csvdata$Lex7=as.numeric(levels(csvdata$Lex7))[csvdata$Lex7]
csvdata$Lex8=as.numeric(levels(csvdata$Lex8))[csvdata$Lex8]

csvdata$Lex9=as.numeric(levels(csvdata$Lex9))[csvdata$Lex9]
csvdata$Lex10=as.numeric(levels(csvdata$Lex10))[csvdata$Lex10]
csvdata$Lex11=as.numeric(levels(csvdata$Lex11))[csvdata$Lex11]
csvdata$Lex12=as.numeric(levels(csvdata$Lex12))[csvdata$Lex12]


capture.output(csvdata[rowSums(is.na(csvdata)) > 0,],file = "Missing_genes.csv")


row.has.na <- apply(csvdata, 1, function(x){any(is.na(x))})

csvdata2 <- csvdata[!row.has.na,]

csvdata2
})

output$contents <- shiny::renderDataTable({

rt()
})



output$lx1<-renderUI({
selectInput("lx1", label = h4("Select 1st Expression Profile"),
choices = colnames(rt()[,4:15]),
selected = "Lex1")
})
output$lx2<-renderUI({
selectInput("lx2", label = h4("Select 2nd Expression Profile"),
choices = colnames(rt()[,4:15]),
selected = "Lex2")

})

output$td<-renderUI({
radioButtons("td", label = h4("Trendline"),
choices = list("Add Trendline" = "lm", "Remove Trendline" = ""),
selected = "")
})

output$an<-renderUI({


radioButtons("an", label = h4("Correlation Coefficient"),
choices = list("Add Cor.Coef" = cor(subset(rt(), select=c(input$lx1)),subset(rt(), select=c(input$lx2))), "Remove Cor.Coef" = ""),
selected = "")
})

# 1. create reactive values
vals <- reactiveValues()
# 2. create df to store clicks
vals$click_all <- data.frame(x = numeric(),
y = numeric(),

label = character())
# 3. add points upon plot click
observe({
# get clicked point
click_data <- event_data("plotly_click", source = "select")
# get data for current point
label_data <- data.frame(x = click_data[["x"]],
y = click_data[["y"]],
label = click_data[["key"]],
stringsAsFactors = FALSE)

# add current point to df of all clicks
vals$click_all <- merge(vals$click_all,
label_data,
all = TRUE)
})
output$sc<-renderPlotly({

p1 <- ggplot(rt(), aes_string(x = input$lx1, y = input$lx2,key = "gene_symbol"))+
# Change the point options in geom_point
geom_point(color = "darkblue") +

# Change the title of the plot (can change axis titles
# in this option as well and add subtitle)
labs(title = "Cross Correlation") +
# Change where the tick marks are
scale_x_continuous(breaks = seq(0, 80000, 10000)) +
scale_y_continuous(breaks = seq(0, 120000, 20000)) +
# Change how the text looks for each element
theme(title = element_text(family = "Calibri",
size = 10,
face = "bold"),

axis.title = element_text(family = "Calibri Light",
size = 16,
face = "bold",
color = "darkgrey"),
axis.text = element_text(family = "Calibri",
size = 11))+
theme_bw()+
geom_smooth(method = input$td)+
annotate("text", x = 50000, y = 50000, label = as.character(input$an))+
# 4. add labels for clicked points

geom_text(data = vals$click_all,
aes(x = x, y = y, label = label),
inherit.aes = FALSE, nudge_x = 0.25)
ggplotly(p1,source = "select", tooltip = c("key")) %>%
layout(hoverlabel = list(bgcolor = "white",
font = list(family = "Calibri",
size = 9,
color = "black")))

})





}


I ran this with iris dataset and it works so it is a matter of NAs I think. But as you can see in the beginning of my code I get rid of them. So why do they still cause the problem and prevent trendline from displaying?


Answer



Let's distill your question down: a plot worked as you expected for the iris dataset, but not for your dataset.




From what I can tell, you'd like a plot with one smoothed line for all of the data. Let's look at the iris plot:



p1 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, key = Species)) +
geom_point() +
geom_smooth()
ggplotly(p1, tooltip = c("key"))


enter image description here




We see three geom_smooth() lines, instead of one. We have one line per Species because geom_smooth() is using the key aesthetic from when ggplot was initialized.



Unlike the iris dataset, your dataset has a unique key (i.e. gene_symbol) for each row. An analgous dataset is mtcars -- each row is a different car model. Now, let's make the plot with mtcars:



mtcars$car <- row.names(mtcars)
p1 <- ggplot(mtcars, aes(x = mpg, y = cyl, key = car)) +
geom_point() +
geom_smooth()
ggplotly(p1, tooltip = c("key"))



enter image description here



We don't see any smoothed lines. geom_smooth is smoothing by car model, and there is only one data point per car model. Similarly, in your dataset, there is only one data point per gene_symbol.



So we need to make geom_smooth use all of the data points. We have three options:




  1. Set the key aesthetic only where needed (similar to this answer)


  2. Re-map the aesthetics for the geom_smooth layer

  3. Provide a group (similar to this answer)



Here is code for each of those options:



# 1. set the key aesthetic only where needed
# from: https://stackoverflow.com/a/47883636/8099834
mtcars$car <- row.names(mtcars)
p1 <- ggplot(mtcars, aes(x = mpg, y = cyl)) +

geom_point(aes(key = car)) +
geom_smooth()
ggplotly(p1, tooltip = c("key"))

# 2. re-map aesthetics for `geom_smooth`
mtcars$car <- row.names(mtcars)
p1 <- ggplot(mtcars, aes(x = mpg, y = cyl, key = car)) +
geom_point() +
geom_smooth(data = mtcars, aes(x = mpg, y = cyl), inherit.aes = FALSE)
ggplotly(p1, tooltip = c("key"))


# 3. provide a group
# from: https://stackoverflow.com/a/9769836/8099834
mtcars$car <- row.names(mtcars)
p1 <- ggplot(mtcars, aes(x = mpg, y = cyl, key = car, group = car)) +
geom_point() +
geom_smooth(aes(group = 1))
ggplotly(p1, tooltip = c("key"))



enter image description here



If you adapt your code using one of these options, I believe your app should work as you're expecting.


plot explanation - What's causing the hauntings/possessions? - Movies & TV



In Paranormal Activity 3, it is either alluded to or outright stated what is actually causing the hauntings/possessions that occur in the entire series. I can't for the life of me remember if it was supposed to be a ghost, a demon, or something else. What type of entity is supposed to be causing all of the events that are going on?


Answer




From the Paranormal Activity Wiki:




The Demon is the main antagonist of the Paranormal Activity film series, the demon haunts the families of two sisters, Katie and Krisiti. The Demon is then revealed to be Toby.





ScreenRant has a summary of the entire Paranormal Activity movie trilogy in chronological order, with the connections between the films pointed out.


php - syntax error, unexpected T_DOUBLE_ARROW




how i can rid of this error??



Parse error: syntax error, unexpected T_DOUBLE_ARROW in /var/www/core/restvt.api.php on line 35


PHP Code :



            $datax = Array();


foreach ($inis as $key => $data){

if ($data=="mem"){
$str = number_format($ARRAY[(array_search($data.':',$ARRAY)+2)]/1024,0,',','.')." MB [ ".number_format(($ARRAY[(array_search($data.':',$ARRAY)+2)]/$ARRAY[(array_search($data.':',$ARRAY)+1)])*100,0,',','.')." % ]";
array_push($datax, "mem"=>$str); //error here, why?
}else{
array_push($datax,$data=>$ARRAY[(array_search($data.':',$ARRAY)+1)]);
}
}


$jsonr = json_encode($datax);


thx alot for your help...


Answer



I hate seeing people use array_push - I know it's legal. In this case, you can't push a key => value to your array, just do this instead:



$datax['mem'] = $str;



Manual: http://php.net/manual/en/function.array-push.php




edit




If you insist on using the array_push type method, you'll need to create a new array with your new key value pair then use array_merge to join them:



$new_data = array('mem' => $str);

$datax = array_merge($datax, $new_data);

php - Is this a secure method to insert form data into a MySQL database?





Possible Duplicate:
How can I prevent SQL injection in PHP?







This is the example on w3schools.org:



HTML form:







Firstname:
Lastname:
Age:






File insert.php:




    $con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);


$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";


mysql_close($con)
?>


I've read through other questions on here, but I couldn't find a direct answer, as most were much more complicated.



I looked at How can I prevent SQL injection in PHP?, but I'm a bit confused on how to modify this:



$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');


$preparedStatement->execute(array(':column' => $unsafeValue));


Assuming I used the HTML form above and wanted to insert the data from field 'firstname' into the database, should it look like this? Or am I supposed to modify column?:



$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute(array(':column' => $firstname));

Answer




The example you provided inserts the post vars into the database without first analyzing them for evil user input. Use type casting, escaping/filter functions, prepared statements etc. before using them to interact with your DB.



A general rule to go by is to never trust user input. EVER!



Check out: Best way to stop SQL Injection in PHP



In response to your question, here is how you'd handle the entire form using PDO prepared statements.



$stmt = $db->prepare('INSERT INTO Persons (FirstName, LastName, Age) VALUES (:first_name, :last_name, :age)');


$stmt->execute(array(':first_name' => $first_name,':last_name' => $last_name, ':age' => $age));


If you just want to insert one column in the record like you asked, the syntax would be:



$stmt = $db->prepare('INSERT INTO Persons (FirstName) VALUES (:first_name)');

$stmt->execute(':first_name', $first_name);

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...