Programs & Examples On #Xml encoding

Meaning of - <?xml version="1.0" encoding="utf-8"?>

An XML declaration is not required in all XML documents; however XHTML document authors are strongly encouraged to use XML declarations in all their documents. Such a declaration is required when the character encoding of the document is other than the default UTF-8 or UTF-16 and no encoding was determined by a higher-level protocol. Here is an example of an XHTML document. In this example, the XML declaration is included.

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html 
 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Virtual Library</title>
  </head>
  <body>
    <p>Moved to <a href="http://example.org/">example.org</a>.</p>
 </body>
</html>

Please refer to the W3 standards for XML.

Cursor inside cursor

You could also sidestep nested cursor issues, general cursor issues, and global variable issues by avoiding the cursors entirely.

declare @rowid int
declare @rowid2 int
declare @id int
declare @type varchar(10)
declare @rows int
declare @rows2 int
declare @outer table (rowid int identity(1,1), id int, type varchar(100))
declare @inner table (rowid int  identity(1,1), clientid int, whatever int)

insert into @outer (id, type) 
Select id, type from sometable

select @rows = count(1) from @outer
while (@rows > 0)
Begin
    select top 1 @rowid = rowid, @id  = id, @type = type
    from @outer
    insert into @innner (clientid, whatever ) 
    select clientid whatever from contacts where contactid = @id
    select @rows2 = count(1) from @inner
    while (@rows2 > 0)
    Begin
        select top 1 /* stuff you want into some variables */
        /* Other statements you want to execute */
        delete from @inner where rowid = @rowid2
        select @rows2 = count(1) from @inner
    End  
    delete from @outer where rowid = @rowid
    select @rows = count(1) from @outer
End

How to connect wireless network adapter to VMWare workstation?

Workstation doesn't have a wireless NIC type, so direct wireless hardware access is out. If you just want to access through the extant host wireless connection, bridging is your answer.

I think the only way to get a wireless NIC dedicated to the VM would be using a USB wireless NIC as a USB-passthrough device on the VM. When you have Workstation running and a USB device plugged in, it should give you an option to change whether that device is connected to the host or to the VM.

in_array multiple values

IMHO Mark Elliot's solution's best one for this problem. If you need to make more complex comparison operations between array elements AND you're on PHP 5.3, you might also think about something like the following:

<?php

// First Array To Compare
$a1 = array('foo','bar','c');

// Target Array
$b1 = array('foo','bar');


// Evaluation Function - we pass guard and target array
$b=true;
$test = function($x) use (&$b, $b1) {
        if (!in_array($x,$b1)) {
                $b=false;
        }
};


// Actual Test on array (can be repeated with others, but guard 
// needs to be initialized again, due to by reference assignment above)
array_walk($a1, $test);
var_dump($b);

This relies on a closure; comparison function can become much more powerful. Good luck!

Adding CSRFToken to Ajax request

This worked for me (using jQuery 2.1)

$(document).ajaxSend(function(elm, xhr, s){
    if (s.type == "POST") {
        s.data += s.data?"&":"";
        s.data += "_token=" + $('#csrf-token').val();
    }
});

or this:

$(document).ajaxSend(function(elm, xhr, s){
    if (s.type == "POST") {
        xhr.setRequestHeader('x-csrf-token', $('#csrf-token').val());
    }
});

(where #csrf-token is the element containing the token)

Auto Increment after delete in MySQL

I came here looking for an answer to the Title question "MySQL - Auto Increment after delete" but I could only find an answer for that in the questions

By using something like:

DELETE FROM table;
ALTER TABLE table AUTO_INCREMENT = 1;

Note that Darin Dimitrov's answer explain really well AUTO_INCREMENT and it's usage. Take a look there before doing something you might regret.

PS: The question itself is more "Why you need to recycle key values?" and Dolph's answer cover that.

Explanation of <script type = "text/template"> ... </script>

jQuery Templates is an example of something that uses this method to store HTML that will not be rendered directly (that’s the whole point) inside other HTML: http://api.jquery.com/jQuery.template/

flow 2 columns of text automatically with CSS

Automatically floating two columns next to eachother is not currently possible only with CSS/HTML. Two ways to achieve this:

Method 1: When there's no continous text, just lots of non-related paragraphs:

Float all paragraphs to the left, give them half the width of the containing element and if possible set a fixed height.

<div id="container">
  <p>This is paragraph 1. Lorem ipsum ... </p>
  <p>This is paragraph 2. Lorem ipsum ... </p>
  <p>This is paragraph 3. Lorem ipsum ... </p>
  <p>This is paragraph 4. Lorem ipsum ... </p>
  <p>This is paragraph 5. Lorem ipsum ... </p>
  <p>This is paragraph 6. Lorem ipsum ... </p>
</div>

#container { width: 600px; }
#container p { float: left; width: 300px; /* possibly also height: 300px; */ }

You can also insert clearer-divs between paragraphs to avoid having to use a fixed height. If you want two columns, add a clearer-div between two-and-two paragraphs. This will align the top of the two next paragraphs, making it look more tidy. Example:

<div id="container">
  <p>This is paragraph 1. Lorem ipsum ... </p>
  <p>This is paragraph 2. Lorem ipsum ... </p>
  <div class="clear"></div>
  <p>This is paragraph 3. Lorem ipsum ... </p>
  <p>This is paragraph 4. Lorem ipsum ... </p>
  <div class="clear"></div>
  <p>This is paragraph 5. Lorem ipsum ... </p>
  <p>This is paragraph 6. Lorem ipsum ... </p>
</div>

/* in addition to the above CSS */
.clear { clear: both; height: 0; }

Method 2: When the text is continous

More advanced, but it can be done.

<div id="container">
  <div class="contentColumn">
    <p>This is paragraph 1. Lorem ipsum ... </p>
    <p>This is paragraph 2. Lorem ipsum ... </p>
    <p>This is paragraph 3. Lorem ipsum ... </p>
  </div>
  <div class="contentColumn">
    <p>This is paragraph 4. Lorem ipsum ... </p>
    <p>This is paragraph 5. Lorem ipsum ... </p>
    <p>This is paragraph 6. Lorem ipsum ... </p>
  </div>
</div>

.contentColumn { width: 300px; float: left; }
#container { width: 600px; }

When it comes to the ease of use: none of these are really easy for a non-technical client. You might attempt to explain to him/her how to do this properly, and tell him/her why. Learning very basic HTML is not a bad idea anyways, if the client is going to be updating the web pages via a WYSIWYG-editor in the future.

Or you could try to implement some Javascript-solution that counts the total number of paragraphs, splits them in two and creates columns. This will also degrade gracefully for those who have JavaScript disabled. A third option is to have all this splitting-into-columns-action happen serverside if this is an option.

(Method 3: CSS3 Multi-column Layout Module)

You might read about the CSS3 way of doing it, but it's not really practical for a production website. Not yet, at least.

Remove empty lines in a text file via grep

grep . FILE


(And if you really want to do it in sed, then: sed -e /^$/d FILE)

(And if you really want to do it in awk, then: awk /./ FILE)

Django CSRF check failing with an Ajax POST request

It seems nobody has mentioned how to do this in pure JS using the X-CSRFToken header and {{ csrf_token }}, so here's a simple solution where you don't need to search through the cookies or the DOM:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
xhttp.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
xhttp.send();

How much overhead does SSL impose?

I second @erickson: The pure data-transfer speed penalty is negligible. Modern CPUs reach a crypto/AES throughput of several hundred MBit/s. So unless you are on resource constrained system (mobile phone) TLS/SSL is fast enough for slinging data around.

But keep in mind that encryption makes caching and load balancing much harder. This might result in a huge performance penalty.

But connection setup is really a show stopper for many application. On low bandwidth, high packet loss, high latency connections (mobile device in the countryside) the additional roundtrips required by TLS might render something slow into something unusable.

For example we had to drop the encryption requirement for access to some of our internal web apps - they where next to unusable if used from china.

How can I override Bootstrap CSS styles?

See https://bootstrap.themes.guide/how-to-customize-bootstrap.html

  1. For simple CSS Overrides, you can add a custom.css below the bootstrap.css

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/custom.css">
    
  2. For more extensive changes, SASS is the recommended method.

    • create your own custom.scss
    • import Bootstrap after the changes in custom.scss
    • For example, let’s change the body background-color to light-gray #eeeeee, and change the blue primary contextual color to Bootstrap's $purple variable...

      /* custom.scss */    
      
      /* import the necessary Bootstrap files */
      @import "bootstrap/functions";
      @import "bootstrap/variables";
      
      /* -------begin customization-------- */   
      
      /* simply assign the value */ 
      $body-bg: #eeeeee;
      
      /* or, use an existing variable */
      $theme-colors: (
        primary: $purple
      );
      /* -------end customization-------- */  
      
      /* finally, import Bootstrap to set the changes! */
      @import "bootstrap";
      

Scala Doubles, and Precision

You can use scala.math.BigDecimal:

BigDecimal(1.23456789).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble

There are a number of other rounding modes, which unfortunately aren't very well documented at present (although their Java equivalents are).

Add Text on Image using PIL

Even more minimal example (draws "Hello world!" in black and with the default font in the top-left of the image):

...
from PIL import ImageDraw
...
ImageDraw.Draw(
    image  # Image
).text(
    (0, 0),  # Coordinates
    'Hello world!',  # Text
    (0, 0, 0)  # Color
)

How eliminate the tab space in the column in SQL Server 2008

Use the Below Code for that

UPDATE Table1 SET Column1 = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(Column1, CHAR(9), ''), CHAR(10), ''), CHAR(13), '')))`

Get the date of next monday, tuesday, etc

If I understand you correctly, you want the dates of the next 7 days?

You could do the following:

for ($i = 0; $i < 7; $i++)  
  echo date('d/m/y', time() + 86400 * $i);

Check the documentation for the date function for the format you want it in.

Cannot find module '@angular/compiler'

Just to add to this. You will get this error too, when you are running ng serve not from within your project folder. So always make sure your bash runs from your project folder.

CASE WHEN statement for ORDER BY clause

Another simple example from here..

SELECT * FROM dbo.Employee
ORDER BY 
 CASE WHEN Gender='Male' THEN EmployeeName END Desc,
 CASE WHEN Gender='Female' THEN Country END ASC

Why doesn't Git ignore my specified file?

Another possible reasona few instances of git clients running at the same time. For example "git shell" + "GitHub Desktop", etc.


This happened to me, I was using "GitHub Desktop" as the main client and it was ignoring some new .gitignore settings: commit after commit:

  1. You commit something.
  2. Next, commit: it ignores .gitignore settings. Commit includes lots of temp files mentioned in the .gitignore.
  3. Clear git cache; check whether .gitignore is UTF8; remove files -> commit -> move files back; skip 1 commit – nothing helped.

Reason: the Visual Studio Code editor was running in the background with the same opened repository. VS Code has built-in git control, and this makes some conflicts.

Solution: double-check multiple, hidden git clients and use only one git client at once, especially while clearing git cache.

Convert `List<string>` to comma-separated string

That's the way I'd prefer to see if I was maintaining your code. If you manage to find a faster solution, it's going to be very esoteric, and you should really bury it inside of a method that describes what it does.

(does it still work without the ToArray)?

CMake complains "The CXX compiler identification is unknown"

Your /home/gnu/bin/c++ seem to require additional flag to link things properly and CMake doesn't know about that.

To use /usr/bin/c++ as your compiler run cmake with -DCMAKE_CXX_COMPILER=/usr/bin/c++.

Also, CMAKE_PREFIX_PATH variable sets destination dir where your project' files should be installed. It has nothing to do with CMake installation prefix and CMake itself already know this.

inline conditionals in angular.js

For checking a variable content and have a default text, you can use:

<span>{{myVar || 'Text'}}</span>

Is there a built-in function to print all the current properties and values of an object?

You want vars() mixed with pprint():

from pprint import pprint
pprint(vars(your_object))

Apply a theme to an activity in Android?

You can apply a theme to any activity by including android:theme inside <activity> inside manifest file.

For example:

  1. <activity android:theme="@android:style/Theme.Dialog">
  2. <activity android:theme="@style/CustomTheme">

And if you want to set theme programatically then use setTheme() before calling setContentView() and super.onCreate() method inside onCreate() method.

Java - How to find the redirected url of a url?

@balusC I did as you wrote . In my case , I've added cookie information to be able to reuse the session .

   // get the cookie if need
    String cookies = conn.getHeaderField("Set-Cookie");

    // open the new connnection again
    conn = (HttpURLConnection) new URL(newUrl).openConnection();
    conn.setRequestProperty("Cookie", cookies);

How to analyse the heap dump using jmap in java

If you just run jmap -histo:live or jmap -histo, it outputs the contents on the console!

Disable/turn off inherited CSS3 transitions

Additionally there is a possibility to set a list of properties that will get transitioned by setting the property transition-property: width, height;, more details here

nodejs vs node on ubuntu 12.04

https://nodejs.org/en/download/

Download .pkg file on your mac and install it. it directly works.

?  ~ which node
/usr/local/bin/node
?  ~ node --version
v10.11.0
?  ~ which npm
/usr/local/bin/npm
?  ~ npm --version
6.4.1

What does yield mean in PHP?

The below code illustrates how using a generator returns a result before completion, unlike the traditional non generator approach that returns a complete array after full iteration. With the generator below, the values are returned when ready, no need to wait for an array to be completely filled:

<?php 

function sleepiterate($length) {
    for ($i=0; $i < $length; $i++) {
        sleep(2);
        yield $i;
    }
}

foreach (sleepiterate(5) as $i) {
    echo $i, PHP_EOL;
}

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

How to upgrade docker-compose to latest version

Based on @eric-johnson's answer, I'm currently using this in a script:

#!/bin/bash
compose_version=$(curl https://api.github.com/repos/docker/compose/releases/latest | jq .name -r)
output='/usr/local/bin/docker-compose'
curl -L https://github.com/docker/compose/releases/download/$compose_version/docker-compose-$(uname -s)-$(uname -m) -o $output
chmod +x $output
echo $(docker-compose --version)

it grabs the latest version from the GitHub api.

How to submit a form on enter when the textarea has focus?

Why do you want a textarea to submit when you hit enter?

A "text" input will submit by default when you press enter. It is a single line input.

<input type="text" value="...">

A "textarea" will not, as it benefits from multi-line capabilities. Submitting on enter takes away some of this benefit.

<textarea name="area"></textarea>

You can add JavaScript code to detect the enter keypress and auto-submit, but you may be better off using a text input.

How to use a class from one C# project with another C# project

To provide another much simpler solution:-

  1. Within the project, right click and select "Add -> Existing"
  2. Navigate to the class file in the adjacent project.
  3. The Add button is also a dropdown, click the dropdown and select

"Add as link"

Thats it.

Makefile - missing separator

You need to precede the lines starting with gcc and rm with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line). The result should look like this:

PROG = semsearch
all: $(PROG)
%: %.c
        gcc -o $@ $< -lpthread

clean:
        rm $(PROG)

Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:

PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread

clean: ; rm $(PROG)

Center Plot title in ggplot2

The ggeasy package has a function called easy_center_title() to do just that. I find it much more appealing than theme(plot.title = element_text(hjust = 0.5)) and it's so much easier to remember.

ggplot(data = dat, aes(time, total_bill, fill = time)) + 
  geom_bar(colour = "black", fill = "#DD8888", width = .8, stat = "identity") + 
  guides(fill = FALSE) +
  xlab("Time of day") +
  ylab("Total bill") +
  ggtitle("Average bill for 2 people") +
  ggeasy::easy_center_title()

enter image description here

Note that as of writing this answer you will need to install the development version of ggeasy from GitHub to use easy_center_title(). You can do so by running remotes::install_github("jonocarroll/ggeasy").

String literals and escape characters in postgresql

I find it highly unlikely for Postgres to truncate your data on input - it either rejects it or stores it as is.

milen@dev:~$ psql
Welcome to psql 8.2.7, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit

milen=> create table EscapeTest (text varchar(50));
CREATE TABLE
milen=> insert into EscapeTest (text) values ('This will be inserted \n This will not be');
WARNING:  nonstandard use of escape in a string literal
LINE 1: insert into EscapeTest (text) values ('This will be inserted...
                                              ^
HINT:  Use the escape string syntax for escapes, e.g., E'\r\n'.
INSERT 0 1
milen=> select * from EscapeTest;
          text
------------------------
 This will be inserted
  This will not be
(1 row)

milen=>

How do I disable the security certificate check in Python requests

If you want to send exactly post request with verify=False option, fastest way is to use this code:

import requests

requests.api.request('post', url, data={'bar':'baz'}, json=None, verify=False)

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

In short, git is trying to access a repo it considers on another filesystem and to tell it explicitly that you're okay with this, you must set the environment variable GIT_DISCOVERY_ACROSS_FILESYSTEM=1

I'm working in a CI/CD environment and using a dockerized git so I have to set it in that environment docker run -e GIT_DISCOVERY_ACROSS_FILESYSTEM=1 -v $(pwd):/git --rm alpine/git rev-parse --short HEAD\'

If you're curious: Above mounts $(pwd) into the git docker container and passes "rev-parse --short HEAD" to the git command in the container, which it then runs against that mounted volums.

Swift performSelector:withObject:afterDelay: is unavailable

Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    // your function here
}

Swift 3

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
    // your function here
}

Swift 2

let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) 
dispatch_after(dispatchTime, dispatch_get_main_queue(), { 
    // your function here 
})

How to compile and run C in sublime text 3?

Have you tried just writing out the whole command in a single string?

{
"cmd" : ["gcc $file_name -o ${file_base_name} && ./${file_base_name}"],
"selector" : "source.c",
"shell": true,
"working_dir" : "$file_path"
}

I believe (semi-speculation here), that ST3 takes the first argument as the "program" and passes the other strings in as "arguments". https://docs.python.org/2/library/subprocess.html#subprocess.Popen

How can I convince IE to simply display application/json rather than offer to download it?

If you are okay with just having IE open the JSON into a notepad, you can change your system's default program for .json files to Notepad.

To do this, create or find a .json file, right mouse click, and select "Open With" or "Choose Default Program."

This might come in handy if you by chance want to use Internet Explorer but your IT company wont let you edit your registry. Otherwise, I recommend the above answers.

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Right way to convert data.frame to a numeric matrix, when df also contains strings?

data.matrix(SFI)

From ?data.matrix:

Description:

 Return the matrix obtained by converting all the variables in a
 data frame to numeric mode and then binding them together as the
 columns of a matrix.  Factors and ordered factors are replaced by
 their internal codes.

std::cin input with spaces?

It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".

Use std::getline:

int main()
{
   std::string name, title;

   std::cout << "Enter your name: ";
   std::getline(std::cin, name);

   std::cout << "Enter your favourite movie: ";
   std::getline(std::cin, title);

   std::cout << name << "'s favourite movie is " << title;
}

Note that this is not the same as std::istream::getline, which works with C-style char buffers rather than std::strings.

Update

Your edited question bears little resemblance to the original.

You were trying to getline into an int, not a string or character buffer. The formatting operations of streams only work with operator<< and operator>>. Either use one of them (and tweak accordingly for multi-word input), or use getline and lexically convert to int after-the-fact.

How can I draw vertical text with CSS cross-browser?

I am using the following code to write vertical text in a page. Firefox 3.5+, webkit, opera 10.5+ and IE

.rot-neg-90 {
    -moz-transform:rotate(-270deg); 
    -moz-transform-origin: bottom left;
    -webkit-transform: rotate(-270deg);
    -webkit-transform-origin: bottom left;
    -o-transform: rotate(-270deg);
    -o-transform-origin:  bottom left;
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
}

How to create a dump with Oracle PL/SQL Developer?

Just as an update this can be done by using Toad 9 also.Goto Database>Export>Data Pump Export wizard.At the desitination directory window if you dont find any directory in the dropdown,then you probably have to create a directory object.

CREATE OR REPLACE DIRECTORY data_pmp_dir_test AS '/u01/app/oracle/oradata/pmp_dir_test'; 

See this for an example.

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

Failure [INSTALL_FAILED_OLDER_SDK] basically means that the installation has failed due to the target location (AVD/Device) having an older SDK version than the targetSdkVersion specified in your app.

N/B Froyo 2.2 API 8

To fix this simply change

targetSdkVersion="17" to targetSdkVersion="8"

cheers.

What is the proper #include for the function 'sleep()'?

What is the proper #include for the function 'sleep()'?

sleep() isn't Standard C, but POSIX so it should be:

#include <unistd.h>

How do you run multiple programs in parallel from a bash script?

Your script should look like:

prog1 &
prog2 &
.
.
progn &
wait
progn+1 &
progn+2 &
.
.

Assuming your system can take n jobs at a time. use wait to run only n jobs at a time.

How to make remote REST call inside Node.js? any CURL?

To use latest Async/Await features

https://www.npmjs.com/package/request-promise-native

npm install --save request
npm install --save request-promise-native

//code

async function getData (){
    try{
          var rp = require ('request-promise-native');
          var options = {
          uri:'https://reqres.in/api/users/2',
          json:true
        };

        var response = await rp(options);
        return response;
    }catch(error){
        throw error;
    }        
}

try{
    console.log(getData());
}catch(error){
    console.log(error);
}

PowerShell: Store Entire Text File Contents in Variable

To get the entire contents of a file:

$content = [IO.File]::ReadAllText(".\test.txt")

Number of lines:

([IO.File]::ReadAllLines(".\test.txt")).length

or

(gc .\test.ps1).length

Sort of hackish to include trailing empty line:

[io.file]::ReadAllText(".\desktop\git-python\test.ps1").split("`n").count

How to keep footer at bottom of screen

Perhaps the easiest is to use position: absolute to fix to the bottom, then a suitable margin/padding to make sure that the other text doesn't spill over the top of it.

css:

<style>
  body {
    margin: 0 0 20px;
  }
  .footer {
    position: absolute;
    bottom: 0;
    height: 20px;
    background: #f0f0f0;
    width: 100%;
  }
</style>

Here is the html main content.

<div class="footer"> Here is the footer. </div>

Adding minutes to date time in PHP

Without using a variable:

 $yourDate->modify("15 minutes");
 echo $yourDate->format( "Y-m-d H:i");

With using a variable:

 $interval= 15;
 $yourDate->modify("+{$interval } minutes");  
 echo $yourDate->format( "Y-m-d H:i");

How to print all key and values from HashMap in Android?

It's because your TextView recieve new text on every iteration and previuos value thrown away. Concatenate strings by StringBuilder and set TextView value after loop. Also you can use this type of loop:

for (Map.Entry<String, String> e : map.entrySet()) {
    //to get key
    e.getKey();
    //and to get value
    e.getValue();
}

Authentication versus Authorization

I found the analogy from this article really help me.

Consider a person walking up to a locked door to provide care to a pet while the family is away on vacation. That person needs:

  • Authentication is in the form of a key. The lock on the door only grants access to someone with the correct key in much the same way that a system only grants access to users who have the correct credentials.
  • Authorization is in the form of permissions. Once inside, the person has the authorization to access the kitchen and open the cupboard that holds the pet food. The person may not have permission to go into the bedroom for a quick nap.

So in short, authentication is about user identity while authorization is about user permission.

Invalid application path

When I got this error it appeared to be due to a security setting. When I changed the "Connect As" property to an administrator then I no longer got the message.

Obviously this isn't a good solution for a production environment - one should probably grant the least privileges necessary for the user IIS is going to be using by default. I'll update this answer if I learn more.

Replace string in text file using PHP

Thanks to your comments. I've made a function that give an error message when it happens:

/**
 * Replaces a string in a file
 *
 * @param string $FilePath
 * @param string $OldText text to be replaced
 * @param string $NewText new text
 * @return array $Result status (success | error) & message (file exist, file permissions)
 */
function replace_in_file($FilePath, $OldText, $NewText)
{
    $Result = array('status' => 'error', 'message' => '');
    if(file_exists($FilePath)===TRUE)
    {
        if(is_writeable($FilePath))
        {
            try
            {
                $FileContent = file_get_contents($FilePath);
                $FileContent = str_replace($OldText, $NewText, $FileContent);
                if(file_put_contents($FilePath, $FileContent) > 0)
                {
                    $Result["status"] = 'success';
                }
                else
                {
                   $Result["message"] = 'Error while writing file';
                }
            }
            catch(Exception $e)
            {
                $Result["message"] = 'Error : '.$e;
            }
        }
        else
        {
            $Result["message"] = 'File '.$FilePath.' is not writable !';
        }
    }
    else
    {
        $Result["message"] = 'File '.$FilePath.' does not exist !';
    }
    return $Result;
}

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

Leave you stuff there and Try the following as well:

Start > Right-click on My computer > Properties > Advanced system settings > Environment Variables > look for variable name called "Path" in the lower box

set path value value as: (you can just add it to the starting of line, don't forgot semi column in between )

c:\Program Files\java\jre7\bin

SQL Server add auto increment primary key to existing table

I had this issue, but couldn't use an identity column (for various reasons). I settled on this:

DECLARE @id INT
SET @id = 0 
UPDATE table SET @id = id = @id + 1 

Borrowed from here.

Using jQuery to build table rows from AJAX response(json)

This is working sample that I copied from my project.

_x000D_
_x000D_
 function fetchAllReceipts(documentShareId) {_x000D_
_x000D_
        console.log('http call: ' + uri + "/" + documentShareId)_x000D_
        $.ajax({_x000D_
            url: uri + "/" + documentShareId,_x000D_
            type: "GET",_x000D_
            contentType: "application/json;",_x000D_
            cache: false,_x000D_
            success: function (receipts) {_x000D_
                //console.log(receipts);_x000D_
_x000D_
                $(receipts).each(function (index, item) {_x000D_
                    console.log(item);_x000D_
                    //console.log(receipts[index]);_x000D_
_x000D_
                    $('#receipts tbody').append(_x000D_
                        '<tr><td>' + item.Firstname + ' ' + item.Lastname +_x000D_
                        '</td><td>' + item.TransactionId +_x000D_
                        '</td><td>' + item.Amount +_x000D_
                        '</td><td>' + item.Status + _x000D_
                        '</td></tr>'_x000D_
                    )_x000D_
_x000D_
                });_x000D_
_x000D_
_x000D_
            },_x000D_
            error: function (XMLHttpRequest, textStatus, errorThrown) {_x000D_
                console.log(XMLHttpRequest);_x000D_
                console.log(textStatus);_x000D_
                console.log(errorThrown);_x000D_
_x000D_
            }_x000D_
_x000D_
        });_x000D_
    }_x000D_
    _x000D_
    _x000D_
    // Sample json data coming from server_x000D_
    _x000D_
    var data =     [_x000D_
    0: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test1", Lastname: "Test1", }_x000D_
    1: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test 2", Lastname: "Test2", }_x000D_
];
_x000D_
  <button type="button" class="btn btn-primary" onclick='fetchAllReceipts("@share.Id")'>_x000D_
                                        RECEIPTS_x000D_
                                    </button>_x000D_
 _x000D_
 <div id="receipts" style="display:contents">_x000D_
                <table class="table table-hover">_x000D_
                    <thead>_x000D_
                        <tr>_x000D_
                            <th>Name</th>_x000D_
                            <th>Transaction</th>_x000D_
                            <th>Amount</th>_x000D_
                            <th>Status</th>_x000D_
                        </tr>_x000D_
                    </thead>_x000D_
                    <tbody>_x000D_
_x000D_
                    </tbody>_x000D_
                </table>_x000D_
         </div>_x000D_
         _x000D_
 _x000D_
    _x000D_
    _x000D_
    
_x000D_
_x000D_
_x000D_

Using import fs from 'fs'

For default exports you should use:

import * as fs from 'fs';

Or in case the module has named exports:

import {fs} from 'fs';

Example:

//module1.js

export function function1() {
  console.log('f1')
}

export function function2() {
  console.log('f2')
}

export default function1;

And then:

import defaultExport, { function1, function2 } from './module1'

defaultExport();  // This calls function1
function1();
function2();

Additionally, you should use Webpack or something similar to be able to use ES6 import

Changing the space between each item in Bootstrap navbar

I would suggest you just evenly space them as shown in this answer here

.navbar ul {
  list-style-type: none;
  padding: 0;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  flex-wrap: nowrap; /* assumes you only want one row */
}

Replace multiple strings at once

The top answer is equivalent to doing:

let text = find.reduce((acc, item, i) => {
  const regex = new RegExp(item, "g");
  return acc.replace(regex, replace[i]);
}, textarea);

Given this:

var textarea = $(this).val();
var find = ["<", ">", "\n"];
var replace = ["&lt;", "&gt;", "<br/>"];

In this case, no imperative programming is going on.

Edit and Continue: "Changes are not allowed when..."

Following shooting helped me using VS2010:

go to Tools, Options, Debugging, General and make sure "Require source files to exactly match the original version" is unchecked.

How do I get the current time only in JavaScript

Do you mean:

var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();

Adding calculated column(s) to a dataframe in pandas

The first four functions you list will work on vectors as well, with the exception that lower_wick needs to be adapted. Something like this,

def lower_wick_vec(o, l, c):
    min_oc = numpy.where(o > c, c, o)
    return min_oc - l

where o, l and c are vectors. You could do it this way instead which just takes the df as input and avoid using numpy, although it will be much slower:

def lower_wick_df(df):
    min_oc = df[['Open', 'Close']].min(axis=1)
    return min_oc - l

The other three will work on columns or vectors just as they are. Then you can finish off with

def is_hammer(df):
    lw = lower_wick_at_least_twice_real_body(df["Open"], df["Low"], df["Close"]) 
    cl = closed_in_top_half_of_range(df["High"], df["Low"], df["Close"])
    return cl & lw

Bit operators can perform set logic on boolean vectors, & for and, | for or etc. This is enough to completely vectorize the sample calculations you gave and should be relatively fast. You could probably speed up even more by temporarily working with the numpy arrays underlying the data while performing these calculations.

For the second part, I would recommend introducing a column indicating the pattern for each row and writing a family of functions which deal with each pattern. Then groupby the pattern and apply the appropriate function to each group.

How to set a Default Route (To an Area) in MVC

Accepted solution to this question is, while correct in summing up how to create a custom view engine, does not answer the question correctly. Issue here is that Pino is incorrectly specifying his default route. Particularly his "area" definition is incorrect. "Area" is checked via DataTokens collection and should be added as such:

var defaultRoute = new Route("",new RouteValueDictionary(){{"controller","Default"},{"action","Index"}},null/*constraints*/,new RouteValueDictionary(){{"area","Admin"}},new MvcRouteHandler());
defaultRoute.DataTokens.Add("Namespaces","MyProject.Web.Admin.Controller"); 
routes.Add(defaultRoute);

Specified "area" in defaults object will be ignored. Code above creates a default route, which catches on requests to your site's root and then calls Default controller, Index action in Admin area. Please also note "Namespaces" key being added to DataTokens, this is only required if you have multiple controllers with same name. This solution is verified with Mvc2 and Mvc3 .NET 3.5/4.0

How to destroy JWT Tokens on logout?

On Logout from the Client Side, the easiest way is to remove the token from the storage of browser.

But, What if you want to destroy the token on the Node server -

The problem with JWT package is that it doesn't provide any method or way to destroy the token.

So in order to destroy the token on the serverside you may use jwt-redis package instead of JWT

This library (jwt-redis) completely repeats the entire functionality of the library jsonwebtoken, with one important addition. Jwt-redis allows you to store the token label in redis to verify validity. The absence of a token label in redis makes the token not valid. To destroy the token in jwt-redis, there is a destroy method

it works in this way :

1) Install jwt-redis from npm

2) To Create -

var redis = require('redis');
var JWTR =  require('jwt-redis').default;
var redisClient = redis.createClient();
var jwtr = new JWTR(redisClient);

jwtr.sign(payload, secret)
    .then((token)=>{
            // your code
    })
    .catch((error)=>{
            // error handling
    });

3) To verify -

jwtr.verify(token, secret);

4) To Destroy -

jwtr.destroy(token)

Note : you can provide expiresIn during signin of token in the same as it is provided in JWT.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

You are mixing mysqli and mysql function.

If your are using mysql function then instead mysqli_real_escape_string($your_variable); use

$username = mysql_real_escape_string($_POST['username']);
$pass = mysql_real_escape_string($_POST['pass']);
$pass1 = mysql_real_escape_string($_POST['pass1']);
$email = mysql_real_escape_string($_POST['email']);

If your using mysqli_* function then you have to include your connection to database into mysqli_real_escape function :

$username = mysqli_real_escape_string($your_connection, $_POST['username']);
$pass = mysqli_real_escape_string($your_connection, $_POST['pass']);
$pass1 = mysqli_real_escape_string($your_connection, $_POST['pass1']);
$email = mysqli_real_escape_string($your_connection, $_POST['email']);

Note : Use mysqli_* function since mysql has been deprecated. For information please read mysqli_*

How to show data in a table by using psql command line interface?

On windows use the name of the table in quotes: TABLE "user"; or SELECT * FROM "user";

How to display tables on mobile using Bootstrap?

You might also consider trying one of these approaches, since larger tables aren't exactly friendly on mobile even if it works:

http://elvery.net/demo/responsive-tables/

I'm partial to 'No More Tables' but that obviously depends on your application.

Redis - Connect to Remote Server

I've been stuck with the same issue, and the preceding answer did not help me (albeit well written).

The solution is here : check your /etc/redis/redis.conf, and make sure to change the default

bind 127.0.0.1

to

bind 0.0.0.0

Then restart your service (service redis-server restart)

You can then now check that redis is listening on non-local interface with

redis-cli -h 192.168.x.x ping

(replace 192.168.x.x with your IP adress)

Important note : as several users stated, it is not safe to set this on a server which is exposed to the Internet. You should be certain that you redis is protected with any means that fits your needs.

How to close a window using jQuery

$(element).click(function(){
    window.close();
});

Note: you can not close any window that you didn't opened with window.open. Directly invoking window.close() will ask user with a dialogue box.

Clearing state es6 React

class MyComponent extends Component {
 constructor(props){
  super(props)
   this.state = {
     inputVal: props.inputValue
  }
   // preserve the initial state in a new object
   this.baseState = this.state 
}
  resetForm = () => {
    this.setState(this.baseState)
  }

}

access key and value of object using *ngFor

You have to do it like this for now, i know not very efficient as you don't want to convert the object you receive from firebase.

    this.af.database.list('/data/' + this.base64Email).subscribe(years => {
        years.forEach(year => {

            var localYears = [];

            Object.keys(year).forEach(month => {
                localYears.push(year[month])
            });

            year.months = localYears;

        })

        this.years = years;

    });

Git branching: master vs. origin/master vs. remotes/origin/master

One clarification (and a point that confused me):

"remotes/origin/HEAD is the default branch" is not really correct.

remotes/origin/master was the default branch in the remote repository (last time you checked). HEAD is not a branch, it just points to a branch.

Think of HEAD as your working area. When you think of it this way then 'git checkout branchname' makes sense with respect to changing your working area files to be that of a particular branch. You "checkout" branch files into your working area. HEAD for all practical purposes is what is visible to you in your working area.

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

In case this helps someone, I deployed my app to google play, when I uninstalled it and tried to run a debug on my device (new version) I was getting this failed update message.

I couldn't see the app in my device (it was already uninstalled) so I:

Installed the first version again from google play

Opened Settings/App/App name

Cleared the Data

Cleared the Cache

Uninstalled the app

Now you can deploy the debug version again to the device :)

find if an integer exists in a list of integers

The way you did is correct. It works fine with that code: x is true. probably you made a mistake somewhere else.

List<int> ints = new List<int>( new[] {1,5,7}); // 1

List<int> intlist=new List<int>() { 0,2,3,4,1}; // 2

var i = 5;
var x = ints.Contains(i);   // return true or false

pandas: merge (join) two data frames on multiple columns

Try this

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

left_on : label or list, or array-like Field names to join on in left DataFrame. Can be a vector or list of vectors of the length of the DataFrame to use a particular vector as the join key instead of columns

right_on : label or list, or array-like Field names to join on in right DataFrame or vector/list of vectors per left_on docs

What is considered a good response time for a dynamic, personalized web application?

It depends on what keeps your users happy. For example, Gmail takes quite a while to open at first, but users wait because it is worth waiting for.

How do I sort a VARCHAR column in SQL server that contains numbers?

 SELECT *,
       ROW_NUMBER()OVER(ORDER BY CASE WHEN ISNUMERIC (ID)=1 THEN CONVERT(NUMERIC(20,2),SUBSTRING(Id, PATINDEX('%[0-9]%', Id), LEN(Id)))END DESC)Rn ---- numerical
        FROM
            (

        SELECT '1'Id UNION ALL
        SELECT '25.20' Id UNION ALL

    SELECT 'A115' Id UNION ALL
    SELECT '2541' Id UNION ALL
    SELECT '571.50' Id UNION ALL
    SELECT '67' Id UNION ALL
    SELECT 'B48' Id UNION ALL
    SELECT '500' Id UNION ALL
    SELECT '147.54' Id UNION ALL
    SELECT 'A-100' Id
    )A

    ORDER BY 
    CASE WHEN ISNUMERIC (ID)=0                                /* alphabetical sort */ 
         THEN CASE WHEN PATINDEX('%[0-9]%', Id)=0
                   THEN LEFT(Id,PATINDEX('%[0-9]%',Id))
                   ELSE LEFT(Id,PATINDEX('%[0-9]%',Id)-1)
              END
    END DESC

How do I read a string entered by the user in C?

I found an easy and nice solution:

char*string_acquire(char*s,int size,FILE*stream){
    int i;
    fgets(s,size,stream);
    i=strlen(s)-1;
    if(s[i]!='\n') while(getchar()!='\n');
    if(s[i]=='\n') s[i]='\0';
    return s;
}

it's based on fgets but free from '\n' and stdin extra characters (to replace fflush(stdin) that doesn't works on all OS, useful if you have to acquire strings after this).

Split string based on a regular expression

By using (,), you are capturing the group, if you simply remove them you will not have this problem.

>>> str1 = "a    b     c      d"
>>> re.split(" +", str1)
['a', 'b', 'c', 'd']

However there is no need for regex, str.split without any delimiter specified will split this by whitespace for you. This would be the best way in this case.

>>> str1.split()
['a', 'b', 'c', 'd']

If you really wanted regex you can use this ('\s' represents whitespace and it's clearer):

>>> re.split("\s+", str1)
['a', 'b', 'c', 'd']

or you can find all non-whitespace characters

>>> re.findall(r'\S+',str1)
['a', 'b', 'c', 'd']

How to get the pure text without HTML element using JavaScript?

You can use this:

var element = document.getElementById('txt');
var text = element.innerText || element.textContent;
element.innerHTML = text;

Depending on what you need, you can use either element.innerText or element.textContent. They differ in many ways. innerText tries to approximate what would happen if you would select what you see (rendered html) and copy it to the clipboard, while textContent sort of just strips the html tags and gives you what's left.

innerText also has compatability with old IE browsers (came from there).

Wordpress keeps redirecting to install-php after migration

I tried all of these solutions before I realized that I had enabled opcache in PHP on my live environment. Wordpress was not reading a cached version of wp-config.

IntelliJ cannot find any declarations

If you are new to IntelliJ u May take some time to understand IntelliJ. If a Code has written in Java and using cucumber framework then we have two main files -

  1. Feature file
  2. Step definition file

Goal : what are things we have defined in feature file it must be navigate towards Step Definition File. (Ctrl +click ) Note :feature file has to contain some colourful gherkins keywords too .if it’s not follow the below steps

Solution : go to file >>settings >> plugins - search “Cucumber for Java” Add the plugin restart IntelliJ it will work for sure .

SQL alias for SELECT statement

Not sure exactly what you try to denote with that syntax, but in almost all RDBMS-es you can use a subquery in the FROM clause (sometimes called an "inline-view"):

SELECT..
FROM (
     SELECT ...
     FROM ...
     ) my_select
WHERE ...

In advanced "enterprise" RDBMS-es (like oracle, SQL Server, postgresql) you can use common table expressions which allows you to refer to a query by name and reuse it even multiple times:

-- Define the CTE expression name and column list.
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
-- Define the CTE query.
(
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
)
-- Define the outer query referencing the CTE name.
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID
ORDER BY SalesPersonID, SalesYear;

(example from http://msdn.microsoft.com/en-us/library/ms190766(v=sql.105).aspx)

PHP cURL error code 60

IMPORTANT: after 4 hours , working with laravel 5.7 and php 7.+ and run/use php artison serve on localhost trying to connect to mailgun .

IMPORTANT to Resolve the problem do not work with ip http://127.0.0.1:8000 use localhost or set domain name by host file

ok ,

Python datetime to string without microsecond component

As of Python 3.6+, the best way of doing this is by the new timespec argument for isoformat.

isoformat(timespec='seconds', sep=' ')

Usage:

>>> datetime.now().isoformat(timespec='seconds')
'2020-10-16T18:38:21'
>>> datetime.now().isoformat(timespec='seconds', sep=' ')
'2020-10-16 18:38:35'

How to use curl to get a GET request exactly same as using Chrome?

Open Chrome Developer Tools, go to Network tab, make your request (you may need to check "Preserve Log" if the page refreshes). Find the request on the left, right-click, "Copy as cURL".

Gradle, Android and the ANDROID_HOME SDK location

For Windows:

  1. Add ANDROID_HOME to the Environment Variables: ANDROID_HOME = C:/Users/YOUR_USERNAME/AppData/Local/Android/sdk
  2. Add %ANDROID_HOME%\platform-tools to the PATH.

How can I split a text into sentences?

Here is a middle of the road approach that doesn't rely on any external libraries. I use list comprehension to exclude overlaps between abbreviations and terminators as well as to exclude overlaps between variations on terminations, for example: '.' vs. '."'

abbreviations = {'dr.': 'doctor', 'mr.': 'mister', 'bro.': 'brother', 'bro': 'brother', 'mrs.': 'mistress', 'ms.': 'miss', 'jr.': 'junior', 'sr.': 'senior',
                 'i.e.': 'for example', 'e.g.': 'for example', 'vs.': 'versus'}
terminators = ['.', '!', '?']
wrappers = ['"', "'", ')', ']', '}']


def find_sentences(paragraph):
   end = True
   sentences = []
   while end > -1:
       end = find_sentence_end(paragraph)
       if end > -1:
           sentences.append(paragraph[end:].strip())
           paragraph = paragraph[:end]
   sentences.append(paragraph)
   sentences.reverse()
   return sentences


def find_sentence_end(paragraph):
    [possible_endings, contraction_locations] = [[], []]
    contractions = abbreviations.keys()
    sentence_terminators = terminators + [terminator + wrapper for wrapper in wrappers for terminator in terminators]
    for sentence_terminator in sentence_terminators:
        t_indices = list(find_all(paragraph, sentence_terminator))
        possible_endings.extend(([] if not len(t_indices) else [[i, len(sentence_terminator)] for i in t_indices]))
    for contraction in contractions:
        c_indices = list(find_all(paragraph, contraction))
        contraction_locations.extend(([] if not len(c_indices) else [i + len(contraction) for i in c_indices]))
    possible_endings = [pe for pe in possible_endings if pe[0] + pe[1] not in contraction_locations]
    if len(paragraph) in [pe[0] + pe[1] for pe in possible_endings]:
        max_end_start = max([pe[0] for pe in possible_endings])
        possible_endings = [pe for pe in possible_endings if pe[0] != max_end_start]
    possible_endings = [pe[0] + pe[1] for pe in possible_endings if sum(pe) > len(paragraph) or (sum(pe) < len(paragraph) and paragraph[sum(pe)] == ' ')]
    end = (-1 if not len(possible_endings) else max(possible_endings))
    return end


def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1:
            return
        yield start
        start += len(sub)

I used Karl's find_all function from this entry: Find all occurrences of a substring in Python

How to display string that contains HTML in twig template?

{{ word|striptags('<b>,<a>,<pre>')|raw }}

if you want to allow multiple tags

Sorted collection in Java

The problem with PriorityQueue is that it's backed up by an simple array, and the logic that gets the elements in order is done by the "queue[2*n+1] and queue[2*(n+1)]" thingie. It works great if you just pull from head, but makes it useless if you are trying to call the .toArray on it at some point.

I go around this problem by using com.google.common.collect.TreeMultimap, but I supply a custom Comparator for the values, wrapped in an Ordering, that never returns 0.

ex. for Double:

private static final Ordering<Double> NoEqualOrder = Ordering.from(new Comparator<Double>() {

    @Override
    public int compare(Double d1, Double d2)
    {
        if (d1 < d2) {
            return -1;
        }
        else {
            return 1;
        }
    }
});

This way I get the values in order when I call .toArray(), and also have duplicates.

Cause of a process being a deadlock victim

Q1:Could the time it takes for a transaction to execute make the associated process more likely to be flagged as a deadlock victim.

No. The SELECT is the victim because it had only read data, therefore the transaction has a lower cost associated with it so is chosen as the victim:

By default, the Database Engine chooses as the deadlock victim the session running the transaction that is least expensive to roll back. Alternatively, a user can specify the priority of sessions in a deadlock situation using the SET DEADLOCK_PRIORITY statement. DEADLOCK_PRIORITY can be set to LOW, NORMAL, or HIGH, or alternatively can be set to any integer value in the range (-10 to 10).

Q2. If I execute the select with a NOLOCK hint, will this remove the problem?

No. For several reasons:

Q3. I suspect that a datetime field that is checked as part of the WHERE clause in the select statement is causing the slow lookup time. Can I create an index based on this field? Is it advisable?

Probably. The cause of the deadlock is almost very likely to be a poorly indexed database.10 minutes queries are acceptable in such narrow conditions, that I'm 100% certain in your case is not acceptable.

With 99% confidence I declare that your deadlock is cased by a large table scan conflicting with updates. Start by capturing the deadlock graph to analyze the cause. You will very likely have to optimize the schema of your database. Before you do any modification, read this topic Designing Indexes and the sub-articles.

Pure CSS scroll animation

You can do it with anchor tags using css3 :target pseudo-selector, this selector is going to be triggered when the element with the same id as the hash of the current URL get an match. Example

Knowing this, we can combine this technique with the use of proximity selectors like "+" and "~" to select any other element through the target element who id get match with the hash of the current url. An example of this would be something like what you are asking.

How do I add an active class to a Link from React Router?

Expanding on @BaiJiFeiLong's answer, add an active={} property to the link:

<Nav.Link as={Link} to="/user" active={pathname.startsWith('/user')}>User</Nav.Link>

This will show the User link as active when any path starts with '/user'. For this to update with each path change, include withRouter() on the component:

import React from 'react'
import { Link, withRouter } from 'react-router-dom'
import Navbar from 'react-bootstrap/Navbar'
import Nav from 'react-bootstrap/Nav'

function Header(props) {
    const pathname = props.location.pathname

    return (
        <Navbar variant="dark" expand="sm" bg="black">
            <Navbar.Brand as={Link} to="/">
                Brand name
            </Navbar.Brand>
            <Navbar.Toggle aria-controls="basic-navbar-nav" />
            <Navbar.Collapse id="basic-navbar-nav">
                <Nav className="mr-auto">
                    <Nav.Link as={Link} to="/user" active={pathname.startsWith('/user')}>User</Nav.Link>
                    <Nav.Link as={Link} to="/about" active={pathname.startsWith('/about')}>About</Nav.Link>
                </Nav>
            </Navbar.Collapse>
        </Navbar>
    )
}

export default withRouter(Header)   // updates on every new page

Find all elements with a certain attribute value in jquery

It's not called a tag; what you're looking for is called an html attribute.

$('div[imageId="imageN"]').each(function(i,el){
  $(el).html('changes');
  //do what ever you wish to this object :) 
});

Can I have H2 autocreate a schema in an in-memory database?

If you are using Spring Framework with application.yml and having trouble to make the test find the SQL file on the INIT property, you can use the classpath: notation.

For example, if you have a init.sql SQL file on the src/test/resources, just use:

url=jdbc:h2:~/test;INIT=RUNSCRIPT FROM 'classpath:init.sql';DB_CLOSE_DELAY=-1;

Shift elements in a numpy array

Not numpy but scipy provides exactly the shift functionality you want,

import numpy as np
from scipy.ndimage.interpolation import shift

xs = np.array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])

shift(xs, 3, cval=np.NaN)

where default is to bring in a constant value from outside the array with value cval, set here to nan. This gives the desired output,

array([ nan, nan, nan, 0., 1., 2., 3., 4., 5., 6.])

and the negative shift works similarly,

shift(xs, -3, cval=np.NaN)

Provides output

array([  3.,   4.,   5.,   6.,   7.,   8.,   9.,  nan,  nan,  nan])

Is the practice of returning a C++ reference variable evil?

About horrible code:

int& getTheValue()
{
   return *new int;
}

So, indeed, memory pointer lost after return. But if you use shared_ptr like that:

int& getTheValue()
{
   std::shared_ptr<int> p(new int);
   return *p->get();
}

Memory not lost after return and will be freed after assignment.

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

What USB driver should we use for the Nexus 5?

The one from Google USB Driver worked fine for me on two machines (Windows 7 x64 on both). Once Windows failed to auto-install the driver, I just right-clicked on the phone in Device Manager, chose "update driver" and gave it the path that I'd unzipped that driver into.

What's the difference between next() and nextLine() methods from Scanner class?

I also got a problem concerning a delimiter. the question was all about inputs of

  1. enter your name.
  2. enter your age.
  3. enter your email.
  4. enter your address.

The problem

  1. I finished successfully with name, age, and email.
  2. When I came up with the address of two words having a whitespace (Harnet street) I just got the first one "harnet".

The solution

I used the delimiter for my scanner and went out successful.

Example

 public static void main (String args[]){
     //Initialize the Scanner this way so that it delimits input using a new line character.
    Scanner s = new Scanner(System.in).useDelimiter("\n");
    System.out.println("Enter Your Name: ");
    String name = s.next();
    System.out.println("Enter Your Age: ");
    int age = s.nextInt();
    System.out.println("Enter Your E-mail: ");
    String email = s.next();
    System.out.println("Enter Your Address: ");
    String address = s.next();

    System.out.println("Name: "+name);
    System.out.println("Age: "+age);
    System.out.println("E-mail: "+email);
    System.out.println("Address: "+address);
}

Pass path with spaces as parameter to bat file

If you have a path with spaces you must surround it with quotation marks (").

Not sure if that's exactly what you're asking though?

File opens instead of downloading in internet explorer in a href link

It should be fixed on server side. Your server should return this headers for this file types:

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

I had the same problem, to solve it set specific user from domain in iis -> action sidebar->Basic Settings -> Connect as... -> specific user

enter image description here

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation

In my case, i had installed only the JRE so you could check to make sure you actually have a valid jdk. if not i advise you to uninstall whatever java is installed and download a correct jdk from here (the jdk comes with a jre so no need to download anything else) after set the environment variable and your done

Using LIMIT within GROUP BY to get N results per group?

No, you can't LIMIT subqueries arbitrarily (you can do it to a limited extent in newer MySQLs, but not for 5 results per group).

This is a groupwise-maximum type query, which is not trivial to do in SQL. There are various ways to tackle that which can be more efficient for some cases, but for top-n in general you'll want to look at Bill's answer to a similar previous question.

As with most solutions to this problem, it can return more than five rows if there are multiple rows with the same rate value, so you may still need a quantity of post-processing to check for that.

git: undo all working dir changes including new files

git reset --hard origin/{branchName}

It will delete all untracked files.

How to make div background color transparent in CSS

Opacity gives you translucency or transparency. See an example Fiddle here.

-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";       /* IE 8 */
filter: alpha(opacity=50);  /* IE 5-7 */
-moz-opacity: 0.5;          /* Netscape */
-khtml-opacity: 0.5;        /* Safari 1.x */
opacity: 0.5;               /* Good browsers */

Note: these are NOT CSS3 properties

See http://css-tricks.com/snippets/css/cross-browser-opacity/

How to get current available GPUs in tensorflow?

Ensure you have the latest TensorFlow 2.x GPU installed in your GPU supporting machine, Execute the following code in python,

from __future__ import absolute_import, division, print_function, unicode_literals

import tensorflow as tf 

print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))

Will get an output looks like,

2020-02-07 10:45:37.587838: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1006] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2020-02-07 10:45:37.588896: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Adding visible gpu devices: 0, 1, 2, 3, 4, 5, 6, 7 Num GPUs Available: 8

How to select last child element in jQuery?

For 2019 ...

jQuery 3.4.0 is deprecating :first, :last, :eq, :even, :odd, :lt, :gt, and :nth. When we remove Sizzle, we’ll replace it with a small wrapper around querySelectorAll, and it would be almost impossible to reimplement these selectors without a larger selector engine.

We think this trade-off is worth it. Keep in mind we will still support the positional methods, such as .first, .last, and .eq. Anything you can do with positional selectors, you can do with positional methods instead. They perform better anyway.

https://blog.jquery.com/2019/04/10/jquery-3-4-0-released/

So you should be now be using .first(), .last() instead (or no jQuery).

What is the easiest way to initialize a std::vector with hardcoded elements?

There are various ways to hardcode a vector, i will share few ways:

  1. Initializing by pushing values one by one
// Create an empty vector 
    vector<int> vect;  

    vect.push_back(10); 
    vect.push_back(20); 
    vect.push_back(30); 
  1. Initializing like arrays
vector<int> vect{ 10, 20, 30 };
  1. Initializing from an array
    int arr[] = { 10, 20, 30 }; 
    int n = sizeof(arr) / sizeof(arr[0]); 

    vector<int> vect(arr, arr + n); 
  1. Initializing from another vector
    vector<int> vect1{ 10, 20, 30 }; 

    vector<int> vect2(vect1.begin(), vect1.end()); 

Scaling an image to fit on canvas

You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :

var hRatio = canvas.width / img.width    ;
var vRatio = canvas.height / img.height  ;
var ratio  = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);

i also suppose you want to center the image, so the code would be :

function drawImageScaled(img, ctx) {
   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width    ;
   var vRatio =  canvas.height / img.height  ;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,
                      centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
}

you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output

How to select top n rows from a datatable/dataview in ASP.NET

In framework 3.5, dt.Rows.Cast<System.Data.DataRow>().Take(n)

Otherwise the way you mentioned

Javascript (+) sign concatenates instead of giving sum of variables

Use this instead:

var divID = "question-" + (i+1)

It's a fairly common problem and doesn't just happen in JavaScript. The idea is that + can represent both concatenation and addition.

Since the + operator will be handled left-to-right the decisions in your code look like this:

  • "question-" + i: since "question-" is a string, we'll do concatenation, resulting in "question-1"
  • "question-1" + 1: since "queston-1" is a string, we'll do concatenation, resulting in "question-11".

With "question-" + (i+1) it's different:

  • since the (i+1) is in parenthesis, its value must be calculated before the first + can be applied:
    • i is numeric, 1 is numeric, so we'll do addition, resulting in 2
  • "question-" + 2: since "question-" is a string, we'll do concatenation, resulting in "question-2".

Grouping functions (tapply, by, aggregate) and the *apply family

Despite all the great answers here, there are 2 more base functions that deserve to be mentioned, the useful outer function and the obscure eapply function

outer

outer is a very useful function hidden as a more mundane one. If you read the help for outer its description says:

The outer product of the arrays X and Y is the array A with dimension  
c(dim(X), dim(Y)) where element A[c(arrayindex.x, arrayindex.y)] =   
FUN(X[arrayindex.x], Y[arrayindex.y], ...).

which makes it seem like this is only useful for linear algebra type things. However, it can be used much like mapply to apply a function to two vectors of inputs. The difference is that mapply will apply the function to the first two elements and then the second two etc, whereas outer will apply the function to every combination of one element from the first vector and one from the second. For example:

 A<-c(1,3,5,7,9)
 B<-c(0,3,6,9,12)

mapply(FUN=pmax, A, B)

> mapply(FUN=pmax, A, B)
[1]  1  3  6  9 12

outer(A,B, pmax)

 > outer(A,B, pmax)
      [,1] [,2] [,3] [,4] [,5]
 [1,]    1    3    6    9   12
 [2,]    3    3    6    9   12
 [3,]    5    5    6    9   12
 [4,]    7    7    7    9   12
 [5,]    9    9    9    9   12

I have personally used this when I have a vector of values and a vector of conditions and wish to see which values meet which conditions.

eapply

eapply is like lapply except that rather than applying a function to every element in a list, it applies a function to every element in an environment. For example if you want to find a list of user defined functions in the global environment:

A<-c(1,3,5,7,9)
B<-c(0,3,6,9,12)
C<-list(x=1, y=2)
D<-function(x){x+1}

> eapply(.GlobalEnv, is.function)
$A
[1] FALSE

$B
[1] FALSE

$C
[1] FALSE

$D
[1] TRUE 

Frankly I don't use this very much but if you are building a lot of packages or create a lot of environments it may come in handy.

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

Can Windows Containers be hosted on linux?

Solution 1 - Using VirtualBox

As Muhammad Sahputra suggested in this post, it is possible to run Windows OS inside VirtualBox (using VBoxHeadless - without graphical interface) inside Docker container.

Also, a NAT setup inside the VM network configurations can do a port forwarding which gives you the ability to pass-through any traffic that comes to and from the Docker container. This eventually, in a wide perspective, allows you to run any Windows-based service on top of Linux machine.

Maybe this is not a typical use-case of a Docker container, but it definitely an interesting approach to the problem.


Solution 2 - Using Wine

For simple applications and maybe more complicated, you can try to use wine inside a docker container.

This docker hub page may help you to achieve your goal.


I hope that Docker will release a native solution soon, like they did with docker-machine on Windows several years ago.

Android selector & text color

And selector is the answer here as well.

Search for bright_text_dark_focused.xml in the sources, add to your project under res/color directory and then refer from the TextView as

android:textColor="@color/bright_text_dark_focused"

Multidimensional arrays in Swift

Your original logic for creating the matrix is indeed correct, and it even works in Swift 2. The problem is that in the print loop, you have the row and column variables reversed. If you change it to:

for row in 0...2 {
  for column in 0...2 {
    print("column: \(column) row: \(row) value:\(array[column][row])")

  }
}

you will get the correct results. Hope this helps!

How to redirect cin and cout to files?

If your input file is in.txt, you can use freopen to set stdin file as in.txt

freopen("in.txt","r",stdin);

if you want to do the same with your output:

freopen("out.txt","w",stdout);

this will work for std::cin (if using c++), printf, etc...

This will also help you in debugging your code in clion, vscode

How do I embed PHP code in JavaScript?

We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.

However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.

How do I make a JSON object with multiple arrays?

Using below method pass any value which is any array:

Input parameter: url, like Example: "/node/[any int value of array]/anyKeyWhichInArray" Example: "cars/Nissan/[0]/model"

It can be used for any response:

    public String getResponseParameterThroughUrl(Response r, String url) throws JsonProcessingException, IOException {
    String value = "";
    String[] xpathOrder = url.split("/");
    ObjectMapper objectMapper = new ObjectMapper();
    String responseData = r.getBody().asString();       
    JSONObject jsonObject = new JSONObject(responseData);
    byte[] jsonData = jsonObject.toString().getBytes();
    JsonNode rootNode = objectMapper.readTree(jsonData);
    JsonNode node = null;
    for(int i=1;i<xpathOrder.length;i++) {
        if(node==null)
            node = rootNode;
        if(xpathOrder[i].contains("[")){
            xpathOrder[i] = xpathOrder[i].replace("[", "");
            xpathOrder[i] = xpathOrder[i].replace("]", "");
            node = node.get(Integer.parseInt(xpathOrder[i]));
        }
        else
            node = node.path(xpathOrder[i]);
    }
    value = node.asText();
    return value;
}

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

I found some issue about that kind of error

  1. Database username or password not match in the mysql or other other database. Please set application.properties like this

  

# =============================== # = DATA SOURCE # =============================== # Set here configurations for the database connection # Connection url for the database please let me know "[email protected]" spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc # Username and secret spring.datasource.username = root spring.datasource.password = # Keep the connection alive if idle for a long time (needed in production) spring.datasource.testWhileIdle = true spring.datasource.validationQuery = SELECT 1 # =============================== # = JPA / HIBERNATE # =============================== # Use spring.jpa.properties.* for Hibernate native properties (the prefix is # stripped before adding them to the entity manager). # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update): with "update" the database # schema will be automatically updated accordingly to java entities found in # the project spring.jpa.hibernate.ddl-auto = update # Allows Hibernate to generate SQL optimized for a particular DBMS spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Issue no 2.

Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine

How to change the color of a SwitchCompat from AppCompat library

To have greater control of the track color (no API controlled alpha changes), I extended SwitchCompat and style the elements programmatically:

    public class CustomizedSwitch extends SwitchCompat {

    public CustomizedSwitch(Context context) {
        super(context);
        initialize(context);
    }

    public CustomizedSwitch(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize(context);
    }

    public CustomizedSwitch(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context);
    }

    public void initialize(Context context) {
        // DisplayMeasurementConverter is just a utility to convert from dp to px and vice versa
        DisplayMeasurementConverter displayMeasurementConverter = new DisplayMeasurementConverter(context);
        // Sets the width of the switch
        this.setSwitchMinWidth(displayMeasurementConverter.dpToPx((int) getResources().getDimension(R.dimen.tp_toggle_width)));
        // Setting up my colors
        int mediumGreen = ContextCompat.getColor(context, R.color.medium_green);
        int mediumGrey = ContextCompat.getColor(context, R.color.medium_grey);
        int alphaMediumGreen = Color.argb(127, Color.red(mediumGreen), Color.green(mediumGreen), Color.blue(mediumGreen));
        int alphaMediumGrey = Color.argb(127, Color.red(mediumGrey), Color.green(mediumGrey), Color.blue(mediumGrey));
        // Sets the tints for the thumb in different states
        DrawableCompat.setTintList(this.getThumbDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        mediumGreen,
                        ContextCompat.getColor(getContext(), R.color.light_grey)
                }));
        // Sets the tints for the track in different states
        DrawableCompat.setTintList(this.getTrackDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        alphaMediumGreen,
                        alphaMediumGrey
                }));
    }
}

Whenever I want to use the CustomizedSwitch, I just add one to my xml file.

How to force garbage collection in Java?

If you need to force garbage collection, perhaps you should consider how you're managing resources. Are you creating large objects that persist in memory? Are you creating large objects (e.g., graphics classes) that have a Disposable interface and not calling dispose() when done with it? Are you declaring something at a class level that you only need within a single method?

C++ Dynamic Shared Library on Linux

Basically, you should include the class' header file in the code where you want to use the class in the shared library. Then, when you link, use the '-l' flag to link your code with the shared library. Of course, this requires the .so to be where the OS can find it. See 3.5. Installing and Using a Shared Library

Using dlsym is for when you don't know at compile time which library you want to use. That doesn't sound like it's the case here. Maybe the confusion is that Windows calls the dynamically loaded libraries whether you do the linking at compile or run-time (with analogous methods)? If so, then you can think of dlsym as the equivalent of LoadLibrary.

If you really do need to dynamically load the libraries (i.e., they're plug-ins), then this FAQ should help.

LINQ Inner-Join vs Left-Join

I the following error message when faced this same problem:

The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'.

Solved when I used the same property name, it worked.

(...)

join enderecoST in db.PessoaEnderecos on 
    new 
      {  
         CD_PESSOA          = nf.CD_PESSOA_ST, 
         CD_ENDERECO_PESSOA = nf.CD_ENDERECO_PESSOA_ST 
      } equals 
    new 
    { 
         enderecoST.CD_PESSOA, 
         enderecoST.CD_ENDERECO_PESSOA 
    } into eST

(...)

How to read html from a url in python 3

For python 2

import urllib
some_url = 'https://docs.python.org/2/library/urllib.html'
filehandle = urllib.urlopen(some_url)
print filehandle.read()

For homebrew mysql installs, where's my.cnf?

Since mysql --help shows a list of files, I find it useful to pipe the result to ls to see which of them exist:

$ mysql --help | grep /my.cnf | xargs ls
ls: /etc/my.cnf: No such file or directory
ls: /etc/mysql/my.cnf: No such file or directory
ls: ~/.my.cnf: No such file or directory
/usr/local/etc/my.cnf

For my (Homebrew installed) MySQL 5.7, it seems the files is on /usr/local/etc/my.cnf.

show validation error messages on submit in angularjs

http://jsfiddle.net/LRD5x/30/ A simple solution.

HTML

<form ng-submit="sendForm($event)" ng-class={submitted:submitted}>

JS

$scope.sendForm = function($event) {
  $event.preventDefault()
  $scope.submitted = true
};

CSS

.submitted input.ng-invalid:not(:focus) {
    background-color: #FA787E;
}

input.ng-invalid ~ .alert{
    display:none;
}
.submitted input.ng-invalid ~ .alert{
    display:block;
}

React-Native: Module AppRegistry is not a registered callable module

In my case, my index.js just points to another js instead of my Launcher js mistakenly, which does not contain AppRegistry.registerComponent().

So, make sure the file yourindex.jspoint to register the class.

How do I change the data type for a column in MySQL?

https://dev.mysql.com/doc/refman/8.0/en/alter-table.html

You can also set a default value for the column just add the DEFAULT keyword followed by the value.

ALTER TABLE [table_name] MODIFY [column_name] [NEW DATA TYPE] DEFAULT [VALUE];

This is also working for MariaDB (tested version 10.2)

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are exactly the same. When you use it be consistent. Use one of them in your database

CSS class for pointer cursor

Bootstrap 3 - Just adding the "btn" Class worked for me.

Without pointer cursor:

<span class="label label-success">text</span>

With pointer cursor:

<span class="label label-success btn">text</span>

Get a CSS value with JavaScript

The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.

Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.

The two ways have differences, for example, the IE element.currentStyle property expect that you access the CSS property names composed of two or more words in camelCase (e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc). ......

function getStyle(el, styleProp) {
    var value, defaultView = (el.ownerDocument || document).defaultView;
    // W3C standard way:
    if (defaultView && defaultView.getComputedStyle) {
        // sanitize property name to css notation
        // (hyphen separated words eg. font-Size)
        styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
        return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
    } else if (el.currentStyle) { // IE
        // sanitize property name to camelCase
        styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
            return letter.toUpperCase();
        });
        value = el.currentStyle[styleProp];
        // convert other units to pixels on IE
        if (/^\d+(em|pt|%|ex)?$/i.test(value)) { 
            return (function(value) {
                var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
                el.runtimeStyle.left = el.currentStyle.left;
                el.style.left = value || 0;
                value = el.style.pixelLeft + "px";
                el.style.left = oldLeft;
                el.runtimeStyle.left = oldRsLeft;
                return value;
            })(value);
        }
        return value;
    }
}

Main reference stackoverflow

SQLDataReader Row Count

SQLDataReaders are forward-only. You're essentially doing this:

count++;  // initially 1
.DataBind(); //consuming all the records

//next iteration on
.Read()
//we've now come to end of resultset, thanks to the DataBind()
//count is still 1 

You could do this instead:

if (reader.HasRows)
{
    rep.DataSource = reader;
    rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.

How can I pass a class member function as a callback?

What argument does Init take? What is the new error message?

Method pointers in C++ are a bit difficult to use. Besides the method pointer itself, you also need to provide an instance pointer (in your case this). Maybe Init expects it as a separate argument?

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

After half a day of fiddling with this, found out that PDO had a bug where...

--

//This would run as expected:
$pdo->exec("valid-stmt1; valid-stmt2;");

--

//This would error out, as expected:
$pdo->exec("non-sense; valid-stmt1;");

--

//Here is the bug:
$pdo->exec("valid-stmt1; non-sense; valid-stmt3;");

It would execute the "valid-stmt1;", stop on "non-sense;" and never throw an error. Will not run the "valid-stmt3;", return true and lie that everything ran good.

I would expect it to error out on the "non-sense;" but it doesn't.

Here is where I found this info: Invalid PDO query does not return an error

Here is the bug: https://bugs.php.net/bug.php?id=61613


So, I tried doing this with mysqli and haven't really found any solid answer on how it works so I thought I's just leave it here for those who want to use it..

try{
    // db connection
    $mysqli = new mysqli("host", "user" , "password", "database");
    if($mysqli->connect_errno){
        throw new Exception("Connection Failed: [".$mysqli->connect_errno. "] : ".$mysqli->connect_error );
        exit();
    }

    // read file.
    // This file has multiple sql statements.
    $file_sql = file_get_contents("filename.sql");

    if($file_sql == "null" || empty($file_sql) || strlen($file_sql) <= 0){
        throw new Exception("File is empty. I wont run it..");
    }

    //run the sql file contents through the mysqli's multi_query function.
    // here is where it gets complicated...
    // if the first query has errors, here is where you get it.
    $sqlFileResult = $mysqli->multi_query($file_sql);
    // this returns false only if there are errros on first sql statement, it doesn't care about the rest of the sql statements.

    $sqlCount = 1;
    if( $sqlFileResult == false ){
        throw new Exception("File: '".$fullpath."' , Query#[".$sqlCount."], [".$mysqli->errno."]: '".$mysqli->error."' }");
    }

    // so handle the errors on the subsequent statements like this.
    // while I have more results. This will start from the second sql statement. The first statement errors are thrown above on the $mysqli->multi_query("SQL"); line
    while($mysqli->more_results()){
        $sqlCount++;
        // load the next result set into mysqli's active buffer. if this fails the $mysqli->error, $mysqli->errno will have appropriate error info.
        if($mysqli->next_result() == false){
            throw new Exception("File: '".$fullpath."' , Query#[".$sqlCount."], Error No: [".$mysqli->errno."]: '".$mysqli->error."' }");
        }
    }
}
catch(Exception $e){
    echo $e->getMessage(). " <pre>".$e->getTraceAsString()."</pre>";
}

Printing leading 0's in C

The correct solution is to store the ZIP Code in the database as a STRING. Despite the fact that it may look like a number, it isn't. It's a code, where each part has meaning.

A number is a thing you do arithmetic on. A ZIP Code is not that.

C++ - Hold the console window open?

A more appropriate method is to use std::cin.ignore:

#include <iostream>

void Pause()
{
   std::cout << "Press Enter to continue...";
   std::cout.flush();
   std::cin.ignore(10000, '\n');
   return;
}

How to create a cron job using Bash automatically without the interactive editor?

Chances are you are automating this, and you don't want a single job added twice. In that case use:

__cron="1 2 3 4 5 /root/bin/backup.sh"
cat <(crontab -l) |grep -v "${__cron}" <(echo "${__cron}")

This only works if you're using BASH. I'm not aware of the correct DASH (sh) syntax.

Update: This doesn't work if the user doesn't have a crontab yet. A more reliable way would be:

(crontab -l ; echo "1 2 3 4 5 /root/bin/backup.sh") | sort - | uniq - | crontab - 

Alternatively, if your distro supports it, you could also use a separate file:

echo "1 2 3 4 5 /root/bin/backup.sh" |sudo tee /etc/crond.d/backup

Found those in another SO question.

Calling dynamic function with dynamic number of parameters

Couldn't you just pass the arguments array along?

function mainfunc (func){
    // remove the first argument containing the function name
    arguments.shift();
    window[func].apply(null, arguments);
}

function calledfunc1(args){
    // Do stuff here
}

function calledfunc2(args){
    // Do stuff here
}

mainfunc('calledfunc1','hello','bye');
mainfunc('calledfunc2','hello','bye','goodbye');

Why would we call cin.clear() and cin.ignore() after reading input?

You enter the

if (!(cin >> input_var))

statement if an error occurs when taking the input from cin. If an error occurs then an error flag is set and future attempts to get input will fail. That's why you need

cin.clear();

to get rid of the error flag. Also, the input which failed will be sitting in what I assume is some sort of buffer. When you try to get input again, it will read the same input in the buffer and it will fail again. That's why you need

cin.ignore(10000,'\n');

It takes out 10000 characters from the buffer but stops if it encounters a newline (\n). The 10000 is just a generic large value.

How can I update NodeJS and NPM to the next versions?

you should see this blog nodejs install with package-manager

Before you performance this command. you show run sudo apt-get update, make sure result is Reading package lists... Done, no ERROR

Step by Step (Debian):

sudo apt-get update

install 6_x

curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs

install 7_x

curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
sudo apt-get install -y nodejs

PHP write file from input to txt

If you use file_put_contents you don't need to do a fopen -> fwrite -> fclose, the file_put_contents does all that for you. You should also check if the webserver has write rights in the directory where you are trying to write your "data.txt" file.

Depending on your PHP version (if it's old) you might not have the file_get/put_contents functions. Check your webserver log to see if any error appeared when you executed the script.

Sort Dictionary by keys

For Swift 3, the following sort returnes sorted dictionary by keys:

let unsortedDictionary = ["4": "four", "2": "two", "1": "one", "3": "three"]

let sortedDictionary = unsortedDictionary.sorted(by: { $0.0.key < $0.1.key })

print(sortedDictionary)
// ["1": "one", "2": "two", "3": "three", "4": "four"]

Bootstrap datetimepicker is not a function

The problem is that you have not included bootstrap.min.css. Also, the sequence of imports could be causing issue. Please try rearranging your resources as following:

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>                       
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

DEMO

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

The code marked as the solution did not work for me. This was my solution.

/*
 * http://www.java2s.com/Code/Java/Security/EncryptingaStringwithDES.htm
 * https://stackoverflow.com/questions/23561104/how-to-encrypt-and-decrypt-string-with-my-passphrase-in-java-pc-not-mobile-plat
 */
package encryptiondemo;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


/**
 *
 * @author zchumager
 */
public class EncryptionDemo {

  Cipher ecipher;
  Cipher dcipher;

  EncryptionDemo(SecretKey key) throws Exception {
    ecipher = Cipher.getInstance("AES");
    dcipher = Cipher.getInstance("AES");
    ecipher.init(Cipher.ENCRYPT_MODE, key);
    dcipher.init(Cipher.DECRYPT_MODE, key);
  }

  public String encrypt(String str) throws Exception {
    // Encode the string into bytes using utf-8
    byte[] utf8 = str.getBytes("UTF8");

    // Encrypt
    byte[] enc = ecipher.doFinal(utf8);

    // Encode bytes to base64 to get a string
    return new sun.misc.BASE64Encoder().encode(enc);
  }

  public String decrypt(String str) throws Exception {
    // Decode base64 to get bytes
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

    byte[] utf8 = dcipher.doFinal(dec);

    // Decode using utf-8
    return new String(utf8, "UTF8");
  }


    public static void main(String args []) throws Exception
    {

        String data = "Don't tell anybody!";
        String k = "Bar12345Bar12345";

        //SecretKey key = KeyGenerator.getInstance("AES").generateKey();
        SecretKey key = new SecretKeySpec(k.getBytes(), "AES");
        EncryptionDemo encrypter = new EncryptionDemo(key);

        System.out.println("Original String: " + data);

        String encrypted = encrypter.encrypt(data);

        System.out.println("Encrypted String: " + encrypted);

        String decrypted = encrypter.decrypt(encrypted);

        System.out.println("Decrypted String: " + decrypted);
    }
}

Add Marker function with Google Maps API

THis is other method
You can also use setCenter method with add new marker

check below code

$('#my_map').gmap3({
      action: 'setCenter',
      map:{
         options:{
          zoom: 10
         }
      },
      marker:{
         values:
          [
            {latLng:[position.coords.latitude, position.coords.longitude], data:"Netherlands !"}
          ]
      }
   });

What is the most efficient string concatenation method in python?

You may be interested in this: An optimization anecdote by Guido. Although it is worth remembering also that this is an old article and it predates the existence of things like ''.join (although I guess string.joinfields is more-or-less the same)

On the strength of that, the array module may be fastest if you can shoehorn your problem into it. But ''.join is probably fast enough and has the benefit of being idiomatic and thus easier for other python programmers to understand.

Finally, the golden rule of optimization: don't optimize unless you know you need to, and measure rather than guessing.

You can measure different methods using the timeit module. That can tell you which is fastest, instead of random strangers on the internet making guesses.

Can JavaScript connect with MySQL?

If you want to connect to a MySQL database using JavaScript, you can use Node.js and a library called mysql. You can create queries, and get results as an array of registers. If you want to try it, you can use my project generator to create a backend and choose MySQL as the database to connect. Then, just expose your new REST API or GraphQL endpoint to your front and start working with your MySQL database.


OLD ANSWER LEFT BY NOSTALGIA

THEN

As I understand the question and correct me if I am wrong, it refers to the classic server model with JavaScript only on the client-side. In this classic model, with LAMP servers (Linux, Apache, MySQL, PHP) the language in contact with the database was PHP, so to request data to the database you need to write PHP scripts and echo the returning data to the client. Basically, the distribution of the languages according to physical machines was:

  1. Server Side: PHP and MySQL.
  2. Client Side: HTML/CSS and JavaScript.

This answered to an MVC model (Model, View, Controller) where we had the following functionality:

  1. MODEL: The model is what deals with the data, in this case, the PHP scripts that manage variables or that access data stored, in this case in our MySQL database and send it as JSON data to the client.
  2. VIEW: The view is what we see and it should be completely independent of the model. It just needs to show the data contained in the model, but it shouldn't have relevant data on it. In this case, the view uses HTML and CSS. HTML to create the basic structure of the view, and CSS to give the shape to this basic structure.
  3. CONTROLLER: The controller is the interface between our model and our view. In this case, the language used is JavaScript and it takes the data the model send us as a JSON package and put it inside the containers that offer the HTML structure. The way the controller interacts with the model is by using AJAX. We use GET and POST methods to call PHP scripts on the server-side and to catch the returned data from the server.

For the controller, we have really interesting tools like jQuery, as "low-level" library to control the HTML structure (DOM), and then new, more high-level ones as Knockout.js that allow us to create observers that connect different DOM elements updating them when events occur. There is also Angular.js by Google that works in a similar way, but seems to be a complete environment. To help you to choose among them, here you have two excellent analyses of the two tools: Knockout vs. Angular.js and Knockout.js vs. Angular.js. I am still reading. Hope they help you.

NOW

In modern servers based in Node.js, we use JavaScript for everything. Node.js is a JavaScript environment with many libraries that work with Google V8, Chrome JavaScript engine. The way we work with these new servers is:

  1. Node.js and Express: The mainframe where the server is built. We can create a server with a few lines of code or even use libraries like Express to make even easier to create the server. With Node.js and Express, we will manage the petitions to the server from the clients and will answer them with the appropriate pages.
  2. Jade: To create the pages we use a templating language, in this case, Jade, that allow us to write web pages as we were writing HTML but with differences (it take a little time but is easy to learn). Then, in the code of the server to answer the client's petitions, we just need to render the Jade code into a "real" HTML code.
  3. Stylus: Similar to Jade but for CSS. In this case, we use a middleware function to convert the stylus file into a real CSS file for our page.

Then we have a lot of packages we can install using the NPM (Node.js package manager) and use them directly in our Node.js server just requiring it (for those of you that want to learn Node.js, try this beginner tutorial for an overview). And among these packages, you have some of them to access databases. Using this you can use JavaScript on the server-side to access My SQL databases.

But the best you can do if you are going to work with Node.js is to use the new NoSQL databases like MongoDB, based on JSON files. Instead of storing tables like MySQL, it stores the data in JSON structures, so you can put different data inside each structure like long numeric vectors instead of creating huge tables for the size of the biggest one.

I hope this brief explanation becomes useful to you, and if you want to learn more about this, here you have some resources you can use:

  • Egghead: This site is full of great short tutorials about JavaScript and its environment. It worths a try. And the make discounts from time to time.
  • Code School: With a free and very interesting course about Chrome Developer tools to help you to test the client-side.
  • Codecademy: With free courses about HTML, CSS, JavaScript, jQuery, and PHP that you can follow with online examples.
  • 10gen Education: With everything you need to know about MongoDB in tutorials for different languages.
  • W3Schools: This one has tutorials about all this and you can use it as a reference place because it has a lot of shortcode examples really useful.
  • Udacity: A place with free video courses about different subjects with a few interesting ones about web development and my preferred, an amazing WebGL course for 3D graphics with JavaScript.

I hope it helps you to start.

Have fun!

Matrix Transpose in Python

#generate matrix
matrix=[]
m=input('enter number of rows, m = ')
n=input('enter number of columns, n = ')
for i in range(m):
    matrix.append([])
    for j in range(n):
        elem=input('enter element: ')
        matrix[i].append(elem)

#print matrix
for i in range(m):
    for j in range(n):
        print matrix[i][j],
    print '\n'

#generate transpose
transpose=[]
for j in range(n):
    transpose.append([])
    for i in range (m):
        ent=matrix[i][j]
        transpose[j].append(ent)

#print transpose
for i in range (n):
    for j in range (m):
        print transpose[i][j],
    print '\n'

Delete terminal history in Linux

You can clear your bash history like this:

history -cw

Open multiple Projects/Folders in Visual Studio Code

You can open any folder, so if your projects are in the same tree, just open the folder beneath them.

Otherwise you can open 2 instances of Code as another option

Why has it failed to load main-class manifest attribute from a JAR file?

I was getting the same error when i ran:
jar cvfm test.jar Test.class Manifest.txt

What resolved it was this:
jar cvfm test.jar Manifest.txt Test.class

My manifest has the entry point as given in oracle docs (make sure there is a new line character at the end of the file):
Main-Class: Test

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use the IP instead:

DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

For more possibilities, see this link.

To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):

mysqladmin -u root password 'mynewpassword'

Documentation, and Lost root access in MySQL.

How to Enable ActiveX in Chrome?

http://wiki.answers.com/Q/Does_Google_Chrome_support_ActiveX

Google Chrome comes with an ActiveX shim, as part of its default plugin array. So Google Chrome features at least partial support for ActiveX controls (as do many non-Internet Explorer browsers). I can't find information as to whether or not this includes support for ActiveX security certificates or the like, nor if/where such plugins can be controlled, within the browser.

..... Note that to enable the plug-in you must run Chrome with the following switch " --allow-all-activex" So in shortcut that is used to start up Chrome, add this after "Chrome.exe"

QtCreator: No valid kits found

For QT 5.* if you face error at Kits, like No Valid Kits Found, go to Options->Build&Run-> (Kits tab) then you see a Manual category which should list Desktop as the default.

Just go to your OS Terminal and write sudo apt-get install qt5-default, go back to QT Creator and Start your New Project, and there you see the kit option Desktop included in the list.

JQuery confirm dialog

Try this one

$('<div></div>').appendTo('body')
  .html('<div><h6>Yes or No?</h6></div>')
  .dialog({
      modal: true, title: 'message', zIndex: 10000, autoOpen: true,
      width: 'auto', resizable: false,
      buttons: {
          Yes: function () {
              doFunctionForYes();
              $(this).dialog("close");
          },
          No: function () {
              doFunctionForNo();
              $(this).dialog("close");
          }
      },
      close: function (event, ui) {
          $(this).remove();
      }
});

Fiddle

how to place last div into right top corner of parent div? (css)

_x000D_
_x000D_
.block1 {_x000D_
    color: red;_x000D_
    width: 100px;_x000D_
    border: 1px solid green;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.block2 {_x000D_
    color: blue;_x000D_
    width: 70px;_x000D_
    border: 2px solid black;_x000D_
    position: absolute;_x000D_
    top: 0px;_x000D_
    right: 0px;_x000D_
}
_x000D_
<div class='block1'>_x000D_
  <p>text</p>_x000D_
  <p>text2</p>_x000D_
  <div class='block2'>block2</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Should do it. Assuming you don't need it to flow.

Remove all special characters except space from a string using JavaScript

dot (.) may not be considered special. I have added an OR condition to Mozfet's & Seagull's answer:

function isNumber (text) {
      reg = new RegExp('[0-9]+$');
      if(text) {
        return reg.test(text);
      }
      return false;
    }

function removeSpecial (text) {
  if(text) {
    var lower = text.toLowerCase();
    var upper = text.toUpperCase();
    var result = "";
    for(var i=0; i<lower.length; ++i) {
      if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '') || (lower[i].trim() === '.')) {
        result += text[i];
      }
    }
    return result;
  }
  return '';
}

Why does sudo change the PATH?

This is an annoying function a feature of sudo on many distributions.

To work around this "problem" on ubuntu I do the following in my ~/.bashrc

alias sudo='sudo env PATH=$PATH'

Note the above will work for commands that don't reset the $PATH themselves. However `su' resets it's $PATH so you must use -p to tell it not to. I.E.:

sudo su -p

Use of *args and **kwargs

One place where the use of *args and **kwargs is quite useful is for subclassing.

class Foo(object):
    def __init__(self, value1, value2):
        # do something with the values
        print value1, value2

class MyFoo(Foo):
    def __init__(self, *args, **kwargs):
        # do something else, don't care about the args
        print 'myfoo'
        super(MyFoo, self).__init__(*args, **kwargs)

This way you can extend the behaviour of the Foo class, without having to know too much about Foo. This can be quite convenient if you are programming to an API which might change. MyFoo just passes all arguments to the Foo class.

What does '&' do in a C++ declaration?

#include<iostream>
using namespace std;
int add(int &number);

int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(&number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}

int add(int &p)
{
            *p=*p+100;
            return(*p);
}

This is invalid code on several counts. Running it through g++ gives:

crap.cpp: In function ‘int main()’:
crap.cpp:11: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int*’
crap.cpp:3: error: in passing argument 1 of ‘int add(int&)’
crap.cpp: In function ‘int add(int&)’:
crap.cpp:19: error: invalid type argument of ‘unary *’
crap.cpp:19: error: invalid type argument of ‘unary *’
crap.cpp:20: error: invalid type argument of ‘unary *’

A valid version of the code reads:

#include<iostream>
using namespace std;
int add(int &number);

int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}

int add(int &p)
{
            p=p+100;
            return p;
}

What is happening here is that you are passing a variable "as is" to your function. This is roughly equivalent to:

int add(int *p)
{
      *p=*p+100;
      return *p;
}

However, passing a reference to a function ensures that you cannot do things like pointer arithmetic with the reference. For example:

int add(int &p)
{
            *p=*p+100;
            return p;
}

is invalid.

If you must use a pointer to a reference, that has to be done explicitly:

int add(int &p)
{
                    int* i = &p;
            i=i+100L;
            return *i;
}

Which on a test run gives (as expected) junk output:

The value of the variable number before calling the function : 5
The value of the variable number after the function is returned : 5
The value of result : 1399090792

How to replace part of string by position?

I was looking for a solution with following requirements:

  1. use only a single, one-line expression
  2. use only system builtin methods (no custom implemented utility)

Solution 1

The solution that best suits me is this:

// replace `oldString[i]` with `c`
string newString = new StringBuilder(oldString).Replace(oldString[i], c, i, 1).ToString();

This uses StringBuilder.Replace(oldChar, newChar, position, count)

Solution 2

The other solution that satisfies my requirements is to use Substring with concatenation:

string newString = oldStr.Substring(0, i) + c + oldString.Substring(i+1, oldString.Length);

This is OK too. I guess it's not as efficient as the first one performance wise (due to unnecessary string concatenation). But premature optimization is the root of all evil.

So pick the one that you like the most :)

How to extract the nth word and count word occurrences in a MySQL string?

The field's value is:

 "- DE-HEB 20% - DTopTen 1.2%"
SELECT ....
SUBSTRING_INDEX(SUBSTRING_INDEX(DesctosAplicados, 'DE-HEB ',  -1), '-', 1) DE-HEB ,
SUBSTRING_INDEX(SUBSTRING_INDEX(DesctosAplicados, 'DTopTen ',  -1), '-', 1) DTopTen ,

FROM TABLA 

Result is:

  DE-HEB       DTopTEn
    20%          1.2%

Reading a .txt file using Scanner class in Java

here are some working and tested methods;

using Scanner

package io;

import java.io.File;
import java.util.Scanner;

public class ReadFromFileUsingScanner {
    public static void main(String[] args) throws Exception {
        File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
        Scanner sc=new Scanner(file);
        while(sc.hasNextLine()){
            System.out.println(sc.nextLine());
        }
    }
}


Here's another way to read entire file (without loop) using Scanner class

package io;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadingEntireFileWithoutLoop {
    public static void main(String[] args) throws FileNotFoundException {
        File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
        Scanner sc=new Scanner(file);
        sc.useDelimiter("\\Z");
        System.out.println(sc.next());
    }
}

using BufferedReader

 package io;
import java.io.*;
public class ReadFromFile2 {
    public static void main(String[] args)throws Exception {
        File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
        BufferedReader br=new BufferedReader(new FileReader(file));
        String st;
        while((st=br.readLine())!=null){
            System.out.println(st);
        }
    }
}

using FileReader

package io;
import java.io.*;
public class ReadingFromFile {
    public static void main(String[] args) throws Exception {
        FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
        int i;
        while((i=fr.read())!=-1){
            System.out.print((char) i);
        }
    }
}

Bootstrap: change background color

You could hard code it.

<div class="col-md-6" style="background-color:blue;">
</div>

<div class="col-md-6" style="background-color:white;">
</div>

How to remove all duplicate items from a list

In this way one can delete a particular item which is present multiple times in a list : Try deleting all 5

list1=[1,2,3,4,5,6,5,3,5,7,11,5,9,8,121,98,67,34,5,21]
print list1
n=input("item to be deleted : " )
for i in list1:
    if n in list1:
        list1.remove(n)
print list1

Handling NULL values in Hive

To check for the NULL data for column1 and consider your datatype of it is String, you could use below command :

select * from tbl_name where column1 is null or column1 <> '';

Highlighting Text Color using Html.fromHtml() in Android?

textview.setText(Html.fromHtml("<font color='rgb'>"+text contain+"</font>"));

It will give the color exactly what you have made in html editor , just set the textview and concat it with the textview value. Android does not support span color, change it to font color in editor and you are all set to go.

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
    //Your stuff
});

Working with TIFFs (import, export) in Python using numpy

You can also use pytiff of which I'm the author.

    import pytiff

    with pytiff.Tiff("filename.tif") as handle:
        part = handle[100:200, 200:400]

    # multipage tif
    with pytiff.Tiff("multipage.tif") as handle:
        for page in handle:
            part = page[100:200, 200:400]

It's a fairly small module and may not have as many features as other modules, but it supports tiled tiffs and bigtiff, so you can read parts of large images.

How to add a border to a widget in Flutter?

Best way is using BoxDecoration()

Advantage

  • You can set border of widget
  • You can set border Color or Width
  • You can set Rounded corner of border
  • You can add Shadow of widget

Disadvantage

  • BoxDecoration only use with Container widget so you want to wrap your widget in Container()

Example

    Container(
      margin: EdgeInsets.all(10),
      padding: EdgeInsets.all(10),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.orange,
        border: Border.all(
            color: Colors.pink[800],// set border color
            width: 3.0),   // set border width
        borderRadius: BorderRadius.all(
            Radius.circular(10.0)), // set rounded corner radius
        boxShadow: [BoxShadow(blurRadius: 10,color: Colors.black,offset: Offset(1,3))]// make rounded corner of border
      ),
      child: Text("My demo styling"),
    )

enter image description here

How to remove indentation from an unordered list item?

display:table-row; will also get rid of the indentation but will remove the bullets.

Viewing unpushed Git commits

If you want to see all commits on all branches that aren't pushed yet, you might be looking for something like this:

git log --branches --not --remotes

And if you only want to see the most recent commit on each branch, and the branch names, this:

git log --branches --not --remotes --simplify-by-decoration --decorate --oneline

Frequency table for a single variable

Maybe .value_counts()?

>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0       1
1       2
2       2
3       3
4       3
5       3
6    fred
7     1.8
8     1.8
>>> counts = my_series.value_counts()
>>> counts
3       3
2       2
1.8     2
fred    1
1       1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}

New line character in VB.Net?

In this case, I can use vbNewLine, vbCrLf or "\r\n".

Brew doctor says: "Warning: /usr/local/include isn't writable."

sudo mkdir -p /usr/local/include /usr/local/lib /usr/local/sbin

sudo chown -R $(whoami) /usr/local/include /usr/local/lib /usr/local/sbin

This will create all required directories and give it the correct ownership.

After running these commands check with: brew doctor

This works for Mojave.

The most efficient way to implement an integer based power function pow(int, int)

Here is the method in Java

private int ipow(int base, int exp)
{
    int result = 1;
    while (exp != 0)
    {
        if ((exp & 1) == 1)
            result *= base;
        exp >>= 1;
        base *= base;
    }

    return result;
}

Properties file with a list as the value for an individual key

Try writing the properties as a comma separated list, then split the value after the properties file is loaded. For example

a=one,two,three
b=nine,ten,fourteen

You can also use org.apache.commons.configuration and change the value delimiter using the AbstractConfiguration.setListDelimiter(char) method if you're using comma in your values.

TypeError: list indices must be integers or slices, not str

I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.

Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.

Is there any way to set environment variables in Visual Studio Code?

My response is fairly late. I faced the same problem. I am on Windows 10. This is what I did:

  • Open a new Command prompt (CMD.EXE)
  • Set the environment variables . set myvar1=myvalue1
  • Launch VS Code from that Command prompt by typing code and then press ENTER
  • VS code was launched and it inherited all the custom variables that I had set in the parent CMD window

Optionally, you can also use the Control Panel -> System properties window to set the variables on a more permanent basis

Hope this helps.

Android - implementing startForeground for a service?

Solution for Oreo 8.1

I've encountered some problems such as RemoteServiceException because of invalid channel id with most recent versions of Android. This is how i solved it:

Activity:

override fun onCreate(savedInstanceState: Bundle?) {
    val intent = Intent(this, BackgroundService::class.java)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(intent)
    } else {
        startService(intent)
    }
}

BackgroundService:

override fun onCreate() {
    super.onCreate()
    startForeground()
}

private fun startForeground() {

    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val channelId =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                createNotificationChannel()
            } else {
                // If earlier version channel ID is not used
                // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
                ""
            }

    val notificationBuilder = NotificationCompat.Builder(this, channelId )
    val notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(PRIORITY_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build()
    startForeground(101, notification)
}


@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(): String{
    val channelId = "my_service"
    val channelName = "My Background Service"
    val chan = NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_HIGH)
    chan.lightColor = Color.BLUE
    chan.importance = NotificationManager.IMPORTANCE_NONE
    chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    service.createNotificationChannel(chan)
    return channelId
}

JAVA EQUIVALENT

public class YourService extends Service {

    // Constants
    private static final int ID_SERVICE = 101;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // do stuff like register for BroadcastReceiver, etc.

        // Create the Foreground Service
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(PRIORITY_MIN)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .build();

        startForeground(ID_SERVICE, notification);
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(NotificationManager notificationManager){
        String channelId = "my_service_channelid";
        String channelName = "My Foreground Service";
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        // omitted the LED color
        channel.setImportance(NotificationManager.IMPORTANCE_NONE);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        notificationManager.createNotificationChannel(channel);
        return channelId;
    }
}

How to convert list of key-value tuples into dictionary?

>>> dict([('A', 1), ('B', 2), ('C', 3)])
{'A': 1, 'C': 3, 'B': 2}

How to change text color and console color in code::blocks?

Functions like textcolor worked in old compilers like turbo C and Dev C. In today's compilers these functions would not work. I am going to give two function SetColor and ChangeConsoleToColors. You copy paste these functions code in your program and do the following steps.The code I am giving will not work in some compilers.

The code of SetColor is -

 void SetColor(int ForgC)
 {
     WORD wColor;

      HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
      CONSOLE_SCREEN_BUFFER_INFO csbi;

                       //We use csbi for the wAttributes word.
     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
     {
                 //Mask out all but the background attribute, and add in the forgournd     color
          wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
          SetConsoleTextAttribute(hStdOut, wColor);
     }
     return;
 }

To use this function you need to call it from your program. For example I am taking your sample program -

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <dos.h>
#include <dir.h>

int main(void)
{
  SetColor(4);
  printf("\n \n \t This text is written in Red Color \n ");
  getch();
  return 0;
}

void SetColor(int ForgC)
 {
 WORD wColor;

  HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  CONSOLE_SCREEN_BUFFER_INFO csbi;

                       //We use csbi for the wAttributes word.
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                 //Mask out all but the background attribute, and add in the forgournd color
      wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
      SetConsoleTextAttribute(hStdOut, wColor);
 }
 return;
}

When you run the program you will get the text color in RED. Now I am going to give you the code of each color -

Name         | Value
             |
Black        |   0
Blue         |   1
Green        |   2
Cyan         |   3
Red          |   4
Magenta      |   5
Brown        |   6
Light Gray   |   7
Dark Gray    |   8
Light Blue   |   9
Light Green  |   10
Light Cyan   |   11
Light Red    |   12
Light Magenta|   13
Yellow       |   14
White        |   15

Now I am going to give the code of ChangeConsoleToColors. The code is -

void ClearConsoleToColors(int ForgC, int BackC)
 {
 WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
               //Get the handle to the current output buffer...
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
                     //This is used to reset the carat/cursor to the top left.
 COORD coord = {0, 0};
                  //A return value... indicating how many chars were written
                    //   not used but we need to capture this since it will be
                      //   written anyway (passing NULL causes an access violation).
  DWORD count;

                               //This is a structure containing all of the console info
                      // it is used here to find the size of the console.
 CONSOLE_SCREEN_BUFFER_INFO csbi;
                 //Here we will set the current color
 SetConsoleTextAttribute(hStdOut, wColor);
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                          //This fills the buffer with a given character (in this case 32=space).
      FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

      FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
                          //This will set our cursor position for the next print statement.
      SetConsoleCursorPosition(hStdOut, coord);
 }
 return;
}

In this function you pass two numbers. If you want normal colors just put the first number as zero and the second number as the color. My example is -

#include <windows.h>          //header file for windows
#include <stdio.h>

void ClearConsoleToColors(int ForgC, int BackC);

int main()
{
ClearConsoleToColors(0,15);
Sleep(1000);
return 0;
}
void ClearConsoleToColors(int ForgC, int BackC)
{
 WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
               //Get the handle to the current output buffer...
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
                     //This is used to reset the carat/cursor to the top left.
 COORD coord = {0, 0};
                  //A return value... indicating how many chars were written
                    //   not used but we need to capture this since it will be
                      //   written anyway (passing NULL causes an access violation).
 DWORD count;

                               //This is a structure containing all of the console info
                      // it is used here to find the size of the console.
 CONSOLE_SCREEN_BUFFER_INFO csbi;
                 //Here we will set the current color
 SetConsoleTextAttribute(hStdOut, wColor);
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                          //This fills the buffer with a given character (in this case 32=space).
      FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

      FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
                          //This will set our cursor position for the next print statement.
      SetConsoleCursorPosition(hStdOut, coord);
 }
 return;
} 

In this case I have put the first number as zero and the second number as 15 so the console color will be white as the code for white is 15. This is working for me in code::blocks. Hope it works for you too.

Use grep --exclude/--include syntax to not grep through certain files

Please take a look at ack, which is designed for exactly these situations. Your example of

grep -ircl --exclude=*.{png,jpg} "foo=" *

is done with ack as

ack -icl "foo="

because ack never looks in binary files by default, and -r is on by default. And if you want only CPP and H files, then just do

ack -icl --cpp "foo="

Angular window resize event

Based on the solution of @cgatian I would suggest the following simplification:

import { EventManager } from '@angular/platform-browser';
import { Injectable, EventEmitter } from '@angular/core';

@Injectable()
export class ResizeService {

  public onResize$ = new EventEmitter<{ width: number; height: number; }>();

  constructor(eventManager: EventManager) {
    eventManager.addGlobalEventListener('window', 'resize',
      e => this.onResize$.emit({
        width: e.target.innerWidth,
        height: e.target.innerHeight
      }));
  }
}

Usage:

import { Component } from '@angular/core';
import { ResizeService } from './resize-service';

@Component({
  selector: 'my-component',
  template: `{{ rs.onResize$ | async | json }}`
})
export class MyComponent {
  constructor(private rs: ResizeService) { }
}

Is there a way to reset IIS 7.5 to factory settings?

There are automatic backup under %systemdrive%\inetpub\history but it may not help much if you already made lots of changes.

http://blogs.iis.net/bills/archive/2008/03/24/how-to-backup-restore-iis7-configuration.aspx

You will have to regularly back up manually using appcmd.

If you try to reinstall IIS, please first uninstall IIS and WAS via Add/Remove Programs, and then delete all existing files under C:\inetpub and C:\Windows\system32\inetsrv directories. Then you can install again cleanly.

WARN: beginners on IIS are not recommended to execute the steps above without a full backup of the system. The steps should be executed with caution and good understanding of IIS. If you are not capable of or you have doubt, make sure you open a support case with Microsoft via http://support.microsoft.com and consult.

add new row in gridview after binding C#, ASP.net

protected void TableGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowIndex == -1 && e.Row.RowType == DataControlRowType.Header)
   {
      GridViewRow gvRow = new GridViewRow(0, 0, DataControlRowType.DataRow,DataControlRowState.Insert);
      for (int i = 0; i < e.Row.Cells.Count; i++)
      {
         TableCell tCell = new TableCell();
         tCell.Text = "&nbsp;";
         gvRow.Cells.Add(tCell);
         Table tbl = e.Row.Parent as Table;
         tbl.Rows.Add(gvRow);
      }
   }
}

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

This worked for me, source: here

I had this error and it wasn't related with the DB constrains (at least in my case). I have an .xsd file with a GetRecord query that returns a group of records. One of the columns of that table was "nvarchar(512)" and in the middle of the project I needed to changed it to "nvarchar(MAX)".

Everything worked fine until the user entered more than 512 on that field and we begin to get the famous error message "Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints."

Solution: Check all the MaxLength property of the columns in your DataTable.

The column that I changed from "nvarchar(512)" to "nvarchar(MAX)" still had the 512 value on the MaxLength property so I changed to "-1" and it works!!.

Display image as grayscale using matplotlib

I would use the get_cmap method. Ex.:

import matplotlib.pyplot as plt

plt.imshow(matrix, cmap=plt.get_cmap('gray'))

Undefined reference to main - collect2: ld returned 1 exit status

In my case it was just because I had not Saved the source file and was trying to compile a empty file .

How to check whether particular port is open or closed on UNIX?

Try (maybe as root)

lsof -i -P

and grep the output for the port you are looking for.

For example to check for port 80 do

lsof -i -P | grep :80

instanceof Vs getClass( )

I know it has been a while since this was asked, but I learned an alternative yesterday

We all know you can do:

if(o instanceof String) {   // etc

but what if you dont know exactly what type of class it needs to be? you cannot generically do:

if(o instanceof <Class variable>.getClass()) {   

as it gives a compile error.
Instead, here is an alternative - isAssignableFrom()

For example:

public static boolean isASubClass(Class classTypeWeWant, Object objectWeHave) {

    return classTypeWeWant.isAssignableFrom(objectWeHave.getClass())
}

Add st, nd, rd and th (ordinal) suffix to a number

I strongly recommend this, it is super easy and straightforward to read. I hope it help?

  • It avoid the use of negative integer i.e number less than 1 and return false
  • It return 0 if input is 0
function numberToOrdinal(n) {

  let result;

  if(n < 0){
    return false;
  }else if(n === 0){
    result = "0";
  }else if(n > 0){

    let nToString = n.toString();
    let lastStringIndex = nToString.length-1;
    let lastStringElement = nToString[lastStringIndex];

    if( lastStringElement == "1" && n % 100 !== 11 ){
      result = nToString + "st";
    }else if( lastStringElement == "2" && n % 100 !== 12 ){
      result = nToString + "nd";
    }else if( lastStringElement == "3" && n % 100 !== 13 ){
      result = nToString + "rd";
    }else{
      result = nToString + "th";
    }

  }

  return result;
}

console.log(numberToOrdinal(-111));
console.log(numberToOrdinal(0));
console.log(numberToOrdinal(11));
console.log(numberToOrdinal(15));
console.log(numberToOrdinal(21));
console.log(numberToOrdinal(32));
console.log(numberToOrdinal(43));
console.log(numberToOrdinal(70));
console.log(numberToOrdinal(111));
console.log(numberToOrdinal(300));
console.log(numberToOrdinal(101));

OUTPUT

false
0
11th
15th
21st
32nd
43rd
70th
111th
300th
101st